Scaling an EC2 instance to zero

ProgrammingAWS

November 30, 2026 · today

I recently built a game with an online multiplayer mode, so I needed a game server. Running it all day would be wasteful when only a handful of my friends play, and only occasionally. I wanted it off when nobody is around, and back up quickly when someone opens the game.

The Solution

EC2 has no convenient scale-to-zero. An autoscaling group needs warm pools and Cloudwatch alarms to trigger scale-in and would probably still be slower than a cron job.

I did consider Runway as an option but its scale-to-zero feature watches network traffic, which never goes quiet for me because the game server holds a persistent database connection even when idle.

So I built a small controller that starts the instance on demand and stops it after 10 idle minutes:

  • A Lambda function that can track client pings and start and stop the game server
  • An Upstash Redis database to store the last activity time
  • An Eventbridge rule that triggers the Lambda every minute to check if the instance should be stopped
  • A client script
infra.ts
1 2// Redis Configuration 3const redisUrl = new sst.Secret("UPSTASH_REDIS_REST_URL"); 4 5const redisToken = new sst.Secret("UPSTASH_REDIS_REST_TOKEN"); 6 7// This is the EC2 instance that will be used to run the server 8const awsLinuxAmiId = 'ami-0532be01f26a3de55'; 9export const server = new sst.aws.Instance("Server", { 10 ami: awsLinuxAmiId, 11 instanceType: 't2.micro', 12 // ...other configuration settings (ssh keys, vpc etc.) 13}); 14 15 16// The main Lambda function - it is triggered by clients using the URL, as well as the Eventbridge schedule 17export const instanceController = new sst.aws.Function("InstanceController", { 18 handler: "functions/instance-controller.handler", 19 timeout: "10 seconds", 20 memory: "128 MB", // It is not a heavy function, so we can keep it low 21 url: { 22 // We need to allow CORS for the client to ping the function 23 cors: { allowOrigins: ["*"], allowMethods: ["POST"] }, 24 }, 25 environment: { 26 INSTANCE_ID: server.id, 27 INSTANCE_HOST: ip.publicIp, 28 UPSTASH_REDIS_REST_URL: redisUrl.value, 29 UPSTASH_REDIS_REST_TOKEN: redisToken.value, 30 }, 31 permissions: [ 32 { actions: ["ec2:DescribeInstances"], resources: ["*"] }, 33 { 34 actions: ["ec2:StartInstances", "ec2:StopInstances"], 35 resources: [server.arn], 36 }, 37 ], 38 nodejs: { install: ["@aws-sdk/client-ec2"] }, 39}); 40 41// This allows external clients to ping the Lambda function 42new aws.lambda.Permission("InstanceControllerUrl", { 43 action: "lambda:InvokeFunctionUrl", 44 function: instanceController.name, 45 principal: "*", 46 functionUrlAuthType: "NONE", 47}); 48 49// This allows the Eventbridge schedule to invoke the Lambda function URL 50new aws.lambda.Permission("InstanceControllerInvoke", { 51 action: "lambda:InvokeFunction", 52 function: instanceController.name, 53 principal: "*", 54}); 55 56// We trigger the Lambda function every minute to check if the instance should be stopped 57new sst.aws.Cron("InstanceControllerIdle", { 58 function: instanceController.arn, 59 schedule: "rate(1 minute)", 60 event: { action: "idle" }, 61}); 62

Napkin Math

A Linux t2.micro left running in us-east-1 costs $8.47 a month for compute. At 3 hours a week it costs $0.15, a saving of $8.32, or 98%.

At 100 ms and 128 MB a ping, the Lambda adds about 600 GB-seconds a month, roughly $0.01 and well inside the 400,000 GB-second free tier.

Implementing the Controller

Each client ping writes lastActivity to Upstash and then checks the instance. A stopped instance gets started. ready means the running instance answered a healthcheck with HTTP 200, and everything else gets starting.

The cron ping stops a running instance after ten idle minutes, counting from the last ping or from EC2's LaunchTime if there isn't one. It takes a 60-second lock and rereads activity first, so a ping that lands between the reads cancels the stop.

