Sleeping Stages

A staging or test stage usually runs all night and all weekend for nobody. With sleep, Stacktape stops the stage outside the hours you set and starts it again in time, or when nobody uses it and again when someone opens it. You can also put a stage to sleep and wake it by hand.

A sleeping stage costs less, not nothing. Load balancers, NAT gateways, the storage of stopped databases and everything billed by use keep billing. stacktape stage status lists what still bills for your stage.

sleep is for stages that are not production. A stage that counts as production ignores it and stays awake, so one config can deploy both your staging and your production stage.

Turning it on

sleep:
stage === 'staging'
? { awakeHours: { timezone: 'Europe/Prague', from: '08:00', to: '19:00' } }
: undefined

The TypeScript example sets sleep for staging only. The YAML example sets it for every stage the config deploys, and the stages that count as production ignore it: see Which stages may sleep.

Deploy the stage. From then on Stacktape checks every 5 minutes whether the stage should be awake or asleep. The stage is up at from: Stacktape starts the wake early enough, 8 to 12 minutes before (see How long a wake takes). It goes to sleep up to 5 minutes after to.

OptionWhat it does
awakeHours.timezoneThe time zone of from and to, as an IANA name such as Europe/Prague.
awakeHours.from, awakeHours.toWhen the stage is up and when it goes to sleep, as HH:MM on a 24-hour clock. A to earlier than from is on the next day. to: '24:00' is the end of the day. The awake hours must last at least 15 minutes: a shorter window could pass between two checks.
awakeHours.daysThe days the awake hours start on. Monday to Friday when you leave it out, so the stage sleeps through the weekend.
whenIdleSleep when nobody uses the stage, and wake when someone opens it. See When nobody uses it.
keepAwakeNames of resources that are never stopped. See Work that runs at night.

Without awakeHours or whenIdle, nothing happens by itself: the stage sleeps and wakes only when you say so.

A deploy of a non-production stage without sleep prints a tip under its cost estimate when sleeping outside 08:00–19:00 UTC on weekdays would save at least $10 a month. sleep: false hides it.

Which stages may sleep

A stage sleeps only when it is clearly not production:

  • its config says stageType: non-production, or
  • it was created as a non-production stage in the Stacktape Console, or
  • its name says so: staging, dev, test, preview, pr-123 and similar.

A name that says nothing, such as main, counts as production. For such a stage, set stageType: non-production in stackConfig.

On a stage that counts as production, the deploy leaves sleep out and says so:

Sleep: off for stage `production`, which counts as production because of its name. Stacktape never puts production to sleep. If it isn't, set `stackConfig.stageType: non-production`.

The stage gets no sleep at all: no schedule, no waker, and stacktape stage sleep refuses it. If the stage slept before it became production, that deploy wakes it and removes its sleep.

A rollback cannot leave anything out, because it restores a release as it was deployed. So stacktape rollback to a release that used sleep is refused on a stage that counts as production now. If CloudFormation itself goes back to such a release (a failed deploy rolls back, or stacktape cf:rollback), Stacktape marks the stage and keeps it awake until the next deploy.

Daylight saving time

The hours follow the clock people in the time zone see. On the day the clocks go forward, a time that does not exist takes effect that much later: 02:30 becomes 03:30. On the day the clocks go back, a time that happens twice takes effect the first time.

When nobody uses it

A preview or test stage is often used for an hour and then forgotten. With whenIdle, the stage goes to sleep after a while without use, and wakes when someone opens its address or work arrives in a worker's queue.

stackConfig:
  sleep:
    whenIdle:
      afterMinutes: 20

whenIdle: true waits 30 minutes. The shortest wait is 10 minutes.

A preview deploy turns whenIdle on by itself when the config leaves it out: see Sleep and Spot for previews.

What counts as use

