Setting up real-time webhooks for letter printing, dispatch, and delivery.

2/20/2026
Setting up real-time webhooks for letter printing, dispatch, and delivery.
In modern software architecture, the days of polling APIs in tight database loops are officially over.Whether tracking payments in Stripe, message delivery in Twilio, or repository pushes in GitHub, modern cloud platforms operate on reactive, event-driven webhooks. When an event occurs, the provider pushes an HTTP POST payload to your application in real time, triggering instant business logic.Yet, for decades, physical postal logistics remained a complete black box. Businesses dumped thousands of letters into the postal system, and then had to wait in total darkness. Did the print shop actually print the file? Did Royal Mail collect the mailbags? Did the postman deliver the envelope, or was the address undeliverable?To answer these questions, operations teams had to pick up the telephone, call commercial printing houses, quote vague job reference numbers, and wait hours for a manual status update.The operational paralysis this causes in digital software is severe. In customer dunning workflows, finance teams do not know when a formal arrears notice was served. In debt collection, compliance officers cannot prove statutory grace periods. In enterprise sales, Account Executives have no idea when a high-value proposal arrived on an executive's desk.Philosophically, physical mail in the UK should provide the exact same real-time event telemetry as digital communication. When a letter is printed, handed to Royal Mail, sorted at a regional distribution center, and delivered through a recipient's letterbox, your software should be notified within milliseconds through a secure, signed webhook.At LetterAPI, we engineered our infrastructure to turn the physical Royal Mail postal network into a real-time event stream. In this comprehensive guide, we show you how to configure, secure, and scale real-time webhooks for the complete letter lifecycle: from `letter.created` and `letter.printed` to `letter.dispatched` and `letter.delivered`.

The letter lifecycle state machine: Understanding postal events

To build reactive software around physical mail, developers must understand the discrete states a letter traverses during fulfillment.LetterAPI models the physical mailing journey through six distinct webhook events:1. `letter.created`: The initial HTTP POST request was received, authenticated, and validated against the Royal Mail Postcode Address File (PAF). The document is queued in our distributed intake pipeline.2. `letter.printed`: The document was rendered at 1200 DPI on commercial digital production presses, folded into thirds by automated vacuum folding blades, and inserted into a pristine DL window envelope.3. `letter.dispatched`: The envelope was collected by Royal Mail distribution vehicles at our regional print facility and injected into the national sorting network.4. `letter.in_transit`: The envelope was scanned by optical sorting machinery at an intermediate Royal Mail regional mail center, verifying active transit.5. `letter.delivered`: The envelope arrived at the recipient's local delivery office and was scanned onto the postman's final delivery route for doorstep drop-off.6. `letter.failed`: A fatal error occurred during intake or manufacturing (e.g. PAF rejection, corrupt PDF binary, or unresolvable address geometry), accompanied by descriptive error codes in the payload.

The 3-step plan: Implementing real-time postal webhooks

Setting up reactive postal webhooks in your application follows a straightforward 3-step plan:Step 1: Expose an idempotent, public HTTPS webhook endpoint. In your backend framework (Express, FastAPI, Next.js, Django), create a route that accepts incoming HTTP POST requests and returns an immediate HTTP 200 OK status.Step 2: Verify the cryptographic HMAC SHA-256 signature. Protect your endpoint from forgery by verifying the `X-LetterAPI-Signature` header against your private webhook signing secret using constant-time comparison.Step 3: Register your webhook endpoint in the LetterAPI dashboard. Configure your public webhook URL in the LetterAPI developer settings, select the events you wish to receive, and execute a test ping to verify end-to-end connectivity.

Cryptographic signature verification: Protecting against replay attacks

