Engineering

API Integration Best Practices: 12 Lessons From Production

Twelve API integration best practices learned from running integrations against Meta, X, LinkedIn, TikTok and YouTube in production, with TypeScript code for retries, idempotency and webhook verification.

API Integration Best Practices: 12 Lessons From Production

The most important API integration best practices are: treat tokens as expiring state, retry only what is safe to retry and make writes idempotent, respect each provider's rate limits, verify every webhook signature against the raw body, validate input at your boundary, and never let secrets leak into responses or logs. Versioning, structured errors and observability exist so you find out about upstream changes before your users do.

These lessons come from running integrations against a dozen social network APIs at once.

TL;DR

  • Model the full token lifecycle: refresh ahead of expiry, classify refresh failures as permanent or transient, and tell the user when they must reconnect.
  • Retry with exponential backoff and jitter, honor Retry-After, and generate the idempotency key once per operation, outside the retry loop.
  • Budget rate limits per provider. Some are per call, some are per day, some are per account, and the docs do not always agree with themselves.
  • Verify webhook HMAC signatures over the exact bytes received, with a constant-time compare. Every provider encodes it differently.
  • Validate with a schema at the edge, strip secrets at the response boundary, and return one error shape everywhere.
  • Pin API versions, track deprecation dates, and log the provider's trace ID on every failure.

What is API integration?

API integration is connecting two systems through their APIs so that data and actions flow between them without a human in the middle. Your app calls the provider's API to create, read or change something (publish a post, fetch analytics), and the provider calls you back through webhooks when something happens on its side (a new comment, a direct message).

A demo takes an afternoon. Production is the demo plus everything that happens when tokens expire, quotas run out and the provider ships a new version.

The 5 stages of API integration

  1. Discovery: read the docs, the terms, the rate limits, the app review requirements and the changelog. For social APIs, app review alone can take weeks (see social media API approval by platform).
  2. Design: decide on auth flow, data model, sync vs async, webhook vs polling, and how you map the provider's errors to yours.
  3. Build: implement against a sandbox or test account, with the failure paths written at the same time as the happy path.
  4. Test: unit tests with mocked responses, then contract tests against the real API, then a staged rollout to real users.
  5. Operate: monitor, alert, rotate credentials, track deprecations and migrate versions. This stage never ends and costs the most.

1. Read the docs, then distrust them

Why: provider docs are the contract, but they are written by people and they drift. How: read the reference, the rate limit page and the changelog before you design anything, then confirm every limit against the live API.

Example: Meta's Instagram content publishing guide limits accounts to 100 API-published posts per 24 hours, and a few sections later, under carousels, says 50. Both are on the page today. The fix is to query GET /<IG_ID>/content_publishing_limit and enforce the limit in your own scheduler rather than hardcoding either number.

2. Build for the full token lifecycle, not the first login

Why: OAuth is easy on day one and a top source of silent failures by day sixty. How: store expiry with every token, refresh ahead of expiry, and classify failures.

Lifetimes vary wildly. TikTok's token management docs list a 2-hour access token and a 180-day refresh token, and every refresh returns a new refresh token: keep using the old one and the user has to authorize again.

Our refresher runs daily and refreshes anything expiring within seven days, so each token gets several attempts before it dies. We do not widen that window: over-refreshing long-lived tokens just rotates refresh tokens for nothing. Short-lived tokens, like Reddit's one-hour access tokens, are refreshed on demand at the call site.

Most integrations get classification wrong. A 5xx or 429 during refresh is transient: retry it. A revoked refresh token is permanent: fail fast and notify the owner. Meta returns an expired token as HTTP 400 with "type": "OAuthException" and "code": 190 (Graph API error handling), not a 401, so status-code-only logic burns every retry on a dead token. On a permanent failure, Outstand emits an account.token_expired webhook so the customer can ask the user to reconnect. For Meta specifics, see long-lived page access tokens.

3. Retry with backoff, jitter and a budget

Why: networks fail, providers throttle, and naive retries turn a blip into a thundering herd. How: retry only network errors, 408, 425, 429 and 5xx; use exponential backoff with jitter; honor Retry-After; and cap total time, not just attempts.

The total-time cap matters most. An Instagram or Threads publish creates a container, polls its status, then publishes. We use one eight-minute budget for the whole publish, not one per container, because a 20-item carousel polls 21 containers and per-container timeouts multiply past the lifetime of the request hosting them.

Fit backoff to the operation. Meta recommends polling container status once per minute for up to five minutes, but most image containers are ready within seconds, so we poll at 1, 2, 3, 5, 10, 15, then 30 seconds. On LinkedIn, a comment posted right after a company page share can be rejected until the share propagates, so comments retry at 2, 4 and 8 seconds on transient errors only.

4. Make every write idempotent

Why: after a timeout you do not know whether the server processed the request, and retrying a non-idempotent write is how users get duplicate posts. How: send an idempotency key with every create, and generate it once per logical operation, outside the retry loop.

Outstand's POST /v1/posts accepts an Idempotency-Key header. Keys are remembered for 24 hours per organization, a retry while the first attempt is still running gets a 409 with Retry-After, and reusing a key with a different body gets a 422. Here is a retry wrapper that gets the details right:

