Sub topic 10
Other Local State to Move Out of Instances
This chapter assumes you know how HTTP requests and cookies work, you have built a web service or API, and you know what a load balancer does. You have already seen how sessions can move out of instance memory. Sessions are only one kind of instance-local state. This chapter covers the others, how to spot them, and where each one usually goes.
Why session state is not the whole story
A service is stateless when any instance can handle any request and the result does not depend on which instance was chosen. Moving sessions to a shared store fixes one common violation. Other violations are easy to miss because they do not look like "state". They look like a cache, a temp file, a counter, or a scheduled job.
The test is the same for all of them. Ask what happens if the instance is killed right now, or if the next request goes to a different instance. If data is lost, or the behavior changes, that data is instance-local state that matters.
Not all local data is a problem. A read-only cache that can be rebuilt on demand is fine. The problem is data that is both needed and unique to one instance.
Common kinds of instance-local state
| Kind of state | Typical symptom when you scale out | Usual destination |
|---|---|---|
| Uploaded files on local disk | A file uploaded to instance A returns 404 from instance B | Object storage such as S3 |
| In-process cache | Instances return different values for the same data after an update | Shared cache such as Redis, or a short TTL |
| Rate-limit counters | A client gets N times the intended limit across N instances | Shared counter in Redis or at the gateway |
| Scheduled jobs | A nightly job runs on every instance | Single scheduler, leader election, or a lock |
| Background job queues held in memory | Jobs vanish on restart | Durable queue such as SQS or RabbitMQ |
| WebSocket or connection state | A reconnecting client lands on an instance that knows nothing about it | Pub/sub backplane and a shared subscription record |
| Local logs and temp files | Logs are lost when the instance is replaced | Log shipping to a central system |
| Generated IDs or sequences | Two instances produce the same ID | Database sequences, UUIDs, or a ID service |
The sections below go through the ones that cause the most trouble.
Files on local disk
A typical bug looks like this. A user uploads an avatar. The handler saves it to ./uploads/ on the instance. The next request for the avatar goes to another instance and returns 404. With one instance everything works, so the bug appears only after scaling out.
The fix is to write files to shared object storage and keep only the object key in your database. The instance writes the file and forgets it.
import uuid
import boto3
s3 = boto3.client("s3")
BUCKET = "example-avatars"
def save_avatar(user_id: str, data: bytes, content_type: str) -> str:
key = f"avatars/{user_id}/{uuid.uuid4()}"
s3.put_object(Bucket=BUCKET, Key=key, Body=data, ContentType=content_type)
return key # store this key in the database, not a local path
def avatar_url(key: str, expires_in: int = 300) -> str:
return s3.generate_presigned_url(
"get_object",
Params={"Bucket": BUCKET, "Key": key},
ExpiresIn=expires_in,
)Two details are worth noting. The key includes a random UUID, so two uploads never overwrite each other and you avoid a race between instances. The download uses a presigned URL, so the file bytes go from storage to the client without passing through your instances.
Temporary files are a separate case. An instance can use local disk as scratch space during one request, such as resizing an image, as long as the result is written elsewhere before the request ends and the scratch file is not needed later.
In-process caches
An in-process cache, such as a dictionary or an LRU cache inside the application, is fast because it has no network hop. It also has two problems in a multi-instance deployment:
- Each instance has its own copy, so copies drift apart. After an update, instance A may serve fresh data while instance B serves stale data until its entry expires.
- A new or restarted instance starts empty. If many instances restart together, all of them hit the database at once.
You have three reasonable options.
- Keep the local cache, but use a short TTL and accept brief inconsistency. This suits data where a few seconds of staleness is harmless, such as a public product catalog.
- Move the cache to a shared store such as Redis. All instances see the same value, at the cost of a network call on each read.
- Use both. A small local cache sits in front of the shared one, with a very short TTL, so hot keys avoid the network call.
Whichever you choose, the cache must never be the only copy of the data. If losing the cache would lose information, it is no longer a cache.
import json
import time
import redis
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
_local = {} # key -> (expires_at, value)
LOCAL_TTL = 5
SHARED_TTL = 300
def get_profile(user_id: str, load_from_db):
key = f"profile:{user_id}"
now = time.monotonic()
hit = _local.get(key)
if hit and hit[0] > now:
return hit[1]
raw = r.get(key)
if raw is not None:
value = json.loads(raw)
else:
value = load_from_db(user_id)
r.set(key, json.dumps(value), ex=SHARED_TTL)
_local[key] = (now + LOCAL_TTL, value)
return valueIn this example a profile update can be invisible to an instance for up to 5 seconds, because of the local layer. That bound is the price of avoiding a Redis call on every read. If 5 seconds is too long for your data, drop the local layer.
Rate-limit counters
Suppose each instance limits a client to 100 requests per minute, counting in memory. With four instances behind a load balancer, a client can send up to 400 requests per minute. The limit you configured is not the limit you enforce, and the real limit changes whenever you scale.
Counters have to be shared. A fixed-window counter in Redis is the simplest form.
import time
import redis
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
def allow_request(client_id: str, limit: int = 100, window_seconds: int = 60) -> bool:
window = int(time.time()) // window_seconds
key = f"rate:{client_id}:{window}"
pipe = r.pipeline()
pipe.incr(key)
pipe.expire(key, window_seconds)
count, _ = pipe.execute()
return count <= limitINCR is atomic, so concurrent requests on different instances cannot both read the same value and both write back the same increment. The key includes the window number, so old counters expire by themselves.
A fixed window has a known weakness. A client can send 100 requests at the end of one window and 100 more at the start of the next, so 200 requests in a short span. Sliding-window or token-bucket algorithms reduce this, and they also need shared state. When the limit exists to protect against abuse rather than to bill customers, the simple version is usually enough.
You must also decide what happens when Redis is unreachable. Failing open allows all requests and keeps the service available but removes protection. Failing closed rejects requests and protects the backend but causes an outage. The right choice depends on what the limit protects.
Scheduled and background work
Code that starts a timer when the process starts is instance-local behavior. If you run three instances, a "send daily report at 02:00" timer fires three times and users get three emails.
There are four common remedies.
- Run the scheduler as a separate single deployment, not inside the web instances.
- Use a managed scheduler, such as a cloud cron service or Kubernetes CronJob, that triggers one job run.
- Take a distributed lock before running, so only the instance that gets the lock proceeds.
- Elect a leader and let only the leader run scheduled work.
A lock needs an expiry, or a crashed holder blocks the job forever. A lock with an expiry creates its own edge case: if the job takes longer than the expiry, a second instance may start while the first is still running. Design the job itself to be idempotent, meaning that running it twice produces the same result as running it once. Locks reduce duplicate runs, and idempotency makes the remaining duplicates safe.
import redis
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
def run_once(job_name: str, work, lock_seconds: int = 300) -> bool:
# SET with nx=True succeeds only if the key does not already exist.
acquired = r.set(f"lock:{job_name}", "1", nx=True, ex=lock_seconds)
if not acquired:
return False
work()
return TrueThis sketch does not release the lock after the work finishes, so the job cannot run again until the lock expires. That is deliberate for a once-per-period job. A lock for protecting a critical section needs an owner token so one instance cannot release another's lock.
In-memory job queues have a similar problem. If a handler puts work in a list in memory and a worker thread drains it, a restart or deploy loses whatever is in the list. Use a durable queue, where messages are stored outside the process and are acknowledged only after the work completes. Unacknowledged messages are redelivered, which again means handlers should be idempotent.
Long-lived connections
WebSockets and server-sent events keep a connection open to one specific instance. The connection itself cannot move, so you cannot make it fully stateless. What you can do is keep everything else out of the instance:
- Store who is subscribed to what in a shared place, so a reconnecting client can be restored on any instance.
- Use a publish/subscribe channel between instances. When instance A receives a message for a user connected to instance B, it publishes to the channel and B delivers it.
- Let clients reconnect automatically and resume from a last-seen message ID.
During a deploy, the instance closes its connections and clients reconnect to other instances. If reconnecting restores everything, the deploy is invisible to users.
Generated IDs and ordering
Counters kept in memory, such as next_order_number = 1000, produce duplicates once two instances run. Use a database sequence, or generate globally unique IDs without coordination, such as UUIDs or time-ordered IDs. If the number must be gapless and sequential, such as an invoice number, take it from the database inside the transaction that creates the record.
Logs, metrics and temporary data
Instances in an autoscaling group or container platform are disposable. When one is replaced, its local disk goes with it. Logs written to a file on the instance are lost at the moment you most need them, after a crash. Write logs to standard output and let the platform ship them to a central system. Export metrics to a collector instead of reading them from instance files.
Finding hidden state
Hidden state is found by looking for specific patterns in the code and the deployment.
- Module-level dictionaries, lists, and counters that are written to during requests.
- Writes to the local file system outside a temp directory.
- Timers and schedulers started at process start-up.
- Singleton objects that hold data between requests.
- Configuration that is read once and expected to change at runtime.
A direct test is to run two instances behind a load balancer with no stickiness, send traffic round-robin, and kill one instance in the middle of a user flow. Anything that breaks marks local state you still depend on.
Trade-offs to keep in mind
Moving state out of instances is not free. Each externalized item adds a network call, a new dependency that can fail, and an operational burden. The goal is not to remove every local variable. The goal is that losing an instance, or adding one, never loses data or changes correct behavior.
Exercise
A service runs four instances behind a load balancer. Each instance keeps an in-memory counter and rejects a client after 60 requests per minute. Users report that some clients clearly exceed 60 requests per minute without being blocked. Explain why, estimate the worst-case effective limit, and name a fix.
Show answer
Each instance counts only the requests it receives, so the counters are independent. With round-robin balancing, a client can send 60 requests to each of the four instances in one minute, so the effective limit is up to 240 requests per minute, and it grows when instances are added. The fix is to keep the counter in a shared store such as Redis and use an atomic increment (INCR) on a key that includes the client ID and the time window, with an expiry equal to the window. Alternatively, enforce the limit at a gateway in front of the instances.
Exercise
A nightly cleanup task is started by a timer inside each web instance. After scaling from one to three instances, the task runs three times. Give two ways to fix this, and say why the task should still be idempotent after you fix it.
Show answer
One fix is to move the timer out of the web instances into a single scheduler deployment or a managed cron service such as a Kubernetes CronJob. Another is to take a lock with an expiry (for example SET with NX and EX in Redis) so only one instance runs the task. The task should still be idempotent because locks can expire while a slow run is still in progress, and a crashed run may be retried, so two executions can still overlap or repeat. An idempotent task makes those duplicates harmless.