Sub topic 7
Keeping the Application Tier Stateless
This chapter assumes you know EC2, VPC subnets, and IAM, and that you have read the earlier chapters on failure domains and multi-AZ subnet layout. Here you will see why a stateless application tier is a precondition for surviving the loss of an Availability Zone (AZ).
Why state breaks availability
An instance is stateful when it holds data that no other instance has. Examples are a user session in process memory, an uploaded file on local disk, or a counter in a local cache. If that instance or its AZ fails, the data is gone. A load balancer also cannot send the user's next request to just any healthy instance, because only one instance can answer it correctly.
A stateless instance keeps nothing that matters between requests. Any instance can serve any request, and any instance can be replaced at any time. This is what lets an Auto Scaling group (covered in a later chapter) add, remove, and replace instances across AZs without users noticing.
Where state goes instead
Move each kind of state to a service that is already replicated across AZs.
| State | Common mistake | Better home |
|---|---|---|
| User sessions | In-memory or sticky sessions | ElastiCache with a replica in another AZ, DynamoDB, or a signed token such as a JWT |
| Uploaded files | Local disk or instance store | Amazon S3, or EFS for shared file systems |
| Application data | Database on the instance | RDS Multi-AZ, Aurora, or DynamoDB |
| Configuration and secrets | Baked into files by hand | SSM Parameter Store or Secrets Manager |
| Background jobs | In-process queue | Amazon SQS |
Instance store and a plain EBS volume are zonal. An EBS volume lives in one AZ and cannot be attached to an instance in another, so treat both as scratch space.
A session store in practice
The following Python function keeps a session in DynamoDB instead of memory. Any instance in any AZ can read it. DynamoDB replicates data across multiple AZs in a Region.
import time
import uuid
import boto3
table = boto3.resource("dynamodb").Table("web-sessions")
def create_session(user_id: str, ttl_seconds: int = 3600) -> str:
session_id = str(uuid.uuid4())
table.put_item(
Item={
"session_id": session_id,
"user_id": user_id,
"expires_at": int(time.time()) + ttl_seconds,
}
)
return session_id
def get_session(session_id: str) -> dict | None:
response = table.get_item(Key={"session_id": session_id})
item = response.get("Item")
if item and item["expires_at"] > int(time.time()):
return item
return NoneEnable DynamoDB time to live (TTL) on the expires_at attribute so expired sessions are deleted automatically. The table needs session_id as its partition key.
What the request path looks like
Common errors
- Writing logs only to local disk. Ship them to CloudWatch Logs, or you lose them with the instance.
- Storing the only copy of a generated report on local disk.
- Running cron jobs on every instance, which causes duplicate work. Use EventBridge Scheduler or a single queue consumer.
- Relying on a manually configured server. Build an AMI or a launch template with user data so a replacement instance starts identical.
Exercise
A web tier keeps shopping carts in each instance's memory, and the load balancer uses sticky sessions. An AZ fails. What happens to users in that AZ, and what change fixes it?
Show answer
Their instances are lost, and so are their carts, because the only copy lived in memory on those instances. The load balancer sends them to surviving instances that have no cart data. Move carts to a shared, multi-AZ store such as DynamoDB or ElastiCache with a replica in another AZ, so any instance can read them. Sticky sessions can then be turned off.