Race-Free Real-Time Bidding at Scale: Building an AI-Assisted Auction Platform on AWS with WebSockets, SQS FIFO, ElastiCache, and Amazon Bedrock

Race-Free Real-Time Bidding at Scale: Building an AI-Assisted Auction Platform on AWS with WebSockets, SQS FIFO, ElastiCache, and Amazon Bedrock

How a production car auction platform accepts tens of thousands of bids in an auction’s final seconds without a single race condition, using per car SQS FIFO ordering, conditional writes on RDS, ElastiCache, and a read only AI assistant on Amazon Bedrock.

SR. Cloud and Devops Engineer & Certified Solutions Architect | AWS Community Builder | Claude Certi
The problem: 25,000 bids in the closing seconds

When a live car auction closes, up to 25,000 bids hit the platform in its final seconds, many of them on the same cars within the same millisecond. Every bid must be accepted or rejected in the right order, and every bidder must see the new high bid instantly. Get it wrong and the wrong person wins a car.
I designed, built, and run the AWS infrastructure for a US-based online car auction platform that runs no-reserve live auctions. In a no-reserve auction the highest bid wins, whatever the price, so bid correctness is the whole business.
Two things break first under this load:
  • Race conditions. Two bidders both read a current bid of $500, both bid $550 and both writes succeed. Now two people think they are winning.
  • Database pressure. Tens of thousands of bids hitting the database at the same instant pile up as lock contention and connection exhaustion.

In this guide you will build the bidding engine that solves both:
  1. A WebSocket layer on Amazon API Gateway, authenticated with Amazon Cognito.
  1. A bid intake Lambda that puts every bid into an Amazon SQS FIFO queue, one message group per car.
  1. A bid processor Lambda that accepts a bid only through a conditional write on the Amazon RDS primary.
  1. A broadcast step that pushes the new high bid to every connected bidder, using Redis to track connections.
  1. A caching layer at every tier: Amazon CloudFront at the edge and Amazon ElastiCache for Redis as a hot bid cache.
  1. An AI auction assistant on Amazon Bedrock with Claude that answers bidder questions from live data, without ever touching a bid.
  1. Production hardening: AWS WAF, Multi-AZ, dead-letter queues, and the alarms that tell you a bid is waiting too long.

Prerequisites: an AWS account, Node.js 20, the AWS CLI, and working knowledge of Lambda and VPCs. This guide walks through the design and the implementation steps; it contains no production code from the platform.
Architecture at a glance
The platform runs two separate paths: browsing is cached and served by EC2, while bidding is event-driven and never touches the web servers. The full stack is CloudFront and AWS WAF at the edge, an Application Load Balancer with EC2 Auto Scaling in private subnets, Amazon RDS with a Multi-AZ primary and a read replica, Amazon ElastiCache for Redis for caching and connection tracking, Amazon S3 for vehicle images, Amazon Cognito for sign-in and a NAT gateway for outbound traffic. An AI auction assistant built on Amazon Bedrock with Claude answers bidder questions from the same caches the website reads (Step 6).


Read it in two columns: the left column serves pages from the read replica, the right column carries every bid through the FIFO queue to the primary, and the processor pushes the result back out through API Gateway.

Step 1: The WebSocket layer with API Gateway and Cognito

API Gateway WebSocket APIs hold the persistent connections, so your servers never have to. Create a WebSocket API with four routes:
Route
Integration
What it does
 $connect 
Lambda authorizer + connect Lambda
Verifies the Cognito token, records the connection
 $disconnect 
disconnect Lambda
Removes the connection from Redis
 subscribe 
subscribe Lambda
Adds the connection to a car's watcher set
 placeBid 
bid intake Lambda
Queues the bid (Step 2)
Set the route selection expression to  $request.body.action , so a client message like  {"action":"placeBid", ...}  hits the right Lambda.


Authenticate on connect

Browsers cannot set custom headers on a WebSocket handshake. The client therefore passes its Cognito ID token as a query string parameter, and a Lambda authorizer on  $connect  verifies it:
  1. Create a Lambda authorizer of type  REQUEST  on the  $connect  route, with the  token  query string parameter as its identity source.
  1. In the authorizer, verify the token's signature, expiry, issuer (your user pool), and audience (your app client). The open-source AWS JWT Verify library does all four.
  1. On success, return an Allow policy and put the user's Cognito  sub  into the authorizer context as  userId . On failure, deny, and the handshake never completes.