Because webhook endpoints are exposed to the public internet, verifying the authenticity and integrity of incoming payloads is mission-critical.An attacker who discovers your webhook URL could attempt to send spoofed `letter.delivered` events, tricking your billing system into believing that an arrears notice was served when it was never printed.LetterAPI secures all webhook transmissions using HMAC SHA-256 signatures combined with a Unix timestamp header (`X-LetterAPI-Timestamp`):1. Construct the Signed Payload: Concatenate the timestamp string, a period character (`.`), and the raw request body string (e.g. `1726584000.{"event":"letter.delivered"...}`).2. Compute the HMAC Digest: Compute the HMAC SHA-256 hash of this concatenated string using your private webhook secret (`whsec_...`).3. Verify Header Signature: Compare the computed hexadecimal digest against the `X-LetterAPI-Signature` header using constant-time string comparison (`crypto.timingSafeEqual`).4. Enforce Timestamp Tolerance: Check that the timestamp is within 300 seconds (5 minutes) of current server time to prevent malicious actors from intercepting and replaying historical webhook requests.

Technical blueprint: Production Node.js/Express webhook receiver

Here is a complete, enterprise-grade Express webhook receiver featuring raw body capture, cryptographic signature verification, timestamp tolerance checks, and idempotent event processing:
src/webhooks/letterapi-receiver.ts — typescript
import express, { Request, Response } from 'express';
import crypto from 'crypto';
​
const app = express();
const WEBHOOK_SECRET = process.env.LETTERAPI_WEBHOOK_SECRET || 'whsec_sample_secret_key_84920';
const TOLERANCE_SECONDS = 300; // 5-minute replay tolerance
​
interface LetterEventPayload {
event: 'letter.created' | 'letter.printed' | 'letter.dispatched' | 'letter.in_transit' | 'letter.delivered' | 'letter.failed';
letter_id: string;
timestamp: string;
data: {
recipient_name: string;
postcode: string;
postage_class: 'first_class' | 'second_class';
carrier: 'Royal Mail';
mailmark_barcode?: string;
delivery_office?: string;
};
metadata?: Record<string, any>;
error?: {
code: string;
message: string;
};
}
​
// Express raw body middleware required for HMAC cryptographic verification
app.post('/api/v1/webhooks/letterapi', express.raw({ type: 'application/json' }), async (req: Request, res: Response) => {
const sigHeader = req.headers['x-letterapi-signature'] as string;
const timestampHeader = req.headers['x-letterapi-timestamp'] as string;
​
if (!sigHeader || !timestampHeader) {
return res.status(401).json({ error: 'Missing webhook security headers' });
}
​
// 1. Enforce Timestamp Tolerance to Prevent Replay Attacks
const eventTimestamp = parseInt(timestampHeader, 10);
const currentTimestamp = Math.floor(Date.now() / 1000);
if (Math.abs(currentTimestamp - eventTimestamp) > TOLERANCE_SECONDS) {
console.error('[Security Warning] Webhook timestamp outside acceptable tolerance window!');
return res.status(401).json({ error: 'Webhook timestamp expired' });
}
​
// 2. Compute and Verify HMAC SHA-256 Signature
const rawBody = req.body as Buffer;
const signedPayload = `${timestampHeader}.${rawBody.toString('utf8')}`;
const expectedSig = crypto
.createHmac('sha256', WEBHOOK_SECRET)
.update(signedPayload)
.digest('hex');
​
const sigBuffer = Buffer.from(sigHeader, 'hex');
const expectedBuffer = Buffer.from(expectedSig, 'hex');
​
if (sigBuffer.length !== expectedBuffer.length || !crypto.timingSafeEqual(sigBuffer, expectedBuffer)) {
console.error('[Security Alert] Invalid LetterAPI webhook HMAC signature!');
return res.status(401).json({ error: 'Invalid signature' });
}
​
// 3. Deserialize Payload
const payload: LetterEventPayload = JSON.parse(rawBody.toString('utf8'));
console.log(`[LetterAPI Webhook] Verified Event: ${payload.event} for Letter: ${payload.letter_id}`);
​
// 4. Handle Event Asynchronously (e.g. emit to internal event bus or BullMQ queue)
try {
switch (payload.event) {
case 'letter.delivered':
console.log(`✓ Letter ${payload.letter_id} delivered by Royal Mail to ${payload.data.delivery_office}`);
// TODO: Update database invoice status to 'NOTICE_SERVED', notify CRM
break;
case 'letter.dispatched':
console.log(`-> Letter ${payload.letter_id} in Royal Mail sorting network`);
break;
case 'letter.failed':
console.error(`✗ Letter ${payload.letter_id} failed: ${payload.error?.message}`);
break;
}
​
// 5. Always return 200 OK promptly to acknowledge receipt
return res.status(200).json({ received: true });
} catch (err: any) {
console.error('[Webhook Processing Error]', err);
return res.status(500).json({ error: 'Internal processing error' });
}
});
​
app.listen(4000, () => console.log('LetterAPI webhook listener active on port 4000'));

