Sub topic 7
Keeping the application tier stateless
This chapter assumes you can launch EC2 instances behind an Application Load Balancer (ALB) and read basic Python and the AWS CLI. The earlier chapters on failure domains and load balancing are also assumed. Here you will learn why the application tier must hold no unique data, where each kind of state should live instead, and which mistakes quietly undo the design.
Why state decides whether an AZ failure hurts
State is any data an instance holds that other instances do not have, and that you would miss if the instance vanished. Examples are a login session in process memory, an uploaded file on the local disk, or a counter in a variable.
A zonal failure removes every instance in one Availability Zone at once. If those instances hold unique state, that state is lost. Users in those sessions are logged out, uploads disappear, and in-flight work is dropped. If the instances are stateless, the surviving instances in other AZs can serve any request, because they can reach the same data.
Statelessness also makes the rest of the plan work. Auto Scaling can terminate and replace instances freely. The load balancer can send any request to any target. Rolling deployments need no special handling.
A stateless tier does not mean the system has no state. It means the state lives in services built to be multi-AZ, and the instances are interchangeable.
Where each kind of state should go
Move each kind of state to a store whose failure scope is wider than one instance. Prefer stores that are regional or Multi-AZ.
| State | Common mistake | Better home |
|---|---|---|
| User sessions | Memory or local files | DynamoDB, or ElastiCache with a replica in another AZ |
| Uploaded files | Local disk | S3 (regional) |
| Shared files that need a file system | One instance's EBS volume | EFS (regional) or FSx |
| Business records | Local SQLite or local database | RDS Multi-AZ or Aurora |
| Configuration and secrets | Baked into the AMI or edited on the host | Systems Manager Parameter Store or Secrets Manager |
| Logs and metrics | Files on local disk | CloudWatch Logs, shipped continuously |
| Background work | In-process queues | SQS |
An EBS volume lives in a single AZ. If you keep primary data on one, you have recreated the single point of failure you were removing. Snapshots and restore help with recovery, but they are not a substitute for a shared store.
Sessions: a worked example
Sessions are the most common source of hidden state. Many web frameworks default to in-memory sessions. With two instances, a user who logs in on one instance appears logged out when the load balancer sends the next request to the other.
First, create a session table with a time-to-live (TTL) attribute. TTL tells DynamoDB to delete expired items automatically.
aws dynamodb create-table \
--table-name web-sessions \
--attribute-definitions AttributeName=session_id,AttributeType=S \
--key-schema AttributeName=session_id,KeyType=HASH \
--billing-mode PAY_PER_REQUEST
aws dynamodb wait table-exists --table-name web-sessions
aws dynamodb update-time-to-live \
--table-name web-sessions \
--time-to-live-specification Enabled=true,AttributeName=expires_atThen store sessions in it instead of in memory. This module has no framework dependency, so any web handler can call it.
import json
import secrets
import time
import boto3
TABLE_NAME = "web-sessions"
TTL_SECONDS = 1800
table = boto3.resource("dynamodb").Table(TABLE_NAME)
def create_session(data: dict) -> str:
"""Store session data and return the ID to put in a cookie."""
session_id = secrets.token_urlsafe(32)
table.put_item(
Item={
"session_id": session_id,
"data": json.dumps(data),
"expires_at": int(time.time()) + TTL_SECONDS,
}
)
return session_id
def load_session(session_id: str):
"""Return the session data, or None if missing or expired."""
response = table.get_item(Key={"session_id": session_id}, ConsistentRead=True)
item = response.get("Item")
# TTL deletion can lag by hours, so check expiry in code as well.
if item is None or item["expires_at"] <= time.time():
return None
return json.loads(item["data"])
def delete_session(session_id: str) -> None:
table.delete_item(Key={"session_id": session_id})The expiry check in load_session matters. DynamoDB removes expired items in the background, and that can happen well after the timestamp passes. Without the check, an expired session could still be accepted.
DynamoDB is regional, so it survives the loss of an AZ without any action from you. ElastiCache works too, but only if you enable a replica in a second AZ with automatic failover. A single-node cache is a zonal single point of failure.
An alternative is to put the session in a signed, encrypted cookie, so the server stores nothing. This works for small sessions. Keep the signing key in Secrets Manager so every instance uses the same one.
Sticky sessions are a crutch
ALB stickiness binds a client to one target with a cookie. It can make an in-memory design appear to work, but it fails exactly when you need it. If the target's AZ fails, the stickiness cookie points at a dead target. The load balancer picks a new one and the session is gone.
Stickiness also skews load. Heavy users stay pinned to one instance, so one AZ can carry more traffic than the others. If you have moved state out of the instances, turn stickiness off:
aws elbv2 modify-target-group-attributes \
--target-group-arn "$TARGET_GROUP_ARN" \
--attributes Key=stickiness.enabled,Value=falseOther hidden state
Sessions are only the obvious case. Look for these as well:
- Local caches. A cache of database results on each instance is fine if stale or missing entries are harmless. It is a problem if correctness depends on the cache being identical on every instance.
- Local scheduled jobs. A cron entry on every instance runs the job once per instance. A cron entry on only one instance stops running when that instance dies. Use Amazon EventBridge Scheduler to invoke a job, or an SQS queue that workers pull from, so exactly one worker takes each unit of work.
- Instance-specific identity. Do not use the hostname or instance ID as a key for data. A replacement instance gets a new one.
- In-progress work. A request that takes minutes and keeps progress in memory is lost when the instance stops. Write progress to a durable store, or split the work into steps on a queue.
- Local logs. A zone failure takes unshipped logs with it, and you need them most then. Ship them off the instance as they are written.
- Configuration drift. If an operator edits a file on a running instance, a replacement will not have that change. Treat instances as immutable and change the launch template instead.
Make retries safe
When an instance disappears mid-request, the client or load balancer retries, and the new instance sees the request again. If the first attempt already charged a card or created a record, the retry may repeat it.
Make write operations idempotent, which means repeating them has the same result as doing them once. A common technique is for the client to send a unique request ID. The server records it with a conditional write and rejects duplicates:
import boto3
from botocore.exceptions import ClientError
dynamodb = boto3.resource("dynamodb")
requests_table = dynamodb.Table("processed-requests")
def claim_request(request_id: str) -> bool:
"""Return True if this request ID is new, False if already processed."""
try:
requests_table.put_item(
Item={"request_id": request_id},
ConditionExpression="attribute_not_exists(request_id)",
)
return True
except ClientError as err:
if err.response["Error"]["Code"] == "ConditionalCheckFailedException":
return False
raiseThis sketch assumes a processed-requests table keyed on request_id. In production, claim the ID and perform the work so that a crash between the two does not lose the request, for example by writing the result in the same transaction.
Shutting down cleanly
Instances also leave during normal operations: scale-in, deployments, and Spot interruptions. Handle them the same way as a failure, with a little more grace.
- Set the target group's deregistration delay to match your longest normal request. The default is 300 seconds, which is often too long and slows deployments.
- On SIGTERM, stop accepting new connections, finish in-flight requests, then exit.
- Use an Auto Scaling lifecycle hook if the instance must finish work, such as flushing a buffer, before termination.
aws elbv2 modify-target-group-attributes \
--target-group-arn "$TARGET_GROUP_ARN" \
--attributes Key=deregistration_delay.timeout_seconds,Value=60A quick test for statelessness
Run these checks before relying on the design:
- Log in, then terminate the instance that served you. You should stay logged in.
- Upload a file, then terminate the instance. The file should still be downloadable.
- Disable stickiness and send ten consecutive requests. Every one should behave the same regardless of which instance answers.
- Replace every instance with a fresh one from the launch template. Nothing should be missing.
Exercise
An application keeps shopping carts in instance memory. The team enables ALB stickiness so users stay on one instance, and runs in two AZs. An AZ fails. What happens to users whose carts were on instances in the failed AZ, and what is the fix?
Show answer
Their carts are lost. The load balancer routes them to an instance in the surviving AZ, which has no copy of the cart. Stickiness only pins a client to a target and does not replicate data. The fix is to store carts in a regional or Multi-AZ store such as DynamoDB, or ElastiCache with a replica in another AZ, then disable stickiness so any instance can serve any user.
Exercise
Why does the session code check expires_at in load_session even though the table has TTL enabled?
Show answer
DynamoDB deletes expired items in the background, and the deletion can lag well behind the expiry time. Until it happens, get_item still returns the item. The code check ensures expired sessions are rejected immediately.