The  userId  in  context  reaches every later route as  event.requestContext.authorizer.userId . Never trust a user ID sent in the message body.


Track connections in Redis

Each car keeps a Redis set of the connection IDs watching it. Redis answers "who is watching car 107023?" in well under a millisecond, which matters when you broadcast after every bid.
Redis key
Type
Holds
Updated by
 car:{carId}:watchers 
Set
Connection IDs watching one car
 subscribe  adds,  $disconnect  removes
 conn:{connectionId}:cars 
Set
Cars one connection is watching
 subscribe  adds,  $disconnect  deletes
Create the Redis client outside the Lambda handler so warm invocations reuse the connection, and send the disconnect cleanup as a single pipelined batch.
The reverse index ( conn:{id}:cars ) lets disconnect clean up in one round trip instead of scanning every car.


Step 2: Queue every bid in SQS FIFO, one message group per car

The bid intake Lambda does not touch the database. It validates the bid, puts it on an SQS FIFO queue, and returns. This single decision removes the race condition and protects RDS.

Why FIFO with car ID as the message group:
  • SQS FIFO delivers messages in the same  MessageGroupId  strictly in order, one at a time. With  MessageGroupId = carId , all bids for one car are processed sequentially, in the order they arrived.
  • Different cars are different groups, so they are processed in parallel. A bidding war on one car never slows down another.
  • The queue absorbs the spike. If 2,000 bids land at once, they wait in the queue for milliseconds instead of fighting for database locks.
Two bidders who bid the same amount on the same car are no longer a race: whichever bid entered the queue first is processed first and wins.
The intake Lambda checks that the amount is a whole number in $50 bid steps, then sends one message with these settings:

Setting
Value
Why
Queue
A FIFO queue (name ends in  .fifo )
Ordering and deduplication
 MessageGroupId 
The car ID
Strict order per car, parallel across cars
 MessageDeduplicationId 
User ID + client bid ID
One click can never become two bids
Message body
Car ID, amount, user ID, connection ID, arrival time
Everything the processor needs, nothing more
The user ID always comes from the authorizer context, never from the message the browser sent.
current high bid, belongs in the processor, because only the processor sees bids in order.
Size the queue for the burst
Do the arithmetic before auction day. As a worked example, if 25,000 bids arrive over a 60 second close, that averages about 420 bids per second, and the real peak in the final seconds is higher.
The intake Lambda sends one message per bid, without batching. A FIFO queue in its default mode supports up to 300 send calls per second per partition. That is below this burst, so enable high throughput mode on the queue. It raises the limit by partitioning the queue by message group, and because every car is its own message group, bids spread across partitions naturally. The exact ceiling depends on your Region, so check the SQS quotas page for yours.

Step 3: The bid processor accepts a bid only through a conditional write

The bid processor Lambda reads from the FIFO queue through an event source mapping. FIFO ordering already serializes bids per car, but the database write is still made conditional. That way correctness never depends on a single mechanism.
The whole acceptance rule lives in one conditional  UPDATE  against the RDS primary. It sets the new high bid and bidder only when all three conditions hold:
  • The row is the car being bid on.
  • The new amount is at least one bid step above the current high bid.
  • The auction's end time is still in the future.
If the statement updates one row, the bid won. If it updates zero rows, the bid was too low or arrived after close. There is no read-then-write gap for another bid to slip into.
For each message in a batch, the processor:
  1. Runs the conditional update on the primary and checks whether one row changed.
  1. Records the bid in a bid history table, accepted or not, with its arrival time.
  1. Notifies bidders (Step 4).
  1. On a real error, stops the batch and reports this message and every later one as failed.