Building reactive business workflows: Real-world operational automations

Once real-time postal webhooks are flowing into your application, you can build sophisticated cross-channel operational automations that were previously impossible with legacy mail:1. Synchronized SDR Sales Follow-Up: When `letter.delivered` fires for an enterprise executive briefing, your CRM automatically alerts the assigned Account Executive via Slack: 'Executive letter delivered to CISO at Acme Corp 20 minutes ago. Initiate warm follow-up phone call now.'2. Multi-Channel Arrears Escalation: When an overdue billing letter is marked `letter.delivered`, your finance system starts a statutory 14-day grace period clock. If payment is not received by Day 12, an automated SMS warning is sent: 'Your formal postal notice was delivered on 12 March. 48 hours remaining before account suspension.'3. Legal Proof of Service Automation: When serving Section 21 tenancy notices or debt claims, the `letter.delivered` webhook captures the Royal Mail Mailmark delivery office scan timestamp and stores it as an immutable audit record under Section 7 of the Interpretation Act 1978, automatically generating court-admissible certificates of posting without manual legal paperwork.

Webhook delivery retry policies and high-availability architecture

What happens if your application server is temporarily restarting during a deployment when LetterAPI attempts to deliver a webhook?LetterAPI incorporates an enterprise-grade automated retry policy designed for 99.99% event delivery reliability.If your webhook endpoint returns a non-2xx status code or times out after 15 seconds, our webhook delivery engine automatically retries using exponential backoff across 72 hours:Retry 1: 5 minutes laterRetry 2: 15 minutes laterRetry 3: 1 hour laterRetry 4: 6 hours laterRetry 5 to 10: Every 12 hours up to 72 hours.Furthermore, our developer dashboard provides a full webhook event log viewer where engineers can inspect request/response headers, view execution latencies, and trigger manual event replays with a single click.

The failure stakes: What happens when businesses operate with postal blindness

Consider the operational hazards of running physical mail without real-time webhooks.Your finance team dispatches debt collection letters, but has no proof of when or if they arrived. When a customer claims they never received the notice, your company has no evidence, forcing debt disputes into protracted, costly legal mediation.Sales teams send expensive direct mail packages, but follow up days too early or weeks too late, missing the critical window when the document was actually on the decision-maker's desk.Customer service representatives are forced to tell inquiring clients: 'We posted it a week ago, hopefully it arrives soon.' Your digital business looks amateurish, uncoordinated, and stuck in the pre-internet era.

The success transformation: Complete real-time physical visibility

Now envision your software powered by LetterAPI's real-time postal webhooks.Every physical letter dispatched by your application is tracked with the same second-by-second precision as a digital payment or transactional email.As Royal Mail optical sorting cameras scan envelopes across the country, your databases update automatically, your CRMs trigger synchronized sales workflows, and your compliance ledgers record indisputable delivery proof.Your business operates with total operational visibility, bridging cloud applications with physical letterboxes through clean, reactive event-driven code.Turn the physical postal network into a real-time event stream. Configure LetterAPI webhooks today.

