Request Lifecycle

Detailed flow of API requests through Appizer's system

Detailed visualization of how API requests are processed through Appizer's system.infrastructure.

Complete Request Flow

<DiagramWrapper
title="API Request Lifecycle"
description="From client request to database storage"
chart={`
sequenceDiagram
participant Client
participant Gateway as API Gateway
participant Auth as Auth Service
participant Validator
participant Queue as Message Queue
participant Processor
participant DB as Database
participant Cache

text
Client->>Gateway: POST /v1/events/track
Gateway->>Auth: Validate API Key
Auth-->>Gateway: ✓ Authenticated

Gateway->>Validator: Validate Request
Validator->>Validator: Check Schema
Validator->>Validator: Validate Types
Validator-->>Gateway: ✓ Valid

Gateway->>Queue: Enqueue Event
Queue-->>Gateway: ✓ Queued
Gateway-->>Client: 202 Accepted

Queue->>Processor: Consume Event
Processor->>Processor: Enrich Data
Processor->>Processor: Transform
Processor->>DB: Store Event
DB-->>Processor: ✓ Stored

Processor->>Cache: Update Metrics
Cache-->>Processor: ✓ Updated

`}
relatedLinks={[
{ label: 'System Flow', href: '/docs/diagrams/system-flow' },
{ label: 'API Overview', href: '/docs/api/overview' }
]}
/>

Request Phases

1. Authentication

Every request must include a valid API key:

typescript
headers: {
  'Authorization': 'Bearer sk_live_abc123...',
  'Content-Type': 'application/json'
}

<DiagramWrapper
title="Authentication Flow"
description="How API keys are validated"
chart={`
flowchart TD
Start([Request Received])
CheckHeader{Has Auth Header?}
ExtractKey[Extract API Key]
ValidateKey{Valid Key?}
CheckPerms{Has Permission?}
Allow[Allow Request]
Deny401[Return 401]
Deny403[Return 403]

text
Start --> CheckHeader
CheckHeader -->|No| Deny401
CheckHeader -->|Yes| ExtractKey
ExtractKey --> ValidateKey
ValidateKey -->|No| Deny401
ValidateKey -->|Yes| CheckPerms
CheckPerms -->|No| Deny403
CheckPerms -->|Yes| Allow

style Allow fill:#e8f5e9,stroke:#388e3c
style Deny401 fill:#ffebee,stroke:#c62828
style Deny403 fill:#ffebee,stroke:#c62828

`}
relatedLinks={[
{ label: 'Authentication', href: '/docs/api/authentication' }
]}
/>

2. Validation

Request payload is validated against schema:

Checks performed:

  • Required fields present
  • Data types correct
  • Values within allowed ranges
  • Payload size within limits
typescript
// Validation rules
{
  event: { type: 'string', required: true, maxLength: 100 },
  userId: { type: 'string', required: false, maxLength: 255 },
  properties: { type: 'object', required: false, maxSize: 10000 }
}

3. Rate Limiting

Requests are checked against rate limits:

<DiagramWrapper
title="Rate Limiting"
description="Token bucket algorithm"
chart={`
stateDiagram-v2
[*] --> CheckBucket
CheckBucket --> HasTokens: Tokens Available
CheckBucket --> NoTokens: Bucket Empty

text
HasTokens --> ConsumeToken
ConsumeToken --> ProcessRequest
ProcessRequest --> [*]

NoTokens --> Return429
Return429 --> [*]

`}
relatedLinks={[
{ label: 'Rate Limits', href: '/docs/api/rate-limits' }
]}
/>

Default limits:

  • 1000 requests per minute
  • 10,000 events per hour
  • Burst capacity: 100 requests

4. Queueing

Valid requests are queued for async processing:

typescript
// Queue message format
{
  id: 'msg_abc123',
  timestamp: '2024-01-15T10:30:00Z',
  payload: {
    event: 'purchase_completed',
    userId: 'user_123',
    properties: { amount: 99.99 }
  },
  metadata: {
    apiKey: 'sk_***',
    ip: '192.168.1.1',
    userAgent: 'Mozilla/5.0...'
  }
}

5. Processing

