
How a Single Leaderboard Exploded My DynamoDB Bill - And How I Fixed It
An engineering case study on serverless optimization, S3 presigned URL scaling overhead, and Serverless HTTP execution limits.
Every student community leader loves a launch. For my AWS Student Builder Group, I designed and built a custom gamified portal. The system was built to host hands-on learning sprints, verify cloud lab submissions, track active builders, and display progress.
But nothing sobered me up faster than opening my AWS CloudWatch dashboard a few days after running our first major cohort.
My DynamoDB Consumed Read Request Units (RRUs) had spiked to over 340 RRUs (well above my baseline provisioned threshold), and my AWS billing alerts were screaming.
Here is the story of how a seemingly simple "student leaderboard" page on my community platform brought my serverless database to its knees, how I diagnosed it, and the architecture patterns I used to slash my database costs while making page loads 10x faster.
The Context: A Community Platform for AWS Student Builders
I built this platform to act as a digital hub for student builders. To keep members motivated during multi-week learning sprints, I built a gamification engine:
- The Sprints: Builders complete hands-on AWS challenges (e.g., deploying static sites, configuring VPCs, writing Lambda functions).
- The Proof: They submit verification screenshots and logs.
- The Leaderboard: Once approved, builders earn XP. The homepage features a real-time leaderboard showing everyone's score, rank, and roadmap completion progress.
The problem started as our cohort size grew. When hundreds of student builders started hitting the challenge details page to check where they stood, page load times ballooned to 10+ seconds, and database read capacity units spiked.
Anatomy of the Bottlenecks
Here is how I originally designed the leaderboard API:
[User Browser]
│
▼ (GET /challenges/:challengeId/leaderboard)
[AWS Lambda (Express API)]
│
▼ (Scan / Query all registrations)
[DynamoDB]
│
▼ (400+ users fetched)
[Generate 400+ S3 Presigned Avatar URLs] ── (Cryptographic signature overhead)
│
▼ (Return massive JSON array)
[User Browser Slices First 15 Users Client-Side]At first glance, it looks like a standard flow. But in serverless environments, this design contains three fatal bottlenecks:
1. The Global Database Scans
Every single time a user loaded or refreshed the leaderboard page, the backend executed a global database scan (
scanAll ) across all registrations, submissions, and student profiles. For a cohort of 500+ builders, this was consuming hundreds of read capacity units per second.2. S3 Presigned URL Signing Overhead
To securely render student profile pictures, my database stores S3 object keys. To show them, the backend must convert these keys into secure, temporary S3 Presigned URLs.
Generating a presigned URL requires calculating a HMAC-SHA256 signature using the AWS SDK client. Doing this once is fast (under 1ms). But doing it 400+ times sequentially inside a single Lambda invocation created massive CPU bottlenecking, pushing execution times to over 6 seconds before any data was sent!
3. Background Thread Freezes (The Email Cohort Issue)
I also had an admin feature to email the cohort of registered students to announce when the next week's labs were unlocked. In NodeJS, I used a traditional "fire-and-forget" background promise to send emails, responding to the client immediately.
On AWS Lambda, this is a fatal anti-pattern. The instant a Lambda handler returns an HTTP response to API Gateway, the container runtime is immediately frozen. The background thread paused mid-execution, dropping 90% of the emails. When I tried to await the loop synchronously instead, sending emails to 400+ users exceeded API Gateway’s strict 29-second timeout limit, resulting in a browser error:
"Failed to fetch" .
The Fixes: Restoring Performance and Cost-Efficiency
I completely refactored both the backend API and frontend views, focusing on caching, query indexing, and server-side pagination.
1. Replacing Scans with Direct Partition Queries (Zero Joins)
I swapped all global database scans with targeted index queries using the
queryByPK pattern. Instead of scanning the entire database, the backend queries the specific partition in parallel:const [regs, subs, allRoadmap] = await Promise.all([
queryByPK(`CHALLENGE#${challengeId}`, 'REGISTRATION#'),
queryByPK(`CHALLENGE#${challengeId}`, 'SUBMISSION#'),
queryByPK(`CHALLENGE#${challengeId}`, 'WEEK#'),
]);This restricts the database read scope solely to the items relating to that challenge, reducing read units from hundreds down to 1 or 2 per page load!
2. Persistent Leaderboard Cache Key with TTL
Rather than re-calculating points, progress, and rankings on every request, I designed a persistent cache key directly inside DynamoDB:
- PK:
LEADERBOARD#CACHE
- SK:
CHALLENGE_LEADERBOARD#${challengeId}
When a request arrives, the backend fetches this pre-computed record instantly. I set a cache duration of 5 minutes. To ensure DynamoDB automatically cleans up old cached records and keeps storage costs low, I included a
ttlExpiresAt attribute (DynamoDB Time-to-Live):await putItem({
PK: 'LEADERBOARD#CACHE',
SK: cacheKey,
cachedAt: new Date().toISOString(),
leaderboardRaw: leaderboardSorted,
ttlExpiresAt: Math.floor(Date.now() / 1000) + 5 * 60 // 5 minutes TTL
});3. Server-Side Slicing (97% Drop in URL Signing)
By applying pagination parameters (
?limit=15&page=X ) before generating S3 presigned URLs, I eliminated the HMAC signing bottleneck:const offset = (page - 1) * limit;
const slicedRaw = leaderboardRaw.slice(offset, offset + limit);
// Generate presigned URLs only for the sliced 15 builders
const signedAvatars = await Promise.all(
slicedRaw.map(e => signBadgeUrlIfNeeded(e._avatarRaw))
);S3 presigned URL calculations dropped from 400+ signatures to only 15, removing the CPU bottleneck entirely and cutting API response times from 10+ seconds to under 200ms.
4. Frontend Chunk Loading & Skeletons
To match the backend optimization, I rebuilt the React frontend to load in chunks.
- On page load, the initial skeleton loader displays while fetching page 1.
- Once loaded, the skeletons are hidden, and the top 15 builders are rendered.
- Clicking "View More Builders" fetches the next page and appends the data in place. This prevents client-side screen blinks, avoiding full page refreshes and providing a premium user experience.
5. Instant True-Rank Payload
With paginated results, the frontend only has the top 15 records. If a logged-in user is ranked 142nd, how do we show their rank capsule at the bottom of the screen?
Previously, the frontend searched for the user locally in the loaded array. Since the array is now paginated, the user wouldn't appear, hiding their status card.
We solved this by having the server pre-calculate the requesting user's true rank index in the overall sorted list and inject it as a single metadata capsule in the response:
{
"leaderboard": [...15 records...],
"myRank": {
"userId": "user-123",
"rank": 142,
"points": 95,
"progress": 40
},
"hasMore": true
}This lets the browser display the builder's floating personal rank instantly on page load without needing to fetch the full list of builders.
6. Serverless Background Delegation via Lambda Self-Invocation
For massive email broadcasts, I replaced the failing background thread with an asynchronous Lambda Self-Invocation pattern.
When an admin broadcasts an email:
- If the recipient list is small ($\le 15$ users), the API executes synchronously and returns the results.
- If the list is large ($> 15$ users), the Lambda function invokes itself asynchronously using the
'Event'invocation type and returns aqueued: truepayload to the client instantly (within 100ms).
import { LambdaClient, InvokeCommand } from '@aws-sdk/client-lambda';
const lambda = new LambdaClient({ region: process.env.AWS_REGION });
await lambda.send(new InvokeCommand({
FunctionName: process.env.AWS_LAMBDA_FUNCTION_NAME,
InvocationType: 'Event', // Non-blocking async execution
Payload: Buffer.from(JSON.stringify({
action: 'SEND_BULK_EMAILS',
emails: emailsToProcess,
fromEmail: resolvedFrom
}))
}));Because AWS handles Lambda asynchronous invocations out-of-band, Lambda allows the background function to run for up to 15 minutes, safely bypassing API Gateway’s 29-second timeout!
Why Lambda Asynchronous Invocation instead of AWS SQS?
A common question when designing background workers on AWS is: "Why not use SQS (Simple Queue Service) or a message broker?"
While SQS is the industry-standard pattern for message queuing, it comes with extra architecture overhead:
- You have to provision and manage an SQS queue resource.
- You have to write a separate consumer Lambda function triggered by SQS.
- Since I built this as a dedicated community product and operational tool to help my community scale, I wanted to keep the AWS infrastructure footprint highly efficient, cost-effective, and easy to deploy.
Using Lambda asynchronous self-invocation allowed me to reuse my existing API Lambda function as its own background worker. It required zero extra resources and zero extra cost, making it a highly optimized solution for our product's operational scale.
The Results: 99.9% Reduction in Reads per Page Load
After deploying these changes, the results were night and day:
- API Response Time: Slashed from 10+ seconds to less than 200ms.
- Database Consumption: Swapping scans with indexed cache queries reduced database read consumption per page load by 99.9%.
- Broadcast Deliverability: Broad cohort emails are now delivered reliably without timeouts or dropped threads.
Lessons Learned
- Don't trust background threads on serverless: If you need background execution in AWS Lambda, delegate it via asynchronous invocation, SQS, or Step Functions.
- Be careful with cryptographic loops: Heavy operations like S3 URL signing or bcrypt hashing in loops can easily bottleneck single-threaded runtimes.
- Paginate early: Slicing arrays client-side is fine for mock databases, but a death sentence for database scaling. Slice on the server.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article