The shared responsibility model for programmatic print and postal infrastructure

Security in cloud-based physical printing operates on a shared responsibility model, analogous to Amazon Web Services (AWS) or Microsoft Azure.Understanding the boundary between your application's security obligations and LetterAPI's infrastructure controls is essential for maintaining enterprise governance:Customer Responsibility: You are responsible for ensuring that all data transmitted to LetterAPI is legally acquired under UK GDPR lawful bases, that API keys are stored securely in secrets managers rather than source code repositories, that your webhook endpoints validate cryptographic signatures, and that recipient addresses are sanitized prior to dispatch.LetterAPI Infrastructure Responsibility: LetterAPI is responsible for securing the API endpoints, encrypting all data in transit using TLS 1.3, maintaining isolated microservice containers, executing zero-retention RAM-based rendering pipelines, ensuring physical access controls at ISO 27001-certified print facilities, and destroying temporary spool files immediately upon print engine intake.By clearly defining this demarcation, compliance auditors can rapidly certify your hybrid mail architecture during annual SOC 2 and ISO 27001 audits without encountering regulatory ambiguity.

Role-Based Access Control (RBAC) and team governance in enterprise accounts

In enterprise software environments, programmatic print pipelines must be managed with granular permissions to prevent unauthorized spending or data misuse.LetterAPI provides comprehensive Role-Based Access Control (RBAC) across organization accounts:Administrator: Full permissions to manage billing instruments, invite and revoke team members, generate and revoke live API keys, configure webhook endpoints, and inspect postal telemetry across all sub-accounts.Developer: Permissions to create and rotate sandbox API keys, inspect webhook delivery logs, execute test print simulations, and manage HTML/CSS template schemas. Developers cannot view sensitive recipient address data or alter corporate billing details.Billing Manager: Read-only access to monthly postal expenditure ledgers, itemized VAT invoices, and multi-tenant department cost centers. Cannot access API credentials or create letter dispatch jobs.Auditor: Read-only access to cryptographic dispatch certificates, system status logs, SOC 2 compliance documentation, and security audit reports.By enforcing least-privilege RBAC policies, your engineering team ensures that access to physical mail capabilities remains strictly governed and auditable.

Physical security controls: Clean-room printing, CCTV surveillance, and automated destruction

Software engineers often focus exclusively on cyber security, forgetting that physical print facilities present distinct physical security threat vectors.If an unauthorized worker could read a printed bank statement or medical lab result as it emerges from a print queue, your organization would suffer a catastrophic GDPR breach.LetterAPI's UK print facilities operate under rigorous physical security protocols certified to ISO 27001 and CPNI (Centre for the Protection of National Infrastructure) standards:Clean-Room Enclosed Production: High-speed continuous-feed inkjet presses and automated DL folding-inserting machines operate inside restricted clean-room production cells. Entry requires biometric fingerprint authentication and dual-factor electronic keycards.Continuous High-Definition CCTV Surveillance: Every square meter of the production floor, envelope feeder trays, sorting bins, and Royal Mail collection docks is monitored 24/7/365 by encrypted HD CCTV cameras, with footage retained securely for 90 days for forensic audit purposes.No Personal Electronic Devices: Machine operators and print technicians are strictly prohibited from bringing mobile phones, cameras, USB storage drives, or writing implements into the production clean-room.Automated Shredding and Destruction: Any paper jams or mechanical misfeeds are automatically diverted into locked, cross-cut shredding bins that reduce paper to DIN 66399 Level P-5 micro-particles on-site, ensuring zero salvageable personal data.

Penetration testing, vulnerability disclosure, and third-party security audits

