
Calling a third-party API in a tutorial takes five lines. Running that integration in production, where tokens expire, networks drop, providers rate-limit you, webhooks arrive twice and a duplicate payment costs real money, takes deliberate engineering. This guide covers the patterns that separate fragile integrations from dependable ones: authentication, secrets management, timeouts and retries with backoff, idempotency keys, rate limiting and webhook verification. Examples use TypeScript on Node.js and reference integrations common in East Africa, such as M-Pesa Daraja, SMS gateways and KRA eTIMS.
Key takeaways
- Wrap every provider behind your own integration module, so the rest of your codebase never calls a third-party API directly.
- Keep secrets out of code and repositories; load them from environment variables or a secrets manager, and rotate them.
- Always set timeouts. Retry only transient failures, with exponential backoff and jitter, and respect
Retry-After. - Make every state-changing operation idempotent, using provider idempotency keys where offered and your own unique constraints everywhere.
- Treat webhooks as untrusted input: verify signatures or source, respond quickly, process asynchronously and deduplicate.
- Design for provider outages: queue work, degrade gracefully and reconcile afterwards.
Reference architecture
Web / mobile client
|
Your API server ----------------------------+
| |
Integration layer (one module per provider) |
- auth + token cache |
- timeouts, retries, circuit breaker |
- rate limiter |
- request/response logging (redacted) |
| |
Outbound HTTPS --> Provider API (Daraja, SMS, eTIMS, courier...)
|
Provider webhook / callback ---> Webhook receiver (verify, store, 200 OK fast)
|
Job queue --> Worker (idempotent processing)
|
Database (unique keys, audit trail)
|
Scheduled reconciliation job (status queries, statements)
The key idea is isolation. When a provider changes its API, deprecates an endpoint or has an outage, the impact is contained in one module and one queue.
Readable, typed code is what keeps a front end maintainable as the team grows.
Step 1: Read the contract before writing code
Before implementing, extract from the provider's documentation:
- Authentication method and token lifetime.
- Environments: sandbox and production base URLs, and how to get production approval. For Daraja, the go-live process on the Safaricom developer portal requires its own steps and lead time.
- Rate limits and how they are signalled (usually HTTP 429).
- Idempotency support: does the provider accept an idempotency key or unique reference?
- Asynchronous behaviour: does the API complete synchronously, or does it return "accepted" and send the final result via callback? M-Pesa STK Push is asynchronous: the initial request is acknowledged, and the outcome arrives at your callback URL after the customer acts on their phone.
- Webhook security: signatures, IP ranges, or neither.
- Error formats and which errors are retryable.
- Data protection: what personal data you send and receive, and where it is processed. Under the Kenya Data Protection Act 2019, you remain responsible for personal data you share with processors.
Step 2: Authentication patterns
| Pattern | How it works | Typical use | Key risks |
|---|---|---|---|
| API key | Static key in a header | SMS gateways, simple SaaS APIs | Leakage; often no expiry |
| OAuth 2.0 client credentials | Exchange client ID and secret for a short-lived access token | Server-to-server: Daraja, many bank APIs | Token caching and refresh bugs |
| OAuth 2.0 authorisation code (with PKCE) | User grants your app access to their account | Google, Microsoft 365, accounting platforms | Token storage, scope creep |
| HMAC request signing | Sign each request with a shared secret | Some payment and exchange APIs | Clock skew, canonicalisation errors |
| Mutual TLS | Client presents a certificate | Banking and enterprise integrations | Certificate expiry and rotation |
For OAuth client credentials, cache the token and refresh it shortly before expiry, rather than requesting a new token on every call. Requesting tokens per call adds latency and can trigger provider rate limits.
// daraja-auth.ts
type CachedToken = { value: string; expiresAt: number };
let cached: CachedToken | null = null;
let inflight: Promise<string> | null = null;
export async function getDarajaToken(): Promise<string> {
const now = Date.now();
if (cached && cached.expiresAt - 60_000 > now) return cached.value; // refresh 60 s early
if (inflight) return inflight; // avoid a stampede of parallel token requests
inflight = (async () => {
const key = requireEnv("DARAJA_CONSUMER_KEY");
const secret = requireEnv("DARAJA_CONSUMER_SECRET");
const baseUrl = requireEnv("DARAJA_BASE_URL"); // sandbox or production
const auth = Buffer.from(`${key}:${secret}`).toString("base64");
const res = await fetch(`${baseUrl}/oauth/v1/generate?grant_type=client_credentials`, {
headers: { Authorization: `Basic ${auth}` },
signal: AbortSignal.timeout(10_000),
});
if (!res.ok) throw new Error(`Daraja auth failed: HTTP ${res.status}`);
const body = (await res.json()) as { access_token: string; expires_in: string | number };
cached = { value: body.access_token, expiresAt: Date.now() + Number(body.expires_in) * 1000 };
return cached.value;
})();
try {
return await inflight;
} finally {
inflight = null;
}
}
export function requireEnv(name: string): string {
const value = process.env[name];
if (!value) throw new Error(`Missing required environment variable ${name}`);
return value;
}
Step 3: Manage secrets properly
- Never commit secrets. Use
.envfiles only for local development and add them to.gitignore. Scan repositories with a secret scanner in CI. - Use a secrets manager in production: AWS Secrets Manager, Azure Key Vault, Google Secret Manager, HashiCorp Vault, or your platform's encrypted environment variables.
- Separate sandbox and production credentials, with production access restricted to the deployment pipeline and a small number of people.
- Rotate keys on a schedule and immediately when staff with access leave.
- Redact logs. Authorisation headers, passwords, M-Pesa security credentials and full phone numbers should never appear in logs.
Step 4: Timeouts, retries and exponential backoff
Node's built-in fetch has no short default timeout, so a hung provider can tie up your request handlers. Always set one.
Retry only when a retry can succeed:
- Retry: network errors, timeouts, HTTP 429, 502, 503, 504, and sometimes 500.
- Do not retry: 400, 401 (refresh the token once instead), 403, 404, 409, 422. These will fail again.
- Only retry non-idempotent requests (POST) if you send an idempotency key or the provider deduplicates by your reference.
Exponential backoff with jitter spreads retries out so that many clients do not hammer a recovering provider at the same moment.
// http-client.ts
const RETRYABLE_STATUS = new Set([429, 500, 502, 503, 504]);
export class HttpError extends Error {
constructor(public status: number, public body: string) {
super(`HTTP ${status}`);
}
}
type RetryOptions = {
attempts?: number; // total attempts, including the first
baseDelayMs?: number;
maxDelayMs?: number;
timeoutMs?: number;
};
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
function retryAfterMs(res: Response): number | null {
const header = res.headers.get("retry-after");
if (!header) return null;
const seconds = Number(header);
if (!Number.isNaN(seconds)) return seconds * 1000;
const date = Date.parse(header);
return Number.isNaN(date) ? null : Math.max(0, date - Date.now());
}
export async function fetchWithRetry(
url: string,
init: RequestInit,
{ attempts = 4, baseDelayMs = 300, maxDelayMs = 8_000, timeoutMs = 15_000 }: RetryOptions = {},
): Promise<Response> {
let lastError: unknown;
for (let attempt = 1; attempt <= attempts; attempt++) {
try {
const res = await fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
if (res.ok) return res;
const body = await res.text();
if (!RETRYABLE_STATUS.has(res.status) || attempt === attempts) {
throw new HttpError(res.status, body);
}
lastError = new HttpError(res.status, body);
const hinted = retryAfterMs(res);
await sleep(hinted ?? backoff(attempt, baseDelayMs, maxDelayMs));
} catch (err) {
if (err instanceof HttpError) throw err; // non-retryable or out of attempts
lastError = err; // network error or timeout
if (attempt === attempts) break;
await sleep(backoff(attempt, baseDelayMs, maxDelayMs));
}
}
throw lastError;
}
// "Full jitter": random delay between 0 and the exponential cap.
function backoff(attempt: number, base: number, max: number): number {
const cap = Math.min(max, base * 2 ** (attempt - 1));
return Math.floor(Math.random() * cap);
}
For user-facing requests, keep total retry time short (a few seconds) and fall back to a queued background job if the provider is still failing. For background jobs, longer retry schedules are fine. If a provider fails repeatedly, a circuit breaker that stops calling it for a cooling-off period protects both your system and theirs.
Step 5: Idempotency keys
On unreliable last-mile links, whether a congested LTE connection at a branch or a fibre cut on your hosting provider's upstream, you will sometimes not know whether a request reached the provider. Idempotency lets you retry safely.
- If the provider supports an
Idempotency-Keyheader, generate one per logical operation and reuse it for every retry of that operation. - If it supports a unique merchant reference (many payment APIs do), use your own order or payment ID.
- Store the key and outcome in your database before and after the call, so a crash mid-request can be resumed.
// payments.ts
import { randomUUID } from "node:crypto";
import { fetchWithRetry } from "./http-client";
import { requireEnv } from "./daraja-auth";
import { db } from "./db";
export async function createPayout(orderId: string, amountKes: number, phone: string) {
// Reuse an existing key for this order if a previous attempt was interrupted.
const existing = await db.payoutAttempts.findByOrderId(orderId);
const idempotencyKey = existing?.idempotencyKey ?? randomUUID();
if (!existing) {
await db.payoutAttempts.insert({ orderId, idempotencyKey, status: "pending" }); // unique(orderId)
}
const res = await fetchWithRetry(`${requireEnv("PAYOUT_API_URL")}/payouts`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${requireEnv("PAYOUT_API_KEY")}`,
"Idempotency-Key": idempotencyKey,
},
body: JSON.stringify({ reference: orderId, amount: amountKes.toFixed(2), currency: "KES", phone }),
});
const result = await res.json();
await db.payoutAttempts.update(orderId, { status: "submitted", providerRef: result.id });
return result;
}
The generic payout provider above is illustrative; adapt header names and payloads to your provider's documentation. Where a provider has no idempotency support, query its status endpoint before retrying a payment request. Daraja, for example, offers a transaction status query.
Most modern apps are a front end talking to many APIs at once.
Step 6: Respect rate limits
Providers cap requests per second or minute. Exceeding limits causes 429 errors and, for some providers, temporary blocking.
- Read the documented limits and build a client-side limiter below them.
- Honour
Retry-After(handled infetchWithRetryabove). - For bulk operations such as sending thousands of SMS reminders or submitting many invoices, use a queue with controlled concurrency rather than
Promise.allover the whole list.
A job queue such as BullMQ (Redis-backed) provides persistence, rate limiting and retries across multiple servers.
Step 7: Receive webhooks securely
Webhooks (callbacks) are HTTP requests from the provider to your server announcing events: payment completed, SMS delivered, invoice validated. Because anyone on the internet can send a request to your URL, verify every one.
Signature verification
Many providers sign the raw request body with HMAC-SHA256 using a shared secret and send the signature in a header. Verify against the raw bytes, before JSON parsing changes whitespace or key order, and compare in constant time.
// webhooks.ts
import express from "express";
import { createHmac, timingSafeEqual } from "node:crypto";
import { requireEnv } from "./daraja-auth";
import { queue } from "./queue";
import { db } from "./db";
const app = express();
const WEBHOOK_SECRET = requireEnv("PROVIDER_WEBHOOK_SECRET");
function isValidSignature(rawBody: Buffer, signatureHex: string | undefined): boolean {
if (!signatureHex) return false;
const expected = createHmac("sha256", WEBHOOK_SECRET).update(rawBody).digest();
const received = Buffer.from(signatureHex, "hex");
return received.length === expected.length && timingSafeEqual(received, expected);
}
app.post("/webhooks/provider", express.raw({ type: "application/json", limit: "256kb" }), async (req, res) => {
if (!isValidSignature(req.body, req.header("x-signature"))) {
res.status(401).end();
return;
}
const event = JSON.parse(req.body.toString("utf8")) as { id: string; type: string; created: number };
// Reject stale events to limit replay attacks (allow 5 minutes of clock skew).
if (Math.abs(Date.now() / 1000 - event.created) > 300) {
res.status(400).end();
return;
}
// Deduplicate: providers retry deliveries, so the same event can arrive more than once.
const inserted = await db.webhookEvents.insertIfAbsent(event.id, event); // unique(event_id)
if (inserted) await queue.add("process-webhook", { eventId: event.id });
res.status(200).end(); // acknowledge quickly; do the real work in a worker
});
app.listen(3000);
Header names, signature encodings and timestamp fields vary between providers; follow each provider's documentation exactly.
When the provider does not sign callbacks
Some APIs, including M-Pesa Daraja callbacks at the time of writing, do not provide an HMAC signature. Compensate with layered controls:
- Use HTTPS with a valid certificate on your callback URL.
- Include an unguessable token in the callback path (for example
/callbacks/mpesa/<random-token>) and rotate it periodically. - Restrict source IPs at your firewall or load balancer if the provider publishes callback IP ranges; check the current Daraja documentation.
- Cross-check critical events: before releasing goods for a high-value payment, confirm via a transaction status query or reconcile against statements.
- Deduplicate on the M-Pesa receipt number with a unique database constraint.
Respond fast, process later
Providers time out webhook deliveries quickly and retry on failure. Do the minimum in the request handler: verify, store and enqueue. Then return 200. Heavy processing, such as updating orders, issuing eTIMS invoices or sending SMS confirmations, belongs in a worker.
Step 8: Observe, reconcile and plan for outages
- Structured logging with a correlation ID per operation, linking your request, the provider call and the callback.
- Metrics per provider: latency, error rate, retry count, rate-limit hits.
- Alerts for silence: if no payment callbacks arrive during trading hours, something is wrong even if no errors are logged.
- Reconciliation jobs that compare your records with provider reports daily. Missed callbacks happen; reconciliation catches them.
- Graceful degradation: if the SMS provider is down, queue messages; if eTIMS submission fails, queue invoices for retry and surface the backlog to finance.
Common mistakes
- Calling providers directly from controllers throughout the codebase, making changes and testing painful.
- No timeouts, so one slow provider exhausts your server's connections.
- Retrying POSTs without idempotency, causing duplicate payments or messages.
- Retrying non-retryable errors such as 400 and 422 in a loop.
- Parsing JSON before verifying signatures, which breaks HMAC checks.
- Doing heavy work inside webhook handlers, leading to timeouts and duplicate deliveries.
- Logging secrets or full personal data, creating security and data protection exposure.
FAQ
How do I store API keys securely in a web application?
Keep them server-side only, loaded from environment variables or a secrets manager, never in front-end code or source control. Rotate them regularly and restrict who can read production secrets.
What is exponential backoff?
A retry strategy where the wait between attempts grows exponentially (for example 0.3 s, 0.6 s, 1.2 s), usually with random jitter, so retries do not overwhelm a recovering service.
What is an idempotency key?
A unique value the client sends with a state-changing request. If the same key is sent again, the server returns the original result instead of repeating the operation, preventing duplicates when retrying.
How do I verify that a webhook really came from the provider?
Verify the provider's signature against the raw request body using the shared secret and a constant-time comparison. If the provider does not sign webhooks, combine HTTPS, secret callback URLs, IP allowlisting and status queries for critical events.
Should I use REST or GraphQL for integrations?
Most third-party providers expose REST APIs, so your integration layer will typically be REST. See REST API vs GraphQL for when GraphQL makes sense for your own APIs, and What Is a REST API? for fundamentals.
How TechBytes can help
We build and maintain production integrations with M-Pesa Daraja, Airtel Money, banks, SMS gateways, KRA eTIMS and SaaS platforms, with the retries, idempotency, webhook security and reconciliation described here. We can also audit an existing integration for reliability and security gaps. Explore our software development services or ask about an API security review through our cybersecurity services.


