Implementing Long-Running Operations

1. Returning 202 Accepted

Example: 202 with Operation Location

POST /reports HTTP/1.1
Content-Type: application/json

{"type": "annual", "year": 2025}

HTTP/1.1 202 Accepted
Location: /operations/abc-123
Content-Type: application/json

{
  "id": "abc-123",
  "status": "queued",
  "links": {"self": "/operations/abc-123"}
}

2. Providing Operation Status Endpoint

EndpointPurpose
GET /operations/{id}Current status + progress
DELETE /operations/{id}Cancel operation
GET /operations/{id}/resultFinal result (when status=completed)

3. Using Polling for Status Updates

StrategyNotes
Fixed intervalSimple; wasteful for slow ops
Exponential backoffStart 1s, double up to 60s
Server-suggestedRetry-After in 202/200 response

4. Implementing Callback URLs

Example: Webhook Callback Registration

POST /reports
{
  "type": "annual",
  "callbackUrl": "https://client.example.com/hooks/report-done",
  "callbackSecret": "shared-secret"
}

5. Using WebSockets for Real-Time Updates

PropertyNotes
BidirectionalServer → client push, client → server messages
Persistent connectionSingle TCP, low overhead per message
Use caseChat, live dashboards, collaborative editing
AuthToken in connection URL or first message

6. Using Server-Sent Events

PropertyNotes
DirectionServer → client only
Content-Typetext/event-stream
Auto-reconnectBuilt into EventSource API
Last-Event-IDResume from last received event
Use caseNotifications, progress, log tailing

Example: SSE Stream

id: 1
event: progress
data: {"percent": 25}

id: 2
event: progress
data: {"percent": 50}

id: 3
event: completed
data: {"resultUrl": "/reports/123"}

7. Implementing Operation Cancellation

MethodURI
DELETE /operations/{id}Standard cancel
POST /operations/{id}/cancelAction-style
Status aftercancellingcancelled

8. Providing Progress Information

FieldType
statusqueued, running, completed, failed, cancelled
progress0.0 - 1.0
currentStep / totalStepsMulti-stage ops
messageHuman-readable detail
startedAt / etaSecondsTiming info

9. Handling Operation Expiration

EventBehavior
Result expires410 Gone with retention policy
Status record TTLKeep 7-30 days
Generated artifactsPre-signed URL with expiry

10. Returning Final Result Location

FieldExample
resultUrlURL to download/view result
Location headerOn final completion redirect
Embedded resultFor small results, inline in status response