functions/instance-controller.ts
1 2import { 3 EC2Client, 4 DescribeInstancesCommand, 5 StartInstancesCommand, 6 StopInstancesCommand, 7} from "@aws-sdk/client-ec2"; 8 9const ec2 = new EC2Client({}); 10const IDLE_MS = 10 * 60 * 1000; 11 12 13export async function handler(event: { action?: string }) { 14 // Case 1: Handle the idle ping event from the Eventbridge schedule 15 if (event?.action === "idle") { 16 return handleIdle() 17 }; 18 19 // Case 2: Handle the ping call from the external client and respond with the state 20 try { 21 const result = await handlePing() 22 return { 23 statusCode: 200, 24 headers: { "content-type": "application/json" }, 25 body: JSON.stringify(result), 26 }; 27 } catch (error) { 28 console.error(error); 29 return { 30 statusCode: 500, 31 headers: { "content-type": "application/json" }, 32 body: JSON.stringify({ status: "starting", retryAfterMs: 3_000 }), 33 }; 34 } 35} 36 37// Helper functions 38 39 40/** 41 * Handle the ping call from the external client, update the last 42 * activity time and respond with the state 43 */ 44async function handlePing() { 45 await redis(["SET", "lastActivity", String(Date.now())]); 46 47 const instance = await describeInstance(); 48 if (instance.state === "running" && (await healthcheck())) { 49 return { status: "ready", retryAfterMs: 60_000 }; 50 } 51 if (instance.state === "stopped") { 52 await ec2.send( 53 new StartInstancesCommand({ InstanceIds: [process.env.INSTANCE_ID!] }), 54 ); 55 } 56 return { status: "starting", retryAfterMs: 3_000 }; 57} 58 59 60/** 61 * Determine if the instance should be stopped 62 */ 63function shouldStop( 64 instance: { state: string; runningSinceMs: number | null }, 65 lastActivityMs: number | null, 66 nowMs: number, 67) { 68 const since = lastActivityMs ?? instance.runningSinceMs; 69 return instance.state === "running" && since != null && nowMs - since >= IDLE_MS; 70} 71 72/** 73 * Handle the idle ping event from the Eventbridge schedule 74 */ 75async function handleIdle() { 76 const instance = await describeInstance(); 77 if (!shouldStop(instance, await getLastActivity(), Date.now())) return; 78 79 const locked = await redis(["SET", "stopLock", "1", "NX", "EX", "60"]); 80 if (locked !== "OK") return; 81 82 if (!shouldStop(instance, await getLastActivity(), Date.now())) return; 83 84 const fresh = await describeInstance(); 85 if (fresh.state !== "running") return; 86 await ec2.send( 87 new StopInstancesCommand({ InstanceIds: [process.env.INSTANCE_ID!] }), 88 ); 89} 90 91/** 92 * Get the last activity time from the Redis database 93 */ 94async function getLastActivity(): Promise<number | null> { 95 const result = await redis(["GET", "lastActivity"]); 96 if (typeof result !== "string" && typeof result !== "number") return null; 97 const parsed = Number(result); 98 return Number.isFinite(parsed) ? parsed : null; 99} 100 101/** 102 * Call the EC2 API to describe the instance status 103 */ 104async function describeInstance() { 105 const described = await ec2.send( 106 new DescribeInstancesCommand({ 107 InstanceIds: [process.env.INSTANCE_ID!], 108 }), 109 ); 110 const instance = described.Reservations?.[0]?.Instances?.[0]; 111 const state = instance?.State?.Name ?? "missing"; 112 return { 113 state, 114 runningSinceMs: 115 state === "running" && instance?.LaunchTime 116 ? instance.LaunchTime.getTime() 117 : null, 118 }; 119} 120 121/** 122 * Perform a healthcheck on the instance 123 */ 124async function healthcheck() { 125 try { 126 const response = await fetch(`http://${process.env.INSTANCE_HOST}/`, { 127 signal: AbortSignal.timeout(2_000), 128 }); 129 return response.status === 200; 130 } catch { 131 return false; 132 } 133} 134 135 136/** 137 * Perform a Redis command 138 */ 139async function redis(command: string[]): Promise<unknown> { 140 const endpoint = process.env.UPSTASH_REDIS_REST_URL!.replace(/\/$/, ""); 141 const response = await fetch(endpoint, { 142 method: "POST", 143 headers: { 144 Authorization: `Bearer ${process.env.UPSTASH_REDIS_REST_TOKEN}`, 145 "Content-Type": "application/json", 146 }, 147 body: JSON.stringify(command), 148 }); 149 const payload = await response.json(); 150 if (!response.ok || payload.error) { 151 throw new Error(payload.error ?? `Upstash ${response.status}`); 152 } 153 return payload.result ?? null; 154} 155 156

Client Triggers

When a player opens game, it pings the Lambda URL instead of dialing the server directly. The reply carries a status and a retryAfterMs telling the game how long to wait before pinging again. On starting the game waits and pings again, which also keeps nudging the instance to boot. On ready the server is up and the game connects to it. A failed ping is treated as starting, so a dropped request just means another try in a few seconds.

client/instance-controller.ts
1 2export async function pingInstanceController(url: string) { 3 try { 4 const response = await fetch(url, { method: "POST" }); 5 const body = await response.json(); 6 const status = response.ok && body.status === "ready" ? "ready" : "starting"; 7 const fallback = status === "ready" ? 60_000 : 3_000; 8 const retryAfterMs = 9 typeof body.retryAfterMs === "number" && body.retryAfterMs > 0 10 ? body.retryAfterMs 11 : fallback; 12 return { status, retryAfterMs }; 13 } catch { 14 return { status: "starting", retryAfterMs: 3_000 }; 15 } 16} 17

Pretty simple but it works well!