Maintaining enterprise trust requires continuous verification by independent, accredited cyber security researchers.LetterAPI undergoes comprehensive third-party security testing across all application layers:Annual CREST-Accredited Penetration Testing: Every 12 months, an independent, CREST-certified security consultancy conducts thorough grey-box and black-box penetration tests across our API gateways, database clusters, web application dashboards, and worker queues.Continuous Automated Dynamic and Static Code Analysis: Every code commit across our platform is scanned by automated SAST and DAST pipelines for OWASP Top 10 vulnerabilities, dependency CVEs, and secret leaks prior to merging into production.Responsible Vulnerability Disclosure Program: We operate an active vulnerability disclosure policy, providing ethical security researchers with a secure, confidential channel to report potential security anomalies with rapid triage and remediation SLA commitments.

The compliance audit checklist: Preparing your hybrid mail stack for regulatory review

When your Data Protection Officer (DPO) or external ISO/SOC auditor reviews your LetterAPI integration, use this comprehensive checklist to ensure swift approval:1. Data Processing Addendum (DPA): Confirm that your organization has executed LetterAPI's UK GDPR-compliant DPA, incorporating standard contractual clauses and sub-processor commitments.2. Encryption in Transit Verification: Verify that your production applications enforce TLS 1.3 for all HTTP connections to `https://api.letterapi.uk/v1` and reject legacy SSL/TLS ciphers.3. Secret Key Protection: Verify that production API keys (`live_sec_...`) are injected via environment variables managed by an encrypted secret store (e.g. AWS Secrets Manager), with zero secrets committed to Git.4. Webhook Cryptographic Verification: Verify that your webhook consumer code enforces constant-time HMAC SHA-256 signature verification before processing event payloads.5. Address Sanitization and Minimization: Ensure that your document payloads contain only the minimal personal data necessary for delivery and legal notice, adhering to the GDPR data minimization principle.

Zero-trust architecture in print pipeline: Mutual TLS (mTLS) and token rotation

For regulated financial and defense institutions, standard server-side TLS is often insufficient to meet internal InfoSec standards.LetterAPI supports Mutual TLS (mTLS) authentication for enterprise customers, requiring both the client application and the API gateway to authenticate each other using X.509 cryptographic certificates.This cryptographically eliminates man-in-the-middle (MITM) attacks and ensures that only authorized workloads running inside your private VPC can communicate with the postal gateway.Additionally, LetterAPI supports short-lived ephemeral JSON Web Tokens (JWTs) generated via OAuth 2.0 client credentials grants, allowing automatic hourly token rotation without storing static secret keys in runtime container memory.

Data residency guarantees: 100% Sovereign UK data lifecycle and storage limits

Following Brexit, UK public sector bodies, NHS trusts, and legal practices face strict requirements regarding UK data residency and cross-border data transfers.LetterAPI guarantees that 100% of your data remains strictly within the borders of the United Kingdom throughout its entire lifecycle:Sovereign UK Data Centres: Our API gateways, database clusters, and rendering microservices are hosted exclusively in AWS `eu-west-2` (London) data centres.Zero Cross-Border Routing: No customer document data or recipient address records are ever routed through EU, US, or offshore nodes for caching, analytics, or logging.Domestic Print Operations: All physical printing, enveloping, and sorting occurs in certified production centres located inside the United Kingdom, before direct handover to Royal Mail.For Data Protection Officers, this sovereign architecture satisfies all requirements of the UK Data Protection Act 2018 and eliminates the need for complex International Data Transfer Agreements (IDTAs).Continuous Compliance Reporting: LetterAPI provides downloadable monthly compliance summaries detailing zero data retention certifications, automated shredding logs, and TLS cipher audit logs. These automated reports allow security officers to maintain audit readiness year-round with zero administrative manual overhead.Cryptographic Chain of Custody: Every postal batch receives a SHA-256 digital custody manifest recorded in an immutable ledger. This provides indisputable forensic proof for corporate auditors, verifying exactly when documents were received, rendered, printed, and handed to Royal Mail.