Sub topic 10
Other Local State to Move Out of Instances
This chapter assumes you know how HTTP requests and cookies work, have built a web service, and understand what a load balancer does. You have already seen that session data should not live in one instance's memory. Sessions are only one kind of local state. Any data that one instance holds and others cannot see causes the same problems: inconsistent behavior between requests, lost data when an instance is replaced, and trouble when you add instances.
Why local state breaks a stateless design
An instance is stateless when you can stop it, replace it, or add a copy of it without changing what users see. Local state breaks that rule. If instance A holds something that instance B needs, the result depends on which instance the load balancer picks.
Typical symptoms:
- A feature works on one request and fails on the next.
- A deploy or autoscaling event makes data vanish.
- Two instances make different decisions from the same input.
Common kinds of local state
| Local state | What goes wrong | Where to move it |
|---|---|---|
| In-memory cache | Each instance caches different data, so users see stale or inconsistent values | Shared cache such as Redis or Memcached |
| Uploaded files on local disk | Other instances cannot serve the file, and it is lost when the instance is replaced | Object storage such as S3 |
| Rate-limit counters in a dict | Each instance counts separately, so the real limit is multiplied by the instance count | Shared counter store |
| Background job queues in memory | Jobs are lost on restart, or run twice | Message queue or job service |
| Scheduled tasks (cron) in each instance | The task runs once per instance | One scheduler, or a distributed lock |
| WebSocket or connection registry | Instances do not know who is connected where | Shared pub/sub or presence store |
| Generated reports or temp files | A follow-up request lands on an instance without the file | Object storage with a link |
Worked example: a rate limiter
A per-instance counter looks correct when you test with one instance.
from collections import defaultdict
counts = defaultdict(int) # lives in this process only
def allow(user_id: str, limit: int = 100) -> bool:
counts[user_id] += 1
return counts[user_id] <= limitWith four instances behind a load balancer, a user can send about 400 requests before every instance blocks them. The counter also resets when the process restarts. A shared counter fixes both problems.
import redis
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
def allow(user_id: str, limit: int = 100, window_seconds: int = 60) -> bool:
key = f"rate:{user_id}"
count = r.incr(key)
if count == 1:
r.expire(key, window_seconds)
return count <= limitINCR is atomic, so concurrent instances never lose an update. The expiry on the first increment starts the window.
The sketch has one gap. If the process dies between incr and expire, the key never expires. A Lua script or a transaction closes it. Wrap the two calls in a pipeline with transaction=True as a simple fix.
Files: write to shared storage
Saving an upload to ./uploads ties the file to one instance's disk. Store it in object storage and keep only its key in your database.
import boto3
s3 = boto3.client("s3")
def save_upload(file_obj, user_id: str, filename: str) -> str:
key = f"uploads/{user_id}/{filename}"
s3.upload_fileobj(file_obj, "my-app-bucket", key)
return keyAny instance can then read the file or hand out a signed URL for it.
What local state is still acceptable
Not all local data must move. Keep it local when losing it costs only a little time and different values across instances are harmless.
- Read-only configuration loaded at startup.
- Compiled templates and loaded ML models.
- Short-lived caches of data that rarely changes, with a short TTL.
- Scratch files that exist only within one request.
The test is: if this instance disappeared right now, would any user notice anything beyond a slower request?
Common errors
- Assuming one instance in development. Everything passes locally, then fails in production. Run at least two instances locally to catch it.
- Relying on sticky sessions to hide the problem. Affinity makes a request land on the same instance, but a restart or scale-in still loses the data.
- Using local disk for durability. Instance disks are often ephemeral and are wiped on redeploy.
- Moving state to a shared store without handling its failure. The store is now a dependency. Decide whether to fail open or fail closed when it is unreachable. A rate limiter might fail open, while a payment check should fail closed.
Exercise
Your service runs on six instances. Each keeps an in-memory counter of failed logins per user and locks the account after 5 failures. Attackers are still able to try about 30 passwords before a lockout. Why, and what is the fix?
Show answer
Each instance counts separately, so each allows 5 failures, giving up to 6 × 5 = 30 attempts. Move the counter to a shared store with atomic increments (for example Redis INCR with a TTL), so all instances see one count. Because this is a security check, decide in advance that it fails closed if the store is unreachable.