Three details matter here:
  • A rejected bid is not a failure. A low bid is a normal outcome: record it, tell the bidder, and move on. Only real errors (database down, timeout) go into  batchItemFailures .
  • Stop at the first failure. Enable  ReportBatchItemFailures  on the event source mapping and return the failed message plus everything after it. Retrying only the failed message would let a later bid jump ahead of an earlier one.
  • Keep the pool small. Each concurrent Lambda opens its own connections. A pool of 1 to 2 per instance, or RDS Proxy in front of the primary, keeps a bid spike from exhausting database connections.

Step 4: Broadcast the new high bid to every watcher

After an accepted bid, the processor looks up the car's watchers in Redis and pushes the update through the API Gateway Management API. A rejected bid goes back only to the bidder who placed it.
  1. Accepted bid: read the car's watcher set from Redis.
  1. Call  PostToConnection  on the API Gateway Management API once per watcher, in parallel. The endpoint is your WebSocket API's HTTPS URL, including the stage.
  1. Rejected bid: send a short "bid rejected" message only to the bidder's own connection.
  1. If a send fails with  GoneException  (HTTP 410), remove that connection from the watcher set.
  • Every send stands alone. One slow or dead connection must not block the other watchers or fail the batch.
  • Clean up on  GoneException . A closed tab does not always trigger  $disconnect  cleanly. Removing the connection the first time a send fails keeps the watcher sets accurate.
  • Send the amount, not the bidder. The broadcast carries the new high bid only. Each client compares it with its own last bid to show "Outbid!" locally.


The read/write split: never read the high bid from a replica

All bid writes go to the RDS primary; browsing traffic goes to a read replica. During an auction, far more people browse inventory pages than place bids. Moving those reads off the primary keeps it free for the writes that matter.
Query
Goes to
Why
Accept a bid (conditional  UPDATE )
Primary
Must see the latest committed bid
Insert bid history
Primary
It is a write
Inventory, search, car detail pages
Read replica
High volume, slightly stale is fine
Bid history and sold vehicle pages
Read replica
Not time critical
Current high bid on first page load
Read replica, then WebSocket
The next broadcast corrects any lag
The trap: a read replica lags the primary, usually by milliseconds, sometimes by seconds under heavy write load. If the bid processor checked the current high bid on the replica, it could accept a bid that was already beaten. That is why the acceptance rule is a single conditional write on the primary, never a read from the replica followed by a write.


Step 5: Cache at every tier, but never decide a bid from a cache

The rule is simple: only the RDS primary decides whether a bid wins, and everything a bidder reads can come from a cache. During an auction, reads outnumber bids by a wide margin, so every read served from a cache is load the primary never sees.
Tier
Service
What it holds
How it stays fresh
Edge
Amazon CloudFront + Amazon S3 (origin access control)
Vehicle photos, JavaScript, CSS
Long TTL, versioned file names
Edge
Amazon CloudFront in front of the ALB
Inventory and listing pages
Short TTL, in seconds
Hot data
Amazon ElastiCache for Redis
Current high bid per car
Write-through on every accepted bid
Hot data
Amazon ElastiCache for Redis
Car details for the auction page
Cache-aside, TTL in minutes, deleted on edit
Connections
Amazon ElastiCache for Redis
WebSocket watchers per car
Updated on subscribe and disconnect
Database
RDS read replica
Everything else
Replication lag, usually milliseconds

Write-through for the high bid, with a raise-only guard

After the conditional  UPDATE  succeeds, the processor writes the new high bid to Redis through a small Lua script. The script reads the cached bid and writes the new value, with a one-hour TTL, only if it is higher. Redis runs the script atomically, so a duplicate or retried message can never lower the cached value.
Redis key
Holds
Written
Expires
 car:{carId}:highBid 
Current high bid
After every accepted bid, raise-only
1 hour
 car:{carId}:details 
Car details for the auction page
On a cache miss
5 minutes, or deleted on edit
One edge case is worth handling. If the Lambda crashes after the database commit but before the cache write, SQS redelivers the message. The conditional  UPDATE  now rejects it, because that amount is already the high bid, so the cache write never runs. On every rejection, refresh the cache from the primary's current value. The TTL is a second safety net: a stale key expires on its own.

Cache-aside for car details

  1. Look up  car:{carId}:details  in Redis.
  1. On a hit, return it.
  1. On a miss, read the car from the read replica, store it in Redis with a 5-minute TTL, and return it.