ts
1const RETRYABLE = new Set([408, 425, 429, 500, 502, 503, 504]);
2
3async function createPostWithRetry(apiKey: string, payload: { content: string; accounts: string[] }) {
4	// One key per logical operation. Never regenerate it inside the loop.
5	const idempotencyKey = crypto.randomUUID();
6	const maxAttempts = 5;
7	const deadline = Date.now() + 60_000;
8
9	for (let attempt = 0; attempt < maxAttempts; attempt++) {
10		let response: Response | undefined;
11		try {
12			response = await fetch('https://api.outstand.so/v1/posts', {
13				method: 'POST',
14				headers: {
15					Authorization: `Bearer ${apiKey}`,
16					'Content-Type': 'application/json',
17					'Idempotency-Key': idempotencyKey,
18				},
19				body: JSON.stringify(payload),
20			});
21		} catch {
22			// Network error: the request may or may not have landed. Safe to retry with the same key.
23		}
24
25		if (response && !RETRYABLE.has(response.status) && response.status !== 409) return response;
26
27		const retryAfter = Number(response?.headers.get('Retry-After'));
28		const backoff = Math.min(30_000, 1000 * 2 ** attempt);
29		const delay = Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter * 1000 : Math.random() * backoff; // full jitter
30		if (Date.now() + delay > deadline) break;
31		await new Promise((resolve) => setTimeout(resolve, delay));
32	}
33	throw new Error('Post creation did not complete within the retry budget');
34}

One subtle case: if the post was stored but not queued, Outstand returns success: false with the post and scheduled: false, and replays that for the same key. A retry cannot tell "never queued" from "queued but the confirmation was lost", and guessing wrong publishes twice, so act on the returned post instead. See the idempotency docs.

5. Treat rate limits as a budget you plan, not an error you handle

Why: a 429 means you have already lost. How: know the shape of each provider's limit, read usage headers on every response, and enforce limits before you call.

Social APIs use very different shapes:

Provider

Limit shape

Where to read usage

Meta Graph API

Rolling percentage of app or business use case quota

X-App-Usage and X-Business-Use-Case-Usage response headers

Instagram publishing

100 API-published posts per account per 24 hours

GET /<IG_ID>/content_publishing_limit

YouTube Data API

100 videos.insert calls per day in their own bucket, 10,000 units for everything else, reset at midnight Pacific

Google Cloud console quotas page

X API

Per-endpoint, per-user or per-app windows, usually 15 minutes or 24 hours

x-rate-limit-remaining and x-rate-limit-reset headers

Sources: Meta rate limiting, YouTube quota costs, X rate limits. For what X access costs, see our X API pricing breakdown.

A daily quota shared across customers needs pacing, not just counting: if one customer schedules 100 uploads at 00:01 Pacific, nobody else uploads that day. We release YouTube upload capacity in intervals, cap each organization, and relax caps near reset. A denied upload carries a stable reason code and an estimated retryAt.

6. Verify every webhook signature over the raw body

Why: your webhook URL is public; without signature checks anyone can post fake events. How: compute an HMAC over the exact bytes received, compare in constant time, reject on mismatch.

Every provider does it slightly differently:

Provider

Header

Signed message

Encoding

Meta (Instagram, Facebook, Threads)

X-Hub-Signature-256: sha256=...

Raw body, keyed with app secret

Hex

LinkedIn

X-LI-Signature

"hmacsha256=" + raw body, keyed with client secret

Lowercase hex

X

X-Twitter-Webhooks-Signature-OAuth2: sha256=...

Raw body, keyed with OAuth 2.0 client secret

Base64

Outstand

X-Outstand-Signature: sha256=...

Raw body, keyed with your signing secret

Hex

Sources: Meta webhooks, LinkedIn webhook validation, X webhooks.

On LinkedIn the prefix is part of the signed string, not the header. The most common bug is verifying JSON.stringify(req.body) after a framework parsed it: re-serialized JSON is not byte-identical to what was sent, so verification fails intermittently. Read the raw body first:

ts
1async function hmacSha256(secret: string, message: string): Promise<Uint8Array> {
2	const enc = new TextEncoder();
3	const key = await crypto.subtle.importKey('raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
4	return new Uint8Array(await crypto.subtle.sign('HMAC', key, enc.encode(message)));
5}
6
7function constantTimeEqual(a: string, b: string): boolean {
8	if (a.length !== b.length) return false;
9	let mismatch = 0;
10	for (let i = 0; i < a.length; i++) mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i);
11	return mismatch === 0;
12}
13
14export async function verifyOutstandWebhook(request: Request, secret: string): Promise<{ ok: boolean; body: string }> {
15	const body = await request.text(); // raw bytes as text, before any JSON parsing
16	const header = request.headers.get('x-outstand-signature') ?? '';
17	if (!header.startsWith('sha256=')) return { ok: false, body };
18
19	const digest = await hmacSha256(secret, body);
20	const expected = Array.from(digest, (b) => b.toString(16).padStart(2, '0')).join('');
21	return { ok: constantTimeEqual(header.slice('sha256='.length), expected), body };
22}