Stacktape's check looks every 5 minutes. The stage counts as unused when, for the whole of afterMinutes:

  • fewer than 3 requests reached your app and got an answer other than a 4xx (such as a 404) at its HTTP APIs, application load balancers (internal ones too), function URLs and CDNs, apart from the probes of the uptime checks in your config. So a page load or a dashboard keeps the stage awake, and the stray requests internet scanners send to every public address do not,
  • no work waits in the SQS queues its services connect to (connectTo), and none of them received or deleted a message: a worker that finished a job a minute ago was in use,
  • nobody deployed or woke it. A deploy and a wake start the count again. A deploy or a wake by hand also keeps the stage awake for 2 hours.

The check counts requests up to the moment it looks, as soon as CloudWatch has published them, which takes a minute or two. A request in the last minute before the stage goes to sleep can be missed; the next one wakes the stage.

If the check cannot read the request counts or the queues, for example because CloudWatch did not answer, the stage stays awake. A stage is put to sleep only on numbers that show it is unused.

Uptime monitors and bots

  • While the stage is awake, the probes of the uptime checks in your config count as no traffic. Other requests your app answers count as use: a dashboard that polls the stage every 30 seconds keeps it awake, and so does an outside monitor or a bot that gets an answer. To watch a stage that should sleep, use an uptime check in its config: it does not fail while the stage sleeps (see Alarms and uptime checks).
  • While the stage sleeps, these requests get an answer but do not wake it: uptime monitors and bots (known names in the User-Agent, and any User-Agent with bot, crawler, spider or monitor in it), HEAD requests, and requests that name a load balancer by its IP address. Internet scanners use those addresses all the time.
  • A load balancer's AWS address (*.elb.amazonaws.com) wakes the stage when it is an address the stage gives out: for an internal load balancer, the only address it has, and for a load balancer with custom domains or certificates, the address in its domain parameter. For a load balancer with a Stacktape domain, people and functions use that domain, and a request to the AWS address does not wake the stage.

A client this list does not know wakes the stage like a person. The stage then goes back to sleep after afterMinutes.

With awake hours

You can use both. Inside the awake hours the stage stays awake whatever the traffic. Outside them it does not go to sleep at the minute the hours end: it sleeps once nobody has used it for afterMinutes, and a visit or a queue message wakes it again.

stackConfig:
  sleep:
    awakeHours:
      timezone: Europe/Prague
      from: '08:00'
      to: '19:00'
    whenIdle: true

All the rules together, the first that applies decides:

  1. A production stage is always awake.
  2. A wake by hand or a deploy keeps the stage awake for 2 hours.
  3. A sleep by hand keeps it asleep until a visit, a queue message, a wake, a deploy, or the start of the awake hours.
  4. Inside the awake hours it is awake, from the start of the wake that has it up at from. A stage that is already awake within 30 minutes of that wake stays awake: a sleep would end before it saved anything.
  5. With whenIdle, a visit or a queue message wakes it, and it sleeps once nobody uses it.
  6. Without whenIdle, it sleeps outside the awake hours.

Opening a sleeping stage

While the stage sleeps, its HTTP API routes and load balancer rules lead to a small function, the waker, instead of to your services. The waker asks for a wake and answers right away:

  • A page in a browser gets a short page that says the stage is waking up and how long that takes. The page reloads every 10 seconds and shows your application as soon as it runs. A browser says whether it loads a page or runs a fetch (Sec-Fetch-Mode). Where that header is missing, any GET whose Accept header allows HTML gets this page, and so does a GET without Accept, which is what arrives through a CDN that forwards only some headers.

  • Every other request gets 503 Service Unavailable with Retry-After, the standard answer for "try again in a moment", and a JSON body:

    { "stage": "waking", "message": "This stage is waking up. That takes about 6 minutes, because its database has to start.", "retryAfterSeconds": 30, "expectedSeconds": 330 }

    expectedSeconds is how long the stage's last wake took, or the usual time for its kind of stage. stage is asleep when the request did not wake the stage, for example a request from an uptime monitor.

Both answers carry Cache-Control: no-store and X-Stacktape-Stage: waking (or asleep).

A frontend on another origin can read the answer: it allows any origin, with or without credentials, and exposes Retry-After and X-Stacktape-Stage. A preflight (OPTIONS) gets 204. So a frontend whose API sleeps can say that the API is waking up instead of failing with a CORS error:

