
Fixing Async API Request Splitting Across Multiple EKS Pods
Our async API worked on one EKS pod but broke with two or more, because per-pod in-memory job state sat behind an ALB that routes requests round-robin. This article explains the root cause, shows the two ALB Ingress annotations that fixed it with sticky sessions, and compares longer-term alternatives like Redis, stateless design, and message queues.
Our async API worked perfectly on one pod and fell apart on two. The cause was per-pod in-memory state behind an Application Load Balancer (ALB) that spreads requests round-robin, and two ALB annotations fixed it in minutes. This article covers what we saw, why it happened, the fix, and the longer-term alternatives.
Introduction
Kubernetes makes scaling easy, but going from one pod to several can expose bugs that only appear under load. One of the most frustrating is an async application that behaves correctly with a single pod and starts failing as soon as you add replicas.
In this article, you will learn:
- What the problem is and how it shows up
- Why it happens
- How we fixed it with AWS Load Balancer Controller Ingress annotations on Amazon EKS
- Alternative approaches for solving the same problem
The problem: async requests split across pods
With one pod, every request goes to the same instance, so session and async state stay consistent. With two or more pods, the ALB distributes requests using its default round-robin algorithm:
text
Single pod -> Everything works2+ pods -> Requests are split, sessions break, async operations fail
Request 1 -> Pod 1 (session created here)Request 2 -> Pod 2 (no knowledge of the session)Request 3 -> Pod 1Request 4 -> Pod 3 (async callback lands here)The impact was visible across the whole application:
Scenario | Single pod | Multiple pods |
|---|---|---|
Async API calls | Working | Broken |
Session state | Maintained | Lost |
WebSocket connections | Stable | Disconnecting |
Long-running operations | Complete | Interrupted |
Environment
Component | Value |
|---|---|
Cloud provider | AWS |
Orchestration | Amazon EKS |
Load balancer | AWS Application Load Balancer (ALB) |
Ingress | AWS Load Balancer Controller |
Application | Async API (Python, FastAPI) |
Pods | 2 or more replicas |
Root cause: job state lived in each pod's memory
The application kept job state in a plain Python dictionary, so every pod had its own private copy:
python
# api_server.py# In-memory job store (use Redis/DB in production)# Also stores temporary directories to keep them aliveJOBS = {}TEMP_DIRS = {}Python dictionaries live in process memory. Multiple pods means multiple Python processes, each with its own separate memory space.
The request flow that caused 404 errors
Step 1: upload metadata (Pod A). The
/api/v1/documents/upload-metadata endpoint saves the PDF locally, uploads it to S3 if configured, and records the job in the in-memory dictionary:python
JOBS[upload_id] = { "status": "uploaded", "file_name": file.filename, "file_path": str(file_path), "s3_input_path": f"input/{file.filename}" if S3_BUCKET_NAME else None, "file_size_mb": file_size_mb, "total_pages": total_pages, "created_at": datetime.now().isoformat(), "selected_pages": None # Set when the user starts processing}At this point only Pod A knows about the job.
Step 2: start processing (Pod B). The ALB can route the next request to a different pod. The
/api/v1/documents/{upload_id}/process endpoint starts with this check:python
if upload_id not in JOBS: raise HTTPException(status_code=404, detail="Upload not found")Pod B's
JOBS dictionary is empty, so the request fails with 404 Not Found .text
Pod A memory: JOBS = {"4311d13d-...": {"status": "uploaded", ...}}Pod B memory: JOBS = {} <- no knowledge of the upload -> 404Pod C memory: JOBS = {} <- no knowledge of the uploadWhy async code makes this easy to miss
Python's
async / await is built for concurrency inside one process, not for coordination across a distributed system. The same pattern shows up in any FastAPI service that keeps operation state locally:python
from fastapi import FastAPI, BackgroundTasksimport uuid
app = FastAPI()
# In-memory storage (this is the problem)async_operations = {}
@app.post("/api/start-processing")async def start_processing(file_id: str, background_tasks: BackgroundTasks): operation_id = str(uuid.uuid4()) # State stored in THIS pod's memory async_operations[operation_id] = {"status": "processing", "file_id": file_id} background_tasks.add_task(process_file, operation_id, file_id) return {"operation_id": operation_id}
@app.get("/api/status/{operation_id}")async def check_status(operation_id: str): # Only works if the request hits the SAME pod if operation_id not in async_operations: return {"error": "Operation not found"} return async_operations[operation_id]Putting it together, the failure happens because:
- Async operation state is stored in local pod memory.
- Each pod has its own isolated memory space.
- The ALB distributes requests across all pods.
- Status checks land on pods that have no record of the operation.
The fix: ALB sticky sessions
Two annotations on the Ingress resolved the issue: one enables sticky sessions on the target group, the other drops invalid header fields at the load balancer.
Before: no stickiness
The original Ingress had no session affinity, so the ALB distributed requests across pods:
yaml
apiVersion: networking.k8s.io/v1kind: Ingressmetadata: name: my-app-ingress namespace: production annotations: kubernetes.io/ingress.class: alb alb.ingress.kubernetes.io/scheme: internet-facing alb.ingress.kubernetes.io/target-type: ipspec: rules: - host: api.myapp.com http: paths: - path: / pathType: Prefix backend: service: name: my-app-service port: number: 80After: sticky sessions and header validation
yaml
apiVersion: networking.k8s.io/v1kind: Ingressmetadata: name: my-app-ingress namespace: production annotations: kubernetes.io/ingress.class: alb alb.ingress.kubernetes.io/scheme: internet-facing alb.ingress.kubernetes.io/target-type: ip
# Fix 1: enable sticky sessions (24 hours = 86400 seconds) alb.ingress.kubernetes.io/target-group-attributes: | stickiness.enabled=true, stickiness.lb_cookie.duration_seconds=86400
# Fix 2: drop invalid header fields alb.ingress.kubernetes.io/load-balancer-attributes: | routing.http.drop_invalid_header_fields.enabled=truespec: rules: - host: api.myapp.com http: paths: - path: / pathType: Prefix backend: service: name: my-app-service port: number: 80What the annotations do
target-group-attributes enables sticky sessions. With stickiness.enabled=true , the ALB sets an AWSALB cookie on the first response. Later requests carrying that cookie go to the same pod. stickiness.lb_cookie.duration_seconds=86400 keeps that binding for 24 hours, so an upload followed by a processing request and its status checks all reach the pod that holds the job.text
Before: Caller -> ALB -> round robin -> Pod 1 / Pod 2 / Pod 3After: Caller -> ALB (AWSALB cookie) -> same pod for every request Other callers -> ALB -> their own sticky podload-balancer-attributes drops invalid headers. routing.http.drop_invalid_header_fields.enabled=true removes HTTP headers with invalid characters, which helps prevent request smuggling attacks and reduces malformed-request errors.Implementing and verifying the fix
The change takes five steps, and the last two confirm that stickiness is actually active.
- Verify the AWS Load Balancer Controller is running.
bash
kubectl get deployment -n kube-system aws-load-balancer-controller# NAME READY UP-TO-DATE AVAILABLE# aws-load-balancer-controller 2/2 2 2- Check the current Ingress.
bash
kubectl get ingress -n productionkubectl describe ingress my-app-ingress -n production- Apply the updated Ingress.
bash
kubectl apply -f ingress-after-fix.yamlkubectl describe ingress my-app-ingress -n production- Confirm the target group attributes on AWS.
bash
aws elbv2 describe-target-group-attributes \ --target-group-arn <your_target_group_arn># Expect stickiness.enabled = true# and stickiness.lb_cookie.duration_seconds = 86400- Test with curl and look for the
AWSALBcookie.
bash
# First request: save the sticky session cookiecurl -v -c cookies.txt https://api.myapp.com/health
# Second request: should reach the same podcurl -v -b cookies.txt https://api.myapp.com/api/async-operation
# Check the AWSALB cookiegrep AWSALB cookies.txtAlternative approaches
Sticky sessions are the fastest fix, but they are not the only one. Here are the other options we considered, from the most production-ready to the simplest.
1. Redis-based shared state (recommended for production)
Best for applications that need true horizontal scaling without session affinity. Pods share state through Redis, so any pod can serve any request.
yaml
apiVersion: apps/v1kind: Deploymentmetadata: name: redis-session-storespec: replicas: 1 selector: matchLabels: app: redis template: metadata: labels: app: redis spec: containers: - name: redis image: redis:7-alpine ports: - containerPort: 6379 resources: requests: memory: "128Mi" cpu: "100m" limits: memory: "256Mi" cpu: "200m"---apiVersion: v1kind: Servicemetadata: name: redis-servicespec: selector: app: redis ports: - port: 6379python
# Flask examplefrom flask import Flaskfrom flask_session import Sessionimport redis
app = Flask(__name__)app.config['SESSION_TYPE'] = 'redis'app.config['SESSION_REDIS'] = redis.from_url('redis://redis-service:6379')Session(app)Pros | Cons |
|---|---|
True horizontal scaling | Additional Redis infrastructure |
Pod restarts do not lose sessions | Redis can become a single point of failure |
Better load distribution | Network latency for session reads |
Production-grade | More complex setup |
2. Stateless design with a shared database
Best for modern API applications that can be redesigned. Operation state lives in a database, not in pod memory, so any pod can answer a status check.
javascript
app.post('/api/async-start', async (req, res) => { const operationId = generateUUID(); // Store operation state in a database, not pod memory await db.saveOperation({ id: operationId, status: 'pending', userId: req.user.id }); res.json({ operationId });});
// Any pod can handle the status checkapp.get('/api/async-status/:operationId', async (req, res) => { const operation = await db.getOperation(req.params.operationId); res.json(operation);});Pros | Cons |
|---|---|
Truly stateless and scalable | Requires application redesign |
No sticky sessions needed | State must live in an external database |
Works with any load balancing | More complex async handling |
Cloud-native approach | Higher development effort |
3. Least-outstanding-requests routing with application cookie stickiness
Best when you want smarter balancing than round robin while keeping sessions pinned. This variant uses an application-controlled cookie instead of the ALB-generated one:
yaml
alb.ingress.kubernetes.io/load-balancer-attributes: > routing.http.drop_invalid_header_fields.enabled=truealb.ingress.kubernetes.io/target-group-attributes: > load_balancing.algorithm.type=least_outstanding_requests, stickiness.enabled=true, stickiness.type=app_cookie, stickiness.app_cookie.cookie_name=MY_APP_SESSION, stickiness.app_cookie.duration_seconds=86400Because the application sets the cookie, you control when a session starts and ends. The same idea works for frameworks with their own session cookie, for example
JSESSIONID in Spring Boot:yaml
alb.ingress.kubernetes.io/target-group-attributes: > stickiness.enabled=true, stickiness.type=app_cookie, stickiness.app_cookie.cookie_name=JSESSIONID, stickiness.app_cookie.duration_seconds=864004. Kubernetes Service session affinity
Best for simple setups without an Ingress controller.
yaml
apiVersion: v1kind: Servicemetadata: name: my-app-service namespace: productionspec: selector: app: my-app ports: - port: 80 targetPort: 8080 sessionAffinity: ClientIP sessionAffinityConfig: clientIP: timeoutSeconds: 86400 # 24 hoursWarning: this uses the source IP address, which can cause uneven distribution behind NAT or proxies.
5. Message queue for async operations
Best for decoupling async work from the API pods completely. Any pod publishes a job, dedicated worker pods consume it, and status lives in a database, so routing no longer matters.
javascript
// Producer: any API pod can create the jobapp.post('/api/async-operation', async (req, res) => { const jobId = uuid(); await messageQueue.publish({ queue: 'async-jobs', message: { jobId, userId: req.user.id, data: req.body } }); res.json({ jobId, status: 'queued' });});
// Consumer: dedicated worker pods, separate from the API podsmessageQueue.consume('async-jobs', async (message) => { await processAsyncJob(message); await db.updateJobStatus(message.jobId, 'completed');});
// Status check: any pod can read the databaseapp.get('/api/job-status/:jobId', async (req, res) => { const status = await db.getJobStatus(req.params.jobId); res.json(status);});On AWS, Amazon SQS is a natural fit for the queue.
Comparison
Method | Complexity | Cost | Scalability | Best for |
|---|---|---|---|---|
ALB sticky sessions | Low | Free | Medium | Quick fix, existing apps |
Redis shared state | Medium | Low | High | Production apps |
Stateless with database | High | Free | Very high | New application design |
LOR routing + app cookie | Low | Free | Medium | App-controlled sessions |
Service session affinity | Low | Free | Low | Simple or internal apps |
Message queue | High | Medium | Very high | Async-heavy workloads |
Security considerations
Combine sticky sessions with the load balancer's security settings:
yaml
alb.ingress.kubernetes.io/load-balancer-attributes: > routing.http.drop_invalid_header_fields.enabled=true, routing.http.desync_mitigation_mode=defensive, routing.http2.enabled=truealb.ingress.kubernetes.io/target-group-attributes: > stickiness.enabled=true, stickiness.lb_cookie.duration_seconds=86400
# Additional security annotationsalb.ingress.kubernetes.io/ssl-redirect: '443'alb.ingress.kubernetes.io/ssl-policy: ELBSecurityPolicy-TLS13-1-2-2021-06Key takeaways
- Sticky sessions are the quick fix. Use them when you need the problem resolved immediately.
- Redis shared state is production grade. Use it when building scalable production systems.
- Stateless design is cloud native. Use it when designing new applications.
- Message queues suit async-heavy workloads. Use them when async operations are core to your application.
Conclusion
Scaling from one pod to several exposed a classic distributed systems challenge: state management. Two ALB annotations solved our immediate problem by pinning each caller to one pod. For a system that scales cleanly, plan a migration to shared state in Redis or a database, or to a fully stateless design.
Start with sticky sessions as the quick fix, then plan the move to a stateless architecture for long-term scalability.
Have you hit similar issues with async applications on Kubernetes? Share your experience in the comments.
Resources
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article