Then respond fast (Outstand times out deliveries at 30 seconds and retries up to 5 times), queue heavy work, and deduplicate. Our webhooks docs list the dedupe keys per event.

7. Validate input at the boundary with a schema

Why: a malformed request that passes your edge becomes a confusing error three layers down, or a half-completed operation at the provider. How: parse every request with a schema (our API workers use Zod) and reject early with a specific message.

Provider constraints belong in that schema too. Threads limits each post to 500 characters, so Outstand rejects a post targeting Threads with a 400 if any segment is longer, before anything publishes anywhere. Failing up front beats publishing to four networks and failing on the fifth. Unrecognized top-level keys are reported in a warnings array, which catches typos early.

8. Never serialize secrets

Why: tokens leak through the boring paths: a debug endpoint, a log line, an error object that captured the request config. How: strip secrets at the response boundary in one place, and keep them out of durable job state.

Our connected-account rows store OAuth tokens next to harmless profile fields, and queries often select the whole row, so every API response passes accounts through one sanitizer that removes the token field. Background workflow parameters stay secret-free too, because they are persisted: the job gets an account ID and fetches the token inside the step. On your side, keep API keys in a secret manager, scope them per environment and rotate them.

9. Return one error shape everywhere

Why: if every endpoint fails differently, every caller writes its own parser. How: pick one shape. Ours is success: false, a human-readable error, and where useful a machine-readable code, with the HTTP status doing its job: 400 for validation, 401 for auth, 409 for conflicts, 500 for internal errors.

json
1{
2	"success": false,
3	"error": "This Idempotency-Key was already used with a different request body. Use a new key for a different request.",
4	"code": "idempotency_key_reuse"
5}

Do the same for errors you receive: wrap each provider's HTTP error in a typed error that keeps its code, subcode and trace ID. "Request failed with status code 400" is useless at 3 a.m.; Meta's message plus fbtrace_id is something you can act on.

10. Pin versions and track deprecations

Why: APIs change under you. How: pin explicit versions, put sunset dates in a calendar, and test against the next version before you are forced to.

Meta guarantees each Graph API version for at least two years (versioning). LinkedIn's versioned APIs require a Linkedin-Version: YYYYMM header on every call, ship monthly, and support each version for at least one year (LinkedIn versioning). A LinkedIn integration nobody touches for a year breaks on schedule. Subscribe to every changelog you depend on, and parse defensively: ignore unknown fields and tolerate missing optional ones.

11. Expect runtime-specific surprises

Why: your HTTP client and runtime can change behavior too. How: test on the real runtime, not just Node.

Our example: Axios 1.20's fetch adapter defaults to cache: 'default', which Cloudflare Workers rejects. Node-only tests would not catch it. The fix was a shared client with fetchOptions: { cache: 'no-store' }, leaving global defaults alone, plus regression tests that run inside the Workers runtime.

12. Make failures observable and testable

How: log every outbound call with provider, endpoint, status, latency and the provider's trace ID. Alert on error rate per provider, so one network breaking does not hide in the average.

Mock the ugly responses in tests: the 400 that means "expired token", the 404 on a container created a second ago, Instagram's "Media ID is not available" refusal (2207027). Keep a few contract tests against real test accounts, and add a circuit breaker so you queue work instead of hammering a failing API.

FAQ

What are the 5 stages of API integration?

Discovery (docs, limits, terms, app review), design (auth, data model, sync vs async, error mapping), build (happy path and failure paths together), test (mocks, contract tests, staged rollout) and operate (monitoring, credential rotation, version migrations). Operating is the longest and most expensive stage.

What are API best practices?

For consuming APIs: plan for token expiry, retry safely with backoff and idempotency keys, budget rate limits, verify webhooks, validate inputs and log provider trace IDs. For building APIs: consistent error shapes, explicit versioning, idempotent writes, clear rate limit headers and an OpenAPI spec.

What are the top best practices for API security?

Use HTTPS everywhere, keep keys in a secret manager and rotate them, request the narrowest OAuth scopes, verify webhook signatures with constant-time comparison, validate all input with a schema, never return tokens in responses or logs, and rate limit your own endpoints.

Should I use webhooks or polling?

Use webhooks when the provider offers them and you can verify signatures, with polling as a reconciliation fallback for missed events. Some providers have no webhooks at all (Bluesky, for example), so a multi-provider integration usually needs both.

When should I use a unified API instead of building each integration?

When you need the same capability across many providers and the integrations are not your core product. Each provider adds its own OAuth flow, rate limits, signature scheme and version schedule, and that maintenance compounds.

Or let a unified API absorb this for social networks

Every practice above is something we run for 12 social networks, so you do not have to rebuild it for each one. Outstand gives you one API key, one POST /v1/posts with idempotency support, one signed webhook format and one error shape, while token refresh, per-network retries and publishing quirks are handled behind it. If you are weighing the trade-offs, read our practical guide to social posting APIs, or go straight to the getting started guide and make your first call in a few minutes.