// Calls the API. While the stage wakes, shows how long it takes and tries again.
async function callApi(url, init) {
  const response = await fetch(url, init);
  if (response.status !== 503) return response;
  const waking = await response.clone().json().catch(() => null);
  if (!waking?.stage) return response;
  showNotice(`Waking up, about ${Math.ceil(waking.expectedSeconds / 60)} minutes`);
  await new Promise((resolve) => setTimeout(resolve, waking.retryAfterSeconds * 1000));
  return callApi(url, init);
}

The example reads the body, not the X-Stacktape-Stage header: an HTTP API with the cors setting answers CORS itself and exposes only the headers in its exposedResponseHeaders. If the stage has a Stacktape CDN, Stacktape also tells the CDN not to keep a 503, so nobody gets the waking page from the cache after the stage is awake.

The waker does not pass anything on. A POST or any other write that arrives while the stage sleeps gets a 503 and is dropped; the client must send it again. The waker never redirects, and it logs neither the body nor the headers of a request. Authorizers on your HTTP API routes stay in front of the waker: a request they refuse does not wake the stage.

However many requests arrive, the stage gets one wake. A request that arrives while the stage is still going to sleep stops the sleep and wakes it again. If a wake fails, the page says so, and the next page load starts another attempt.

The waker answers at most 5 requests at once when the account has room to reserve that much Lambda concurrency, so a flood of requests to a sleeping stage cannot take concurrency from the account's other functions. A new AWS account often cannot reserve any; the waker then shares the account's concurrency like any function.

When the services answer their health checks, the routes lead to them again. A deploy of a sleeping stage wakes it and puts the routes back before it changes anything.

Limits while the stage sleeps:

  • A WebSocket connection cannot open. Clients that reconnect get through once the stage is awake.
  • Behind a load balancer, a request with a body larger than 1 MB is refused by the load balancer.
  • A service behind a network load balancer cannot be woken by a visit. Stacktape refuses whenIdle for it unless it is in keepAwake.
  • Function routes keep answering. Only the routes and rules that lead to a sleeping container service lead to the waker. If someone changed such a route or rule outside Stacktape, the service keeps running, because a visit could not wake it.

Work that arrives while it sleeps

When a message arrives in a queue that a sleeping service connects to, the check wakes the stage within 5 minutes and the service picks the message up. A delayed message wakes the stage too, and so does a message that arrives while the stage is still going to sleep: the sleep stops.

A message waits up to 5 minutes for the check, and the wake takes a few minutes more. So Stacktape refuses any sleep, scheduled, idle or by hand, when a queue that a sleeping service reads keeps messages for less than an hour (messageRetentionPeriodSeconds below 3600). See Queues.

Fargate Spot

A stage whose services run on Fargate Spot (useSpotInstances) can fail to wake while AWS has no Spot capacity in the region. The waking page and stacktape stage status say so, and Stacktape keeps trying until AWS has capacity. Stacktape does not move the services to on-demand capacity by itself in this version.

What the check costs

While the stage is awake, the check reads CloudWatch request counts every 5 minutes: three per load balancer (answers with a 2xx, 3xx and 5xx status), two per HTTP API, function URL and CDN (all requests and those with a 4xx), and two message counts per queue. At CloudWatch's list price that is about $0.09 a month for each count. Reading the queues' depths costs a fraction of a cent. The waker costs nothing while nobody opens a sleeping stage, and a few Lambda invocations when someone does.

What stops

ResourceWhat happens
Containers on Fargate with rolling updates (web-service, private-service, worker-service, multi-container-workload)The number of tasks goes to 0. Scaling is suspended, so no scaling rule starts tasks during the sleep. On wake the earlier task count and scaling settings come back. A service whose scaling cannot be suspended keeps running.
Aurora Serverless v2 with minCapacity: 0 (the default)Not stopped by Stacktape. It pauses by itself about 5 minutes after the last connection closed, and resumes on the next connection.
Other Aurora databases, and RDS instancesStopped.
The stage's own NAT instances (nat: ec2 or ha-ec2)Stopped.
A bastionStopped.