Events are processed asynchronously:

  1. Enrichment
    Add geo-location, device info, and timestamps
  2. Transformation
    Normalize data formats and apply business rules
  3. Validation
    Final validation before storage
  4. Storage
    Write to database with indexes
  5. Cache Update
    Update real-time metrics cache

6. Response

Client receives immediate acknowledgment:

json
{
  "success": true,
  "eventId": "evt_abc123",
  "timestamp": "2024-01-15T10:30:00Z"
}

Error Handling Flow

<DiagramWrapper
title="Error Handling"
description="How errors are processed and returned"
chart={`
flowchart TD
Error[Error Occurs]
Type{Error Type}
Auth[Authentication Error]
Valid[Validation Error]
Rate[Rate Limit Error]
Server[Server Error]

text
Log[Log Error]
Metrics[Update Metrics]
Response[Return Error Response]
Retry{Retryable?}
Queue[Add to Retry Queue]
Alert[Send Alert]

Error --> Type
Type -->|401/403| Auth
Type -->|400| Valid
Type -->|429| Rate
Type -->|500| Server

Auth --> Log
Valid --> Log
Rate --> Log
Server --> Log

Log --> Metrics
Metrics --> Response
Response --> Retry

Retry -->|Yes| Queue
Retry -->|No| Alert

style Error fill:#ffebee,stroke:#c62828
style Response fill:#fff3e0,stroke:#f57c00

`}
relatedLinks={[
{ label: 'Error Handling', href: '/docs/api/errors' }
]}
/>

Performance Characteristics

Latency Breakdown

Phase Typical Latency Notes
Authentication 5-10ms Cached lookups
Validation 2-5ms Schema validation
Rate limiting 1-2ms In-memory check
Queueing 5-10ms Message queue write
Total (sync) 15-30ms Client receives response
Processing 50-100ms Async, not blocking
Storage 20-50ms Database write
Total (async) 70-150ms Event fully processed

Throughput

  • Single event: 1,000 requests/sec
  • Batch events: 25,000 events/sec
  • Peak capacity: 100,000 events/sec

Retry Logic

Failed requests are automatically retried:

<DiagramWrapper
title="Retry Strategy"
description="Exponential backoff with jitter"
chart={`
graph LR
Attempt1[Attempt 1]
Wait1[Wait 1s]
Attempt2[Attempt 2]
Wait2[Wait 2s]
Attempt3[Attempt 3]
Wait3[Wait 4s]
Attempt4[Attempt 4]
Success[Success]
DLQ[Dead Letter Queue]

text
Attempt1 -->|Fail| Wait1
Wait1 --> Attempt2
Attempt2 -->|Fail| Wait2
Wait2 --> Attempt3
Attempt3 -->|Fail| Wait3
Wait3 --> Attempt4
Attempt4 -->|Fail| DLQ

Attempt1 -->|Success| Success
Attempt2 -->|Success| Success
Attempt3 -->|Success| Success
Attempt4 -->|Success| Success

style Success fill:#e8f5e9,stroke:#388e3c
style DLQ fill:#ffebee,stroke:#c62828

`}
relatedLinks={[
{ label: 'Best Practices', href: '/docs/guides/best-practices' }
]}
/>

Retry configuration:

  • Max retries: 4
  • Initial delay: 1 second
  • Backoff multiplier: 2x
  • Max delay: 60 seconds
  • Jitter: ±20%

Monitoring

Track request lifecycle metrics:

typescript
// Metrics collected
{
  requestId: 'req_abc123',
  phases: {
    authentication: { duration: 8, status: 'success' },
    validation: { duration: 3, status: 'success' },
    rateLimiting: { duration: 1, status: 'success' },
    queueing: { duration: 7, status: 'success' },
    processing: { duration: 85, status: 'success' }
  },
  totalDuration: 104,
  status: 'completed'
}

Best Practices

Client-Side

  1. Implement timeouts: Don't wait indefinitely
  2. Handle 202 responses: Request accepted, processing async
  3. Retry on failures: Use exponential backoff
  4. Batch when possible: Reduce request overhead

Server-Side

  1. Validate before sending: Catch errors early
  2. Use idempotency keys: Prevent duplicates
  3. Monitor latency: Track performance
  4. Log request IDs: Aid debugging

Next Steps

On this page