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 in nodejs-best-practices and api-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 DefaultWhy It's Wrongβœ… Mobile-Correct
Same API for web and mobileMobile needs compact responsesSeparate mobile endpoints OR field selection
Full object responsesWastes bandwidth, batteryPartial responses, pagination
No offline considerationApp crashes without networkOffline-first design, sync queues
WebSocket for everythingBattery drainPush notifications + polling fallback
No app versioningCan't force updates, breaking changesVersion headers, minimum version check
Generic error messagesUsers can't fix issuesMobile-specific error codes + recovery actions
Session-based authMobile apps restartToken-based with refresh
Ignore device infoCan't debug issuesDevice 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

TypeUse CaseUser Sees
DisplayNew message, order updateNotification banner
SilentBackground sync, content updateNothing (background)
DataCustom handling by appDepends on app logic

Anti-Patterns

❌ NEVERβœ… ALWAYS
Send sensitive data in pushPush says "New message", app fetches content
Overload with pushesBatch, dedupe, respect quiet hours
Same message to allSegment by user preference, timezone
Ignore failed tokensClean up invalid tokens regularly
Skip APNs for iOSFCM 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 user

2. 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 confirmation

Conflict Resolution Strategies

StrategyHow It WorksBest For
Last-write-winsLatest timestamp overwritesSimple data, single user
Server-winsServer always authoritativeCritical transactions
Client-winsOffline changes prioritizedOffline-heavy apps
MergeCombine changes field-by-fieldDocuments, rich content
CRDTMathematically conflict-freeReal-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 response

3. Mobile API Optimization

Response Size Reduction

TechniqueSavingsImplementation
Field selection30-70%?fields=id,name,thumbnail
Compression60-80%gzip/brotli (automatic)
PaginationVariesCursor-based for mobile
Image variants50-90%/image?w=200&q=80
Delta sync80-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 performance

Batch 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 devices

Silent 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 β†’ Continue

6. 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 RangeCategoryMobile Handling
400-499Client errorShow message, user action needed
401Auth expiredSilent refresh or re-login
403ForbiddenShow upgrade/permission screen
404Not foundRemove from local cache
409ConflictShow sync conflict UI
429Rate limitRetry after header, backoff
500-599Server errorRetry with backoff, show "try later"
NetworkNo connectionUse 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=31536000

Chunked 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 URL

Streaming 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 offline

8. 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 fails

Request 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/Istanbul

What 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.

Source: https://github.com/davila7/claude-code-templates/blob/main/cli-tool/components/skills/creative-design/mobile-design/mobile-backend.md

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.