Stacktape stops the containers first, and the databases and NAT instances once the last container has stopped: a task that is stopping still finishes its requests. A task that is still stopping 10 minutes after the sleep began no longer holds it back. On wake the order is reversed: databases and NAT instances first, then the containers. A NAT instance counts as started once it forwards traffic, not when it boots.

A service that keeps running keeps what it uses running too: the databases it connects to with connectTo and the NAT instances.

What keeps billing

  • Load balancers and NAT gateways. AWS bills them by the hour, used or not.
  • Storage and backups of a stopped database. Only the database's compute stops.
  • The public IP address of a stopped NAT instance.
  • Redis, OpenSearch and Kafka. Sleep does not stop them.
  • Containers on EC2 instances (instanceTypes) and containers with gradual deployments (deployment). Sleep leaves them running in this version, and with them the databases they connect to and the NAT instances.
  • A database with read replicas. AWS cannot stop it.
  • Everything billed by use: functions, buckets, queues, logs, CDN traffic. These cost what they are used.

stacktape stage status shows this list for your stage, with an estimate of the monthly amount where the charge is fixed.

The cost estimate of a deploy and stacktape cost count what sleep stops only for the awake hours. See a stage that sleeps.

AWS starts a stopped database again after 7 days. Stacktape notices at its next check and stops the database again. It changes nothing else then: a service you started by hand keeps running.

AWS applies maintenance and takes automated backups only while a database runs. If the database's maintenance window falls into the hours the stage sleeps, move it into the awake hours with preferredMaintenanceWindow on the database (the window is in UTC).

Work that runs at night

Functions, schedules and queue triggers are not stopped. AWS bills a function only for the time it runs, so stopping one saves nothing.

With whenIdle, functions, batch jobs and web apps on Lambda keep answering while the stage sleeps, and a request to them never wakes it. So everything they connect to with connectTo keeps running, and so do the stage's NAT instances when functions in the VPC reach the internet through them. The deploy says which resources that keeps running, and stacktape stage status lists them with the reason.

With awakeHours alone, a function that runs while the stage sleeps finds its database stopped and fails. If a scheduled function or a queue consumer must work at night, list it in keepAwake:

stackConfig:
  sleep:
    awakeHours:
      timezone: Europe/Prague
      from: '08:00'
      to: '19:00'
    keepAwake:
      - nightlyReport

A resource in keepAwake is never stopped. Neither is anything it connects to with connectTo, nor the stage's NAT instances. In the example, the database that nightlyReport connects to stays up all night, and it bills all night.

Queues

Messages that arrive in an SQS queue while the service that reads it sleeps wait in the queue until the stage wakes. SQS deletes a message once it is older than the queue's retention (messageRetentionPeriodSeconds, 4 days by default). Stacktape watches every queue that a sleeping service connects to with connectTo, and wakes the stage before its oldest message gets that old, also outside the awake hours and after a sleep by hand. When messages wait in a queue but CloudWatch has no age for them, which happens when nobody touched the queue for six hours, Stacktape wakes the stage too. The stage then stays awake for at least 30 minutes, and as long as old messages wait.

Stacktape wakes the stage early enough to have it running before a message expires: twice the time the stage's last wake took, plus 15 minutes, plus 5 % of the retention. A queue that keeps messages for a shorter time than that wakes the stage as soon as a message waits.

A message that arrives just after a check waits up to 5 minutes for the next one, and the wake takes a few minutes more. So the deploy refuses a sleep when a queue that a sleeping service reads keeps messages for less than an hour (messageRetentionPeriodSeconds below 3600). List the service in keepAwake, so it keeps running and reads every message at once, or raise the queue's retention to at least an hour.

When a schedule keeps the stage asleep for longer than a queue keeps its messages, the deploy says so. Nothing is lost, but the stage then wakes outside its awake hours. To avoid that, raise the queue's retention or shorten the sleep.

