
A Serverless Reference Architecture for Mobile App Development on AWS: What We Shipped, What Broke, and What It Cost
A hands-on breakdown of a serverless mobile backend on AWS — AppSync, DynamoDB, Cognito, Lambda — including offline sync, cold starts, and a real cost model.
Most mobile app development write-ups stop at the happy path: wire up Amplify, deploy, screenshot the demo. The interesting part starts three months later, when you have real users on bad networks, a DynamoDB table that has outgrown its original access patterns, and a finance team asking why the bill moved.
This is a write-up of a field-service mobile app we built and ran on AWS — a scheduling and job-reporting app used by technicians who spend most of their day in basements, lifts, and rural sites with two bars of signal. The connectivity profile drove almost every architectural decision, so I'll be explicit about where our constraints were unusual and where the pattern generalises.
Nothing here is theoretical. Every gotcha in the second half of this article cost us at least a day.
1. AppSync over API Gateway + REST
We started with API Gateway and moved to AppSync at about month four. The reason was not GraphQL fashion — it was subscriptions.
Our dispatchers reassign jobs during the day, and the technician's phone needs to know within seconds. On REST we were polling every 30 seconds, which meant 2,880 requests per device per working day doing nothing but returning
304 Not Modified . AppSync subscriptions replaced that with a WebSocket connection that pushes only on actual change.The second reason was over-fetching. A job detail screen needed data from four entities. On REST that was four round-trips or one bloated endpoint we kept versioning. GraphQL let the client declare exactly what that screen needed.
If your app is request/response with no real-time requirement, stay on API Gateway. AppSync adds a schema, a resolver layer, and a mental model your whole team has to learn. It is not free complexity.
2. DynamoDB single-table design
One table,
JobsTable , with a generic partition/sort key and two GSIs. Here is the access pattern map we wrote before writing any code — and I cannot overstate how much pain this document saved:# | Access pattern | Index | PK | SK |
|---|---|---|---|---|
1 | Get technician's jobs for a date | base | TECH#<id> | JOB#<date>#<jobId> |
2 | Get one job with all line items | base | JOB#<jobId> | begins_with(ITEM#) |
3 | Get all jobs at a customer site | GSI1 | SITE#<siteId> | JOB#<date> |
4 | Get unassigned jobs in a region | GSI2 | REGION#<r>#UNASSIGNED | JOB#<priority>#<date> |
5 | Get technician profile | base | TECH#<id> | PROFILE |
Pattern 4 is a sparse index — the
GSI2PK attribute only exists on items where assignedTo is null, and the resolver deletes the attribute on assignment. The item drops out of the index automatically. The dispatch board queries one small index instead of scanning and filtering. This trick is in the DynamoDB docs and it is still the single highest-leverage thing I know in NoSQL modelling.A Lambda resolver for pattern 1:
javascript
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";import { DynamoDBDocumentClient, QueryCommand } from "@aws-sdk/lib-dynamodb";
const client = DynamoDBDocumentClient.from(new DynamoDBClient({}));
export const handler = async (event) => { const { technicianId, date } = event.arguments;
// Identity check against the Cognito claim, not the argument. const callerSub = event.identity?.claims?.sub; if (callerSub !== technicianId && !isDispatcher(event.identity)) { throw new Error("Unauthorized"); }
const { Items } = await client.send(new QueryCommand({ TableName: process.env.TABLE_NAME, KeyConditionExpression: "PK = :pk AND begins_with(SK, :sk)", ExpressionAttributeValues: { ":pk": `TECH#${technicianId}`, ":sk": `JOB#${date}#` }, Limit: 50 }));
return Items ?? [];};Note the authorization check. Early on we trusted
event.arguments.technicianId and any authenticated user could read any technician's schedule by changing one field in the request. It was caught in review. Authorize against the token claim, never against a client-supplied argument.3. Cognito with a pre-token-generation trigger
Cognito User Pools handles sign-in; Identity Pools vends temporary IAM credentials for direct S3 uploads. The useful piece is the pre-token-generation Lambda trigger, which injects the technician's region and role into the JWT as custom claims. AppSync then uses those claims in
@auth rules, so authorization happens at the resolver layer with no extra database lookup on every request.The trade-off: claims are baked in at token issue. A permission change does not take effect until the token refreshes. We set a one-hour access token TTL and added a forced-refresh path for role changes.
4. S3 presigned URLs for photos, never through the API
Technicians upload 5–20 photos per job. Routing those bytes through Lambda would have meant base64 payloads, the 6 MB synchronous invocation limit, and paying for Lambda duration to move data. Instead the client requests a presigned
PUT , uploads straight to S3, and an S3 event notification triggers the resize pipeline.This is the pattern most teams get wrong first, and it is a good diagnostic question to ask any mobile app development company you are evaluating: how do file uploads reach storage? If the answer routes binaries through the application tier, expect timeouts and a bill that scales with megabytes.
The hard part: offline sync
Everything above is standard. Offline is where we lost a month.
Amplify DataStore gives you a local store, automatic sync, and conflict resolution. Out of the box the conflict strategy is Auto Merge, which resolves field-by-field and is fine for independent fields. It is wrong for anything with an invariant across fields.
Our failure case: a technician marks a job
COMPLETE offline and sets completedAt . Meanwhile a dispatcher cancels the same job. Auto Merge produced a job that was CANCELLED with a completedAt timestamp — a state our reporting pipeline had no handling for, and which quietly corrupted a week of completion metrics before anyone noticed.We moved to a Custom strategy backed by a Lambda that understands the state machine:
javascript
const TERMINAL = new Set(["CANCELLED", "VOIDED"]);
export const handler = async (event) => { const { existingItem, newItem } = event; // 'existing' = server-side truth
// A terminal server state always wins, regardless of client timestamp. if (TERMINAL.has(existingItem.status)) { return { action: "REJECT", ...existingItem }; }
// Offline field notes are additive — never let a stale sync drop them. const mergedNotes = mergeNotesById(existingItem.notes, newItem.notes);
return { action: "RESOLVE", ...newItem, notes: mergedNotes, _version: existingItem._version };};Two lessons generalise beyond our domain:
Timestamps from client devices are untrustworthy. Phone clocks drift, and one of our devices was 40 minutes off. Last-writer-wins on a client timestamp is a data-loss bug waiting to happen. Use the server-side
_version from DataStore, or a server-assigned sequence.Decide your conflict policy per model, not per app. Job status needed strict server authority. Field notes needed additive merge. A single global strategy could not express both. Any serious discussion of mobile app development solutions for offline-first products should start with this table — model by model, what wins and why — not with a framework choice.
Cold starts, and what actually helped
Our p99 on the job-detail resolver was around 1.9 seconds. Users described the app as "slow to open" even though the median was under 300 ms.
What we tried, in order of how much it helped:
- Moving reads off Lambda entirely. Simple CRUD went to AppSync's direct DynamoDB resolvers — VTL or JavaScript resolvers, no Lambda in the path. This removed cold starts from about 70% of our traffic. Biggest win by a wide margin, and it also cut cost.
- Trimming the bundle. We were importing the entire AWS SDK v2. Moving to modular v3 clients and bundling with esbuild took the artifact from 14 MB to under 2 MB and cut initialisation meaningfully.
- Moving client construction outside the handler. Standard advice, genuinely effective — the client is reused across warm invocations.
- Provisioned concurrency. It works, but it costs money whether or not it is used. We applied it to exactly one function — the login-time bootstrap resolver — on a scheduled scaling policy covering the 06:00–08:00 shift-start spike. Applying it broadly would have erased the economics of going serverless.
The general principle: the fastest Lambda is the one you deleted.
Cost model
I am not going to publish our invoice, because our traffic mix will not match yours and a copied number is worse than no number. Instead, here is the shape of the model so you can run it yourself in the AWS Pricing Calculator against your own assumptions.
Component | What drives the cost | Where our spend concentrated |
|---|---|---|
AppSync | Query/mutation operations + connection-minutes for subscriptions | Subscriptions, not queries — see below |
DynamoDB | On-demand read/write request units; storage | Low; single-table kept RCU/WCU efficient |
Lambda | GB-seconds + requests | Fell sharply after moving reads to direct resolvers |
S3 + CloudFront | Storage, PUT requests, egress | Photo-heavy; lifecycle rules mattered |
Cognito | Monthly active users | Predictable, scaled linearly |
Data transfer | Egress | Underestimated in our first model |
The line that surprised us was AppSync subscription connection-minutes. We were billed for the duration a device held an open WebSocket, not for messages delivered. Technicians left the app foregrounded all day. Once we tore down subscriptions on background and re-established on foreground, that line dropped by roughly half.
Two habits worth adopting on day one, before the bill teaches you:
- Tag every resource with an
appandenvtag and enable Cost Allocation Tags. Without this you cannot answer "what does this feature cost?"
- Set an S3 lifecycle policy on user-generated media immediately. Job photos were legally required for 24 months but read almost exclusively in the first 14 days. Transitioning to Infrequent Access and then Glacier Instant Retrieval was one afternoon of work against a cost that otherwise compounds forever.
Five things I would tell my past self
- Write the access-pattern table before the schema. Retrofitting a fifth access pattern onto a live single-table design means a migration, and migrations on a table with an offline-syncing client are genuinely unpleasant.
- Test on a real degraded network, not airplane mode. Airplane mode is a clean disconnect. Reality is 2% packet loss and eight-second latency, which is a completely different failure mode. Use the Network Link Conditioner on iOS and Android Studio's network throttling.
- Run on real devices before launch. AWS Device Farm caught a Cognito token-refresh failure on a specific older Android build that no emulator reproduced.
- Budget for the schema-to-client codegen loop. Every GraphQL schema change means regenerating client models and a mobile release. Backend and mobile release cadences are not the same, and pretending otherwise causes version-skew bugs. Version your schema and support N-1 clients.
- Instrument before optimising. We spent a week tuning a Lambda that turned out to account for 3% of user-perceived latency. X-Ray traces would have pointed us at the right function on day one.
Wrapping up
Serverless mobile app development on AWS is a genuinely good default for this class of application — bursty traffic, unpredictable growth, a small team that cannot afford to run infrastructure. The managed pieces did what they promised.
What the marketing around mobile app development services rarely conveys is that the difficulty moves rather than disappears. You stop tuning instances and start reasoning about conflict resolution, token lifetimes, index sparsity, and per-model consistency guarantees. That work is not smaller. It is just further up the stack, and it is much harder to outsource, because it lives in your domain rules rather than in your infrastructure.
If you are running a similar architecture, I would genuinely like to hear how you handled conflict resolution — it is the part of this stack where I am least confident there is a single right answer. Leave a comment.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article