When staff edit a listing, delete the key so the next read reloads it. Do not try to update the cached copy in place; deleting is simpler and cannot race.

Step 6: An AI auction assistant with Amazon Bedrock and Claude

Bidders ask the same questions all auction long: "Does this car run?", "What's the current bid on the Pathfinder?", "Show me AWD SUVs under $2,000." An assistant built on Amazon Bedrock with Claude answers them in plain language, from live data, and is designed so it can never place, change, or cancel a bid.

Tools, not stale embeddings

The current bid changes every second, and inventory changes every day. Indexing that into a vector store would make the assistant wrong within minutes. Instead, Claude calls tools through the Bedrock Converse API, and each tool reads the same caches the website uses:
Tool
Reads from
Answers
 get_current_bid 
Redis hot bid cache
"What's the bid on car 107023 right now?"
 get_car_details 
Redis cache-aside, then read replica
"Does it run? Clean title? Mileage?"
 search_inventory 
Read replica
"AWD SUVs under $2,000 in this auction"
Static content such as fees, the guarantee, and how bidding works changes rarely. That part can come from an Amazon Bedrock Knowledge Base over the help center pages.
The assistant Lambda runs a short loop against the Converse API:
  1. Send the bidder's question with a system prompt, the three tool definitions (each a name, a one-line description, and a JSON schema for its input), a Bedrock guardrail, and a cap on output tokens.
  1. If Claude stops with  tool_use , run each requested tool against the cache or the read replica and send the results back as tool results.
  1. Repeat until Claude answers in text, with a hard limit of five round trips so a confused conversation cannot run up cost.
The system prompt tells Claude it is the auction assistant, that it answers from the tools, and that it cannot place, change, or cancel bids. The model ID lives in configuration, so you can move to a newer Claude model on Bedrock without redeploying code.

Read-only by construction, not by prompt

A system prompt that says "never place bids" is a request, not a control. The real guarantees come from the infrastructure:
  • No write tools. The assistant has no tool that writes anything, so there is nothing for the model to call.
  • IAM. The assistant Lambda's role has no  sqs:SendMessage  on the bid queue and no access to the primary database.
  • Read-only database user. Its database credentials connect only to the read replica, with  SELECT  grants.
  • Amazon Bedrock Guardrails. A guardrail blocks off-topic requests and masks personal data, such as phone numbers, in both prompts and answers.
For a chat-style feel, swap  ConverseCommand  for  ConverseStreamCommand  and push tokens to the browser over the same WebSocket connection the bidder already has open.

Production hardening: security, reliability, observability

A bidding engine that works on a quiet Tuesday is not done. These are the controls that keep it correct on festival day.

Security

  • AWS WAF on CloudFront and the ALB, with AWS managed rule groups and rate-based rules on sign-up and login.
  • AWS WAF does not attach to API Gateway WebSocket APIs. Protect the bid path with stage throttling, the Lambda authorizer, and a per-user rate limit in the intake Lambda.
The rate limit is one Redis counter per user per second: increment it on every bid, let the key expire after two seconds, and reject with HTTP 429 once the count passes your limit, such as five bids per second.
  • Private subnets for EC2, RDS, ElastiCache, and every Lambda that touches data. Only CloudFront, the ALB, and API Gateway face the internet; outbound calls leave through the NAT gateway.
  • Least-privilege IAM per function. The intake Lambda can only send to the bid queue; the processor can only read it; the assistant can do neither.

Reliability

  • Multi-AZ everywhere it matters: RDS primary with automatic failover, ElastiCache with a replica in a second Availability Zone, and the EC2 Auto Scaling group spread across zones.
  • A FIFO dead-letter queue (a DLQ for a FIFO queue must also be FIFO). Set  maxReceiveCount  low, such as 3. Once a bid moves to the DLQ, later bids for that car continue, so any DLQ message is an incident to review, not a backlog.
  • Reserved concurrency on the processor. It caps how many Lambdas, and therefore database connections, a spike can create.

Observability