With whenIdle, any message wakes the stage at the next check, not only an old one: see Work that arrives while it sleeps.

Sleeping and waking by hand

stacktape stage sleep --stage staging --region eu-west-1
stacktape stage wake --stage staging --region eu-west-1
stacktape stage status --stage staging --region eu-west-1
  • stage wake wakes the stage now and waits until it is up. The stage then stays awake for 2 hours, whatever the hours say, and follows awakeHours again after that.
  • stage sleep puts the stage to sleep now. It stays asleep until a wake, a deploy, or the wake that has it up when the awake hours start next.
  • stage status shows whether the stage is awake or asleep, since when and why (by the hours, by hand, or because nobody used it), what woke it last and how long that took, what keeps billing, and when it changes next. If the record of what the sleep stopped is missing, it says so, and the stage check reports it to the Stacktape Console once an hour.

The newest of a sleep and a wake by hand wins. All three commands print JSON with --agent.

How long a wake takes

Measured in eu-west-1 on small test stages, from the command to the first answer of the service:

What wakesTime
Containers only1 to 2 minutes
Containers, a NAT instance and a stopped RDS PostgreSQL instance (db.t4g.micro)4.5 to 5.5 minutes
Containers and a stopped Aurora cluster6 minutes or more. Starting the cluster alone took 5.5 minutes
A paused Aurora Serverless v2 databaseResumes on the first connection, in about 15 seconds according to AWS

With whenIdle, from opening the address to the application's first answer:

What wakesTime
Containers behind an HTTP API1.5 to 2 minutes (75 to 113 seconds in 6 wakes)
Containers behind a load balancer, and a stopped RDS PostgreSQL instance (db.t4g.micro)4.5 to 6 minutes (277 to 340 seconds in 6 wakes)
A message in a sleeping worker's queueUp to 5 minutes until the next check, then 1.5 minutes until the worker processed it

With afterMinutes: 10, a stage that nobody used went to sleep 15 minutes after the deploy that created it: the 10 minutes, the 2 minutes CloudWatch needs to publish request counts, and up to 5 minutes until the next check. After a later deploy, the deploy holds it awake for the same 10 minutes, counted from the start of the deploy.

Going to sleep took 1.5 minutes with containers only and 5 to 8 minutes with a database.

The stage is up at from

Stacktape starts the wake of the awake hours early. It starts it as long before from as the stage's last wake took, plus 6 minutes: the check that starts it runs up to 5 minutes after the planned time, and one minute is kept in reserve. Before the first wake it counts the usual wake: 1 min 40 s with containers only and 5 min 20 s with a stopped database. Rounded up to whole minutes, the wake starts 8 minutes before from, or 12 with a database.

  • A last wake that was quicker than usual does not move the next one later. It was a stage that had not finished going to sleep.
  • A last wake longer than 20 minutes counts as 20, for example one that waited for Fargate Spot capacity.
  • Days without awake hours get no wake.

stacktape stage status shows both times: Next: it is up at Wed 2 Dec 08:00 (Europe/Prague), when its awake hours start. Waking starts at 07:48. A price estimate counts the early wake too: see Cost estimates.

Alarms and uptime checks

A sleeping stage looks broken from the outside: its databases send no metrics, and the waker answers requests with a 503. Stacktape knows when the stage sleeps and keeps that out of your alerts.

  • Alarms of the stage are not sent while it goes to sleep, sleeps or wakes: not to the channels in its config, and not to the Stacktape Console. Without this, each database alarm would fire a few minutes after the sleep stops the database, and an error-rate alarm would fire whenever a request got the waker's 503. When such an alarm recovers after the wake, the recovery is not sent either. The Console keeps a firing it received during sleep in the alarm history, marked as not sent.
  • Uptime checks in the config count a probe that gets the waker's answer, or that fails while the stage sleeps, neither as a failure nor as a success. The check keeps the status it had before the sleep, and the uptime charts show only the time the stage was awake.

A sleep or a wake that failed, or that has been going on for more than 30 minutes, counts as awake: the stage may serve errors, so its alarms and failed probes are sent. Stacktape's own alerts, such as a failed wake or a spend alert, are always sent.

