GuideOpen
Mobile Backend Patterns
This file covers backend/API patterns SPECIFIC to mobile clients. Generic backend patterns are in nodejs-best-practices and api-patterns. Mobile backend is NOT the same as web backend. Different constraints, different patterns.
Mobile Backend Patterns
This file covers backend/API patterns SPECIFIC to mobile clients. Generic backend patterns are innodejs-best-practicesandapi-patterns. Mobile backend is NOT the same as web backend. Different constraints, different patterns.
π§ MOBILE BACKEND MINDSET
Mobile clients are DIFFERENT from web clients:
βββ Unreliable network (2G, subway, elevator)
βββ Battery constraints (minimize wake-ups)
βββ Limited storage (can't cache everything)
βββ Interrupted sessions (calls, notifications)
βββ Diverse devices (old phones to flagships)
βββ Binary updates are slow (App Store review)Your backend must compensate for ALL of these.
π« AI MOBILE BACKEND ANTI-PATTERNS
These are common AI mistakes when building mobile backends:
| β AI Default | Why It's Wrong | β Mobile-Correct |
|---|---|---|
| Same API for web and mobile | Mobile needs compact responses | Separate mobile endpoints OR field selection |
| Full object responses | Wastes bandwidth, battery | Partial responses, pagination |
| No offline consideration | App crashes without network | Offline-first design, sync queues |
| WebSocket for everything | Battery drain | Push notifications + polling fallback |
| No app versioning | Can't force updates, breaking changes | Version headers, minimum version check |
| Generic error messages | Users can't fix issues | Mobile-specific error codes + recovery actions |
| Session-based auth | Mobile apps restart | Token-based with refresh |
| Ignore device info | Can't debug issues | Device ID, app version in headers |
1. Push Notifications
Platform Architecture
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β YOUR BACKEND β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β β
β ββββββββββββ΄βββββββββββ β
β βΌ βΌ β
β βββββββββββββββββββ βββββββββββββββββββ β
β β FCM (Google) β β APNs (Apple) β β
β β Firebase β β Direct or FCM β β
β ββββββββββ¬βββββββββ ββββββββββ¬βββββββββ β
β β β β
β βΌ βΌ β
β βββββββββββββββββββ βββββββββββββββββββ β
β β Android Device β β iOS Device β β
β βββββββββββββββββββ βββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββPush Types
| Type | Use Case | User Sees |
|---|---|---|
| Display | New message, order update | Notification banner |
| Silent | Background sync, content update | Nothing (background) |
| Data | Custom handling by app | Depends on app logic |
Anti-Patterns
| β NEVER | β ALWAYS |
|---|---|
| Send sensitive data in push | Push says "New message", app fetches content |
| Overload with pushes | Batch, dedupe, respect quiet hours |
| Same message to all | Segment by user preference, timezone |
| Ignore failed tokens | Clean up invalid tokens regularly |
| Skip APNs for iOS | FCM alone doesn't guarantee iOS delivery |
Token Management
TOKEN LIFECYCLE:
βββ App registers β Get token β Send to backend
βββ Token can change β App must re-register on start
βββ Token expires β Clean from database
βββ User uninstalls β Token becomes invalid (detect via error)
βββ Multiple devices β Store multiple tokens per user2. Offline Sync & Conflict Resolution
Sync Strategy Selection
WHAT TYPE OF DATA?
β
βββ Read-only (news, catalog)
β βββ Simple cache + TTL
β βββ ETag/Last-Modified for invalidation
β
βββ User-owned (notes, todos)
β βββ Last-write-wins (simple)
β βββ Or timestamp-based merge
β
βββ Collaborative (shared docs)
β βββ CRDT or OT required
β βββ Consider Firebase/Supabase
β
βββ Critical (payments, inventory)
βββ Server is source of truth
βββ Optimistic UI + server confirmationConflict Resolution Strategies
| Strategy | How It Works | Best For |
|---|---|---|
| Last-write-wins | Latest timestamp overwrites | Simple data, single user |
| Server-wins | Server always authoritative | Critical transactions |
| Client-wins | Offline changes prioritized | Offline-heavy apps |
| Merge | Combine changes field-by-field | Documents, rich content |
| CRDT | Mathematically conflict-free | Real-time collaboration |
Sync Queue Pattern
CLIENT SIDE:
βββ User makes change β Write to local DB
βββ Add to sync queue β { action, data, timestamp, retries }
βββ Network available β Process queue FIFO
βββ Success β Remove from queue
βββ Failure β Retry with backoff (max 5 retries)
βββ Conflict β Apply resolution strategy
SERVER SIDE:
βββ Accept change with client timestamp
βββ Compare with server version
βββ Apply conflict resolution
βββ Return merged state
βββ Client updates local with server response3. Mobile API Optimization
Response Size Reduction
| Technique | Savings | Implementation |
|---|---|---|
| Field selection | 30-70% | ?fields=id,name,thumbnail |
| Compression | 60-80% | gzip/brotli (automatic) |
| Pagination | Varies | Cursor-based for mobile |
| Image variants | 50-90% | /image?w=200&q=80 |
| Delta sync | 80-95% | Only changed records since timestamp |
Pagination: Cursor vs Offset
OFFSET (Bad for mobile):
βββ Page 1: OFFSET 0 LIMIT 20
βββ Page 2: OFFSET 20 LIMIT 20
βββ Problem: New item added β duplicates!
βββ Problem: Large offset = slow query
CURSOR (Good for mobile):
βββ First: ?limit=20
βββ Next: ?limit=20&after=cursor_abc123
βββ Cursor = encoded (id + sort values)
βββ No duplicates on data changes
βββ Consistent performanceBatch Requests
Instead of:
GET /users/1
GET /users/2
GET /users/3
(3 round trips, 3x latency)
Use:
POST /batch
{ requests: [
{ method: "GET", path: "/users/1" },
{ method: "GET", path: "/users/2" },
{ method: "GET", path: "/users/3" }
]}
(1 round trip)4. App Versioning
Version Check Endpoint
GET /api/app-config
Headers:
X-App-Version: 2.1.0
X-Platform: ios
X-Device-ID: abc123
Response:
{
"minimum_version": "2.0.0",
"latest_version": "2.3.0",
"force_update": false,
"update_url": "https://apps.apple.com/...",
"feature_flags": {
"new_player": true,
"dark_mode": true
},
"maintenance": false,
"maintenance_message": null
}Version Comparison Logic
CLIENT VERSION vs MINIMUM VERSION:
βββ client >= minimum β Continue normally
βββ client < minimum β Show force update screen
β βββ Block app usage until updated
βββ client < latest β Show optional update prompt
FEATURE FLAGS:
βββ Enable/disable features without app update
βββ A/B testing by version/device
βββ Gradual rollout (10% β 50% β 100%)5. Authentication for Mobile
Token Strategy
ACCESS TOKEN:
βββ Short-lived (15 min - 1 hour)
βββ Stored in memory (not persistent)
βββ Used for API requests
βββ Refresh when expired
REFRESH TOKEN:
βββ Long-lived (30-90 days)
βββ Stored in SecureStore/Keychain
βββ Used only to get new access token
βββ Rotate on each use (security)
DEVICE TOKEN:
βββ Identifies this device
βββ Allows "log out all devices"
βββ Stored alongside refresh token
βββ Server tracks active devicesSilent Re-authentication
REQUEST FLOW:
βββ Make request with access token
βββ 401 Unauthorized?
β βββ Have refresh token?
β β βββ Yes β Call /auth/refresh
β β β βββ Success β Retry original request
β β β βββ Failure β Force logout
β β βββ No β Force logout
β βββ Token just expired (not invalid)
β βββ Auto-refresh, user doesn't notice
βββ Success β Continue6. Error Handling for Mobile
Mobile-Specific Error Format
{
"error": {
"code": "PAYMENT_DECLINED",
"message": "Your payment was declined",
"user_message": "Please check your card details or try another payment method",
"action": {
"type": "navigate",
"destination": "payment_methods"
},
"retry": {
"allowed": true,
"after_seconds": 5
}
}
}Error Categories
| Code Range | Category | Mobile Handling |
|---|---|---|
| 400-499 | Client error | Show message, user action needed |
| 401 | Auth expired | Silent refresh or re-login |
| 403 | Forbidden | Show upgrade/permission screen |
| 404 | Not found | Remove from local cache |
| 409 | Conflict | Show sync conflict UI |
| 429 | Rate limit | Retry after header, backoff |
| 500-599 | Server error | Retry with backoff, show "try later" |
| Network | No connection | Use cached data, queue for sync |
7. Media & Binary Handling
Image Optimization
CLIENT REQUEST:
GET /images/{id}?w=400&h=300&q=80&format=webp
SERVER RESPONSE:
βββ Resize on-the-fly OR use CDN
βββ WebP for Android (smaller)
βββ HEIC for iOS 14+ (if supported)
βββ JPEG fallback
βββ Cache-Control: max-age=31536000Chunked Upload (Large Files)
UPLOAD FLOW:
1. POST /uploads/init
{ filename, size, mime_type }
β { upload_id, chunk_size }
2. PUT /uploads/{upload_id}/chunks/{n}
β Upload each chunk (1-5 MB)
β Can resume if interrupted
3. POST /uploads/{upload_id}/complete
β Server assembles chunks
β Return final file URLStreaming Audio/Video
REQUIREMENTS:
βββ HLS (HTTP Live Streaming) for iOS
βββ DASH or HLS for Android
βββ Multiple quality levels (adaptive bitrate)
βββ Range request support (seeking)
βββ Offline download chunks
ENDPOINTS:
GET /media/{id}/manifest.m3u8 β HLS manifest
GET /media/{id}/segment_{n}.ts β Video segment
GET /media/{id}/download β Full file for offline8. Security for Mobile
Device Attestation
VERIFY REAL DEVICE (not emulator/bot):
βββ iOS: DeviceCheck API
β βββ Server verifies with Apple
βββ Android: Play Integrity API (replaces SafetyNet)
β βββ Server verifies with Google
βββ Fail closed: Reject if attestation failsRequest Signing
CLIENT:
βββ Create signature = HMAC(timestamp + path + body, secret)
βββ Send: X-Signature: {signature}
βββ Send: X-Timestamp: {timestamp}
βββ Send: X-Device-ID: {device_id}
SERVER:
βββ Validate timestamp (within 5 minutes)
βββ Recreate signature with same inputs
βββ Compare signatures
βββ Reject if mismatch (tampering detected)Rate Limiting
MOBILE-SPECIFIC LIMITS:
βββ Per device (X-Device-ID)
βββ Per user (after auth)
βββ Per endpoint (stricter for sensitive)
βββ Sliding window preferred
HEADERS:
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1609459200
Retry-After: 60 (when 429)9. Monitoring & Analytics
Required Headers from Mobile
Every mobile request should include:
βββ X-App-Version: 2.1.0
βββ X-Platform: ios | android
βββ X-OS-Version: 17.0
βββ X-Device-Model: iPhone15,2
βββ X-Device-ID: uuid (persistent)
βββ X-Request-ID: uuid (per request, for tracing)
βββ Accept-Language: tr-TR
βββ X-Timezone: Europe/IstanbulWhat to Log
FOR EACH REQUEST:
βββ All headers above
βββ Endpoint, method, status
βββ Response time
βββ Error details (if any)
βββ User ID (if authenticated)
ALERTS:
βββ Error rate > 5% per version
βββ P95 latency > 2 seconds
βββ Specific version crash spike
βββ Auth failure spike (attack?)
βββ Push delivery failure spikeπ MOBILE BACKEND CHECKLIST
Before API Design
- [ ] Identified mobile-specific requirements?
- [ ] Planned offline behavior?
- [ ] Designed sync strategy?
- [ ] Considered bandwidth constraints?
For Every Endpoint
- [ ] Response as small as possible?
- [ ] Pagination cursor-based?
- [ ] Proper caching headers?
- [ ] Mobile error format with actions?
Authentication
- [ ] Token refresh implemented?
- [ ] Silent re-auth flow?
- [ ] Multi-device logout?
- [ ] Secure token storage guidance?
Push Notifications
- [ ] FCM + APNs configured?
- [ ] Token lifecycle managed?
- [ ] Silent vs display push defined?
- [ ] Sensitive data NOT in push payload?
Release
- [ ] Version check endpoint ready?
- [ ] Feature flags configured?
- [ ] Force update mechanism?
- [ ] Monitoring headers required?
Remember: Mobile backend must be resilient to bad networks, respect battery life, and handle interrupted sessions gracefully. The client cannot be trusted, but it also cannot be hung upβprovide offline capabilities and clear error recovery paths.
Author: davila7, Claude Code templates (davila7). License: MIT.
Shown here with formatting for the web. Keep the author and license notice when you reuse it.
Related entries
There are more like this in the members library
The Claude Code library holds 13,843 entries. Members can search all of them by meaning and read every one in full.