Alarm
Metric
Why it matters
Bids are waiting
SQS  ApproximateAgeOfOldestMessage 
Bidders see a delay before their bid counts
A bid failed
DLQ  ApproximateNumberOfMessagesVisible  > 0
A bid was not processed and needs review
Processor errors
Lambda  Errors  and  Throttles 
Bids are being retried
Replica falling behind
RDS  ReplicaLag 
Listing pages show stale prices
Connection problems
API Gateway  ConnectCount  and  ClientError 
Bidders cannot connect or are being rejected
Turn on AWS X-Ray across API Gateway, both Lambdas, and SQS. A single trace then shows how long one bid spent in each hop, from button press to broadcast.

Results in production: a festival auction with 50,000 real users

This is not a load test. During a festival sale, 50,000 real users took part in live auctions on this architecture, with up to 25,000 bids arriving in an auction's closing seconds. Bidding kept working correctly throughout. The platform has since passed 15,000 cars sold and 33,000 registered bidders.
What held up under that traffic:
  • Bid ordering. SQS FIFO kept every car's bids in arrival order while bids on different cars were processed in parallel.
  • The database. The queue flattened the spikes, so the primary handled a steady stream of writes instead of a burst.
  • Connections. API Gateway held the WebSocket connections, so the EC2 fleet behind the load balancer only served pages.
Detailed operational metrics stay private at the client's request, but the alarms in the observability table above are the ones to watch if you run a similar event.

Lessons learned and gotchas

  1. The Lambda in the VPC needs a route out to call API Gateway. The bid processor runs in private subnets to reach RDS and Redis.  PostToConnection  calls a public API Gateway endpoint, so without a NAT gateway in the route table the broadcast silently times out. Our private subnets route outbound traffic through a NAT gateway.
  1. Correctness belongs in the database, not in application code. An  if (amount > currentBid)  check in Lambda is a race waiting to happen. The conditional  UPDATE  makes the database the single referee.
  1. FIFO ordering survives only if failures are handled in order. Returning only the failed message from a batch lets later bids for the same car jump the queue. Return the failed message and everything after it.
  1. WebSocket connections end on their own. API Gateway closes idle connections after 10 minutes and any connection after 2 hours. Have clients send a small heartbeat during long auctions, and reconnect and resubscribe automatically when a connection drops.
  1. Tokens in query strings end up in logs. Passing the Cognito token on  $connect  is the standard pattern, but keep it out of access logs and keep token lifetimes short.
  1. Pick the message group carefully. Car ID gives ordering where it matters and parallelism everywhere else. A single group for the whole auction would serialize every bid on every car.

A real incident: the bug that waited for the auction

A developer accidentally changed a value in the application's  .env  file. Nothing was restarted, and the website kept serving pages normally, so every health check stayed green. The broken value only mattered at the scheduled auction start, when the auction start process loaded the environment. It read the wrong variables, and the auction did not start.
CloudWatch Logs showed the auction start process failing right away. I traced the error to the changed variable, corrected it, and had the auction running within 5 minutes.
What it taught me:
  • Configuration read only at a scheduled moment can sit broken for hours unnoticed. Validate every required setting when it changes, not when it is first used.
  • Keep runtime configuration out of  .env  files on servers. AWS Systems Manager Parameter Store, or AWS Secrets Manager for secrets, versions every change, records which IAM identity made it, and makes rollback one click.
  • Alarm on business events, not just server health. A CloudWatch alarm that fires when an auction has not reached "started" within a minute of its scheduled time catches this class of failure before bidders do.

Cost and cleanup

The pieces that cost money while idle are the NAT gateway, the ElastiCache node, and the RDS instance. API Gateway, SQS, Lambda, and Amazon Bedrock are billed per request or per token and cost close to nothing when no one is bidding. Delete the stack when you finish testing so the NAT gateway and database stop billing.

Conclusion

A live auction stays fair only if every bid on a car is judged in order, by one referee. SQS FIFO with the car ID as the message group gives you the order. A conditional write on the RDS primary gives you the referee. API Gateway WebSockets and ElastiCache tell every bidder the result in real time. Caches at every tier keep the primary free for bids, and an AI assistant on Amazon Bedrock answers questions without ever touching one. Slow is smooth, and smooth is fast: the queue adds milliseconds and removes every race.
Happy Learning
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article