Model the work as a durable task
A synchronous API is appropriate when work finishes within a predictable request window and a failed call can be retried without ambiguity. Document extraction, generative AI inference, large reports, media conversion, cross-system synchronization, and IoT aggregation often violate those assumptions. Keeping the connection open simply moves the risk to a gateway, load balancer, client timeout, or deployment restart. The backend may finish successfully after the caller has already classified the request as failed and submitted it again.
A safer API accepts the command, creates a durable task, and promptly returns a task ID, an initial state, and a URL for status retrieval. Acceptance means the service has taken responsibility for processing; it does not mean the business operation succeeded. A practical state model includes queued, running, succeeded, failed, and canceled. Workflows that require approval or additional data may also need waiting_for_input. Define valid state transitions and prevent delayed events from moving a terminal task back into an active state.
Task creation also needs an idempotency key. If the caller times out and repeats the same command, the server should return the original task instead of scheduling duplicate work. Document the key's scope, retention period, and conflict behavior. Deriving identity only from a payload hash is risky because two legitimate business operations may intentionally contain identical data.
Use webhooks and polling as complementary mechanisms
Webhooks provide low-latency notification without continuous status traffic, but they are not a reliable message queue. The receiver can be unavailable, a proxy can time out, the sender can retry, and events can arrive out of order. Treat a webhook as a signal that the consumer should reconcile its local record with the authoritative task resource. Do not make one callback the only place where a result exists.
Polling is simpler to implement and inspect, and it naturally recovers from a missed notification. Its trade-off is load versus latency: aggressive polling creates unnecessary API and database traffic, while a long interval delays downstream work. In many integrations, the strongest design combines both approaches. Webhooks drive the normal fast path, while the status endpoint supports recovery, scheduled reconciliation, support tooling, and consumers that cannot receive inbound requests. When polling is the only option, use capped exponential backoff with jitter rather than a fixed interval.
- Prefer webhooks when completion latency matters, task duration varies widely, and the consumer can operate a verified public HTTPS endpoint.
- Prefer polling when inbound connectivity is unavailable, integration volume is modest, or the provider exposes only a status API.
- Use both when a lost notification must not strand a task and automatic recovery after downtime is required.
- Add reconciliation when the operation has significant business impact or crosses systems that cannot participate in one transaction.
Design retries, duplicates, and security into the normal path
A webhook receiver should verify the signature, timestamp, and event ID before persisting the event or placing it on an internal queue, then acknowledge it quickly. Expensive business processing should not run inside the callback request. Verify signatures against the raw request body, constrain timestamp skew to reduce replay risk, and support a short overlap during secret rotation. Callback URLs should not contain long-lived credentials, and receivers should not blindly fetch arbitrary URLs supplied in an event payload.
The sender should retry connection failures and non-success responses with backoff, subject to a maximum attempt count or delivery deadline. The receiver must assume that duplicate delivery will occur. Enforce uniqueness on the event ID and make downstream writes idempotent as well. Never depend on arrival order. Compare an event version, sequence number, or authoritative server timestamp before updating local state so that an older callback cannot overwrite a newer result.
Classify errors as transient or permanent. Rate limiting, temporary unavailability, and network failures are usually retryable. Invalid input, unsupported formats, and insufficient permissions generally require correction rather than another attempt. Expose stable, actionable error codes while keeping stack traces, credentials, and internal topology out of external responses. Large results should usually live in object storage and be retrieved through short-lived signed URLs instead of being embedded in callback bodies.
Build for diagnosis and recovery, not just completion
Carry a consistent task ID, request ID, and correlation ID through the API, queue, worker, outbound provider call, and webhook. Record when the task was created, its current state, the last state change, attempt counts, external identifiers, error classification, and completion time. Monitoring only HTTP error rates is insufficient. Tasks waiting too long in a queue, workers that stop renewing heartbeats, repeated callback delivery failures, and completed results that are never consumed can all indicate operational problems.
Plan explicitly for stuck work. A worker can renew a lease or heartbeat while processing, and a sweeper can identify expired tasks. The recovery action depends on the operation: safely reschedule idempotent work, mark unrecoverable work as failed, or route ambiguous cases for human review. Cancellation also requires precise semantics. It may prevent the next step without reversing an action already submitted to an external ERP, CRM, or cloud service. Multi-stage side effects often need compensating actions rather than an imaginary cross-system rollback.
Before release, test duplicate and out-of-order callbacks, total webhook loss, a timed-out creation request that actually succeeded, worker crashes immediately before and after result persistence, and prolonged rate limiting by a dependency. A production-ready asynchronous integration is not one whose happy path eventually finishes. It is one that can establish the current truth after an interruption, avoid repeating harmful side effects, and resume from a state that operators and software can independently verify.