An alarm that still fires when the stage wakes is sent only once it recovers and fires again. The alarm's state in CloudWatch shows it as firing all along.

The Console learns that the stage sleeps from the stage check, which reports every change within 5 minutes. A stage whose stage check has not reported for 3 hours counts as awake, so its alarms and uptime checks are sent as usual.

Deploys, rollbacks and deletes

A deploy, a rollback or a dev session on a sleeping stage wakes the stage first. The CLI says so and waits until the databases, the NAT instances and the bastion run and the services have their tasks and scaling back. It does not wait for the services to be healthy: a stage that went to sleep with a service that does not start stays deployable, and the deploy can be the fix. If the wake fails, the command stops before it changes the stack, because CloudFormation fails on a stopped database it has to change. Run it again: it continues the wake. To go on anyway, see STP_STAGE_FORCE. After every deploy the stage stays awake for 2 hours, counted from the start of the deploy, also when the stage was awake already. With whenIdle, it stays awake for afterMinutes instead (30 minutes by default), or longer when something held it awake longer already.

The one exception is the first deploy that turns sleep on: outside the awake hours, the stage goes to sleep within 5 minutes of it.

Commands that connect to something a sleep stops check first: bastion session, bastion tunnel, query sql, query redis through a bastion, container exec, container session, script run and deployment-script run. When the stage is asleep, going to sleep or waking, they say which resource is stopped and print the stacktape stage wake command. In a terminal they offer to wake the stage, wait for it and then go on. A resource in keepAwake never stops them.

stacktape delete on a sleeping stage works. AWS deletes an Aurora database only while it runs, so the CLI starts a stopped Aurora cluster first, which takes several minutes, and says so. Everything else stays asleep and stays on record until CloudFormation has the delete, so a delete that stops earlier can be run again. To bring the stage back instead, run stacktape deploy. stage wake works only after a delete that stopped by itself, for example on a failing hook. After a delete or another command that was killed, the wake cannot take over the killed command's lock and fails after 40 minutes.

Removing sleep from the config wakes the stage and then removes the feature.

Everyone who works on the stage needs Stacktape 4.1.0 or newer, which knows sleep; the deploy that turns sleep on says so once. Update with stacktape upgrade, and pin 4.1.0 or newer in CI that installs a fixed version. An older 4.x version refuses a config that contains sleep. With a config that does not contain it, its deploy, rollback and delete fail on their first write with an access-denied error, before anything changes. The Stacktape Console also refuses a deploy, rollback or delete of a sleeping stage from an older version signed in to it, Stacktape 3 included, and says which version to install. Nothing stops an older version's dev or cf:rollback: do not run them against a stage that uses sleep.

How it works

A deploy with sleep adds two small functions to the stack: a check that runs every 5 minutes, and a workflow that stops or starts the stage's resources. With whenIdle and an HTTP API or a load balancer, a third one is added: the waker, which may only record a wake and start the workflow of its own stack. They run in your AWS account, with a role that reaches only this stack's resources, and need neither the Stacktape Console nor your machine.

Before it changes anything, the workflow writes down what was there: the number of tasks, the scaling settings, the size of each instance group. A wake puts back exactly that, and only where the value is still the one the sleep set. If you scaled a service by hand while the stage slept, your number stays.

If a sleep or a wake fails half-way, the next check continues it. When AWS gives no clear answer to a change, the run stops, and the next one first looks at what is there. A stage connected to the Stacktape Console also gets an alert in the Console and its alert channels, and a second message when the problem is gone. So does a stage whose check keeps failing.

The functions write two CloudWatch metrics to your account, in the namespace Stacktape/Cost with the dimension Stack: AsleepSeconds (time asleep) and WakeSeconds (how long each wake took). The stage's state, including the names of its resources, is in the stack's deployment bucket. Nothing else leaves the account.

A stage with sleep cannot be deployed to me-south-1, where AWS does not offer the durable functions the workflow runs on.