# Ferry API Reliability Patterns

Source: https://ferry.vn/en/ferry-api-reliability-reconciliation-patterns/
Locale: en
Category: Ferry API & Tech
Published: 2026-11-25
Updated: 2026-11-25
Author: Le Quoc Khoi (CEO, Ferry VN JSC) — https://ferry.vn/en/author/le-quoc-khoi/
Summary: Ferry API reliability architecture for OTAs: opt-in HMAC-SHA256 webhooks, 3 retries, 600s locks, 5/60s throttles, non-idempotent recovery, and reconciliation.

---

> **Key Takeaways:** Achieving production **ferry API reliability** on **Ferry VN Platform** requires designing around non-idempotent booking writes, asynchronous carrier issuance, multi-layer rate limits, opt-in Standard Webhooks HMAC-SHA256 verification, and scheduled API reconciliation.
>
> - **Non-Idempotent Write Protection:** `POST /api/v1/bookings` has no idempotency keys, so every write timeout must query `bookings.list` before re-creating an order while `@ferryvn/sdk` retries only `GET` and `HEAD` requests.
> - **Per-Booking Isolation and Locks:** Ticket confirmation (`confirmToIssue`) enforces a 600-second execution lock (`120100`), a 5-per-60-seconds HTTP 429 cap keyed by `client IP + bookingId`, and a cluster-wide HTTP 422 soft cooldown (`120140`), isolating one failing booking from other checkouts.
> - **Opt-In Signed Webhooks with Hard 2s Timeout:** Organizations enable `whsec_...` HMAC-SHA256 signing in the Dashboard with zero-downtime grace rotation, receive at-least-once deliveries with 3 retries (~30s, 5m, 30m), and must acknowledge HTTP 2xx within 2 seconds.
> - **Webhooks Are Signals, Polling Is Truth:** Deduplicate by `webhook-id`, re-query `GET /api/v1/bookings/{id}` for authoritative state, handle partial round-trip leg refunds explicitly, and guard against silent `HTTP 200 []` responses.

Engineering **ferry API reliability** for Southeast Asian sea transport demands a different fault-tolerance model than an idempotent payment gateway or airline switch. Maritime reservation engines in Vietnam vary widely in response latency, do not grant upstream temporary seat holds, and experience weather bans that trigger burst cancellations across hundreds of passengers at once.

Dropping naive retry middleware or synchronous webhook handlers onto a multi-operator ferry API creates duplicate bookings, dropped confirmation events after four failed attempts, and out-of-sync ledgers. This reference maps Ferry VN's exact throttling layers, write-recovery rules, opt-in [Standard Webhooks](https://www.standardwebhooks.com) HMAC-SHA256 code, and reconciliation loops for high-volume Online Travel Agencies (OTAs).

## Failure Modes Unique to Maritime Ticketing APIs

Four structural properties govern Ferry VN's Partner API: seats are guaranteed on the carrier only after `confirmToIssue` reaches status `10`, booking creation has no idempotency key, live issuance can take seconds or 5 to 8 minutes depending on operator infrastructure, and outbound webhooks follow unordered at-least-once delivery dropping after four attempts.

![Two-stage Ferry VN API booking boundaries showing Status 2 Unpaid vs Status 10 Issued transitions](https://cdn.ferry.vn/media/31/diagram-ferry-api-two-stage-booking-lifecycle.webp)

| Production Failure Scenario | Ferry VN API Behavior | Safe Partner Engineering Pattern | Anti-Pattern That Breaks Production |
|---|---|---|---|
| **Timeout on `POST /bookings`** | No idempotency key, so order may exist in status `2` | Query `bookings.list` by contact, voyage, and date before retrying | Resending `POST /bookings` via HTTP retry middleware |
| **Seat claimed during checkout** | No upstream hard seat hold, returns HTTP 422 `150201` | Re-fetch boat layout before creation and prompt new seat on `150201` | Caching seat layouts 15+ min and retrying same seat code |
| **Slow live carrier issuance** | `confirmToIssue` holds 600s lock, concurrent calls get `120100` | Switch to polling `GET /bookings/{id}` until terminal state | Aborting after 15s and creating a duplicate booking |
| **Slow webhook handler (>2s)** | Hard 2,000 ms timeout triggers retry (30s, 5m, 30m) | Verify raw HMAC bytes, enqueue job, return HTTP 2xx in <200 ms | Running DB writes or PDF fetches before returning HTTP 200 |
| **Partial round-trip failure** | One leg issues, failed leg refunds, parent stays out of status `10` | Inspect child `orders` inside booking and escalate code to Ferry ops | Re-invoking `confirmToIssue` across the booking |
| **Transient DB/auth blip** | List queries can swallow faults and return HTTP 200 `[]` | Alert on unexpected zero-count drops and retain local cache | Treating `[]` as proof to purge local schedules |
| **Shared NAT egress burst** | Global 5,000 req/10s quota counts per `client IP` per route | Honor `Retry-After` with jitter and isolate egress IPs | Spawning extra worker threads during a 429 burst |

For the full corridor matrix and stack overview, see the [Unified Vietnam Ferry API specification](/en/vietnam-ferry-api-unified-multi-operator-integration/) and [Ferry VN SDK quickstart](/en/ferry-vn-sdk-rest-api-developer-quickstart/).

## Safe Write Retries, Locks, and Rate-Limit Architecture

Resilient clients separate read retries strictly from money-moving writes. In [`@ferryvn/sdk` on npm](https://www.npmjs.com/package/@ferryvn/sdk), `GET` and `HEAD` calls retry up to twice on network errors or HTTP `408`, `429`, `502`, `503`, and `504`, while mutating calls execute once with zero automatic retries.

### Non-Idempotent Creation Recovery Protocol

Because `POST /api/v1/bookings`, `POST /api/v1/cancel-ticket-requests`, and price-addition creation endpoints have no idempotency keys, persist an internal order intent in your own database before calling Ferry VN and run a read-first lookup on any timeout:

```ts
import { FerryClient, FerryConnectionError } from '@ferryvn/sdk'

interface OrderIntent {
  internalRef: string
  contactEmail: string
  voyageId: string
  passengerSocialIds: string[]
}

export async function createOrRecoverBooking(
  ferry: FerryClient,
  intent: OrderIntent,
  createFn: () => Promise<{ booking: { id: string; status: number } }>
) {
  try {
    return await createFn()
  } catch (err) {
    if (!(err instanceof FerryConnectionError)) {
      throw err
    }

    // Read-first lookup before risking a duplicate reservation
    for await (const existing of ferry.bookings.iterate({
      namePhoneEmail: intent.contactEmail,
      limit: 50
    })) {
      const sameVoyage = existing.orders?.some((leg) => leg.voyageId === intent.voyageId)
      if (sameVoyage && existing.status === 2) {
        return { booking: existing, recovered: true }
      }
    }

    throw new Error(`Booking creation uncertain for ${intent.internalRef}; manual check required`)
  }
}
```

Apply the same read-first check to `cancelTicketRequests.create`. Although crediting refunds back up to ancestor organizations is idempotent on Ferry VN, duplicate POST requests after a client timeout create duplicate cancellation records.

### Multi-Layer Rate Limits and Confirmation Locks

Ferry VN enforces five throttling and concurrency layers across its gateway and Redis cluster, documented on the [Ferry VN API and SDK platform hub](/en/platform/api-sdk/) and provisioned through our [API partner onboarding portal](/en/api-partners/).

| Protection Layer | Exact Threshold | Counting Key | HTTP Status & Code | Partner Recovery Rule |
|---|---|---|---|---|
| **Global Route Throttler** | 5,000 req / 10s (500/s per replica) | `client IP` per route and replica | HTTP `429` (`X-RateLimit-*`, `Retry-After`) | Honor `Retry-After` or jittered backoff (1s–30s, max 5 tries) |
| **Optional Per-Key Cap** | 10 to 10,000 req / minute | `API key` (fixed 1-min window) | HTTP `429` (`ApiKeyRateLimited`) | Track Dashboard throttle metrics and tune concurrency |
| **Confirmation HTTP Cap** | 5 requests / 60 seconds | `client IP + bookingId` (per replica) | HTTP `429` (`Retry-After`) | Pause `confirmToIssue` for that order while other checkouts stay free |
| **Confirmation Soft Cooldown** | 5 attempts / 60 seconds | `bookingId` in Redis (cluster-wide) | HTTP `422` code `120140` | Wait 60 seconds and poll `GET /api/v1/bookings/{id}` |
| **Execution Concurrency Locks** | 600s issuance lock / 180s payment lock | `bookingId` | HTTP `422` code `120100` | Wait 60+ seconds and poll booking status until lock clears |

Note that Ferry VN pages its own on-call team on `5xx` errors rather than `429` bursts, so client alerting on `429` rates is your responsibility. Services sharing a NAT egress IP share the per-route `client IP` bucket.

## Opt-In Standard Webhooks HMAC-SHA256 Receiver Architecture

Outbound webhooks deliver HTTP `POST` events across 50+ types (`booking.issuedTicket`, `booking.issuedTicketError`, `disruption.*`, `cancel_ticket_request.refunded`, `invoice.published`). Signing is **opt-in per organization** inside Dashboard **Notification settings** (`Webhook security` card).

![8-status booking finite state machine, 600s confirmToIssue lock, HMAC-SHA256 3-retry delivery, and polling reconciliation loop](https://cdn.ferry.vn/media/31/diagram-en-webhook-hmac-retry-reconciliation-fsm.webp)

When enabled, Ferry VN signs deliveries with Standard Webhooks HMAC-SHA256 (`v1,<base64>`) over `${webhook-id}.${webhook-timestamp}.${rawBody}`, sending `webhook-id` (`msg_<ulid>`), `webhook-timestamp`, `webhook-signature`, `x-event-type`, and `user-agent: Ferry-Webhooks/1`. Organizations without a secret receive `webhook-id` and `webhook-timestamp` unsigned.

- **Zero-downtime rotation:** Rotating a `whsec_...` secret supports grace windows (`none`, `1h`, `24h`, `7d`) sending two space-separated signatures. Because server caches retain decrypted secrets up to 60 seconds per process, accept both secrets briefly even on `none`.
- **Retries and 2-second deadline:** Timeouts (>2,000 ms), network errors, and HTTP `408`/`429`/`5xx` enqueue **3 automatic retries** at ~30s, 5m, and 30m (4 total attempts preserving `webhook-id`). HTTP `3xx` and other `4xx` responses never retry.
- **URL perimeter and egress IPs:** Endpoints require public `https://` (`443` or `8443`) with zero redirects or private/metadata IP resolution. Allowlist static outbound addresses via `GET /api/v1/webhooks/egress-ips` (cached 1h, 14-day migration notice).

### Raw-Body Verification and Sub-2-Second Queue Ingestion

Verify exact raw UTF-8 body bytes rather than re-serialized JSON (`JSON.stringify` breaks HMAC digests), enqueue asynchronously, and return HTTP `200` or `204` immediately:

```ts
import { Webhook } from 'standardwebhooks'
import { parseWebhook } from '@ferryvn/sdk'

const currentVerifier = new Webhook(process.env.FERRY_WEBHOOK_SECRET!)
const previousVerifier = process.env.FERRY_WEBHOOK_SECRET_PREV
  ? new Webhook(process.env.FERRY_WEBHOOK_SECRET_PREV)
  : null

function verifyWithGrace(rawBody: string, headers: Record<string, string>) {
  try {
    return currentVerifier.verify(rawBody, headers)
  } catch (primaryErr) {
    if (!previousVerifier) throw primaryErr
    return previousVerifier.verify(rawBody, headers)
  }
}

export async function handleWebhookRoute(
  rawBody: string,
  headers: Record<string, string>,
  enqueue: (job: { webhookId: string; eventType: string; payload: unknown }) => Promise<void>
) {
  // 1. Authenticate exact raw UTF-8 bytes and enforce +-5 minute replay tolerance
  verifyWithGrace(rawBody, headers)

  // 2. Parse typed event payload via @ferryvn/sdk after verification succeeds
  const parsed = parseWebhook({ headers, body: rawBody })

  // 3. Enqueue fast and acknowledge within 2,000 ms (never run API calls inline)
  await enqueue({
    webhookId: headers['webhook-id'],
    eventType: headers['x-event-type'],
    payload: parsed
  })

  return { status: 204 }
}
```

Deduplicate workers strictly by `webhook-id` (with multi-day TTL) rather than `bookingId`, because one booking emits multiple distinct events over its lifecycle.

### Webhook Gotchas: Ancestor Events, Unfired Triggers, and Filter Risks

Four runtime quirks shape production webhook handlers:

1. **Subscribable vs emitted events:** Revoking an API key emits `apiKey.updated` (`status: "revoked"`) rather than `apiKey.deleted`, and only `child-organization.created` fires in the org group. Test event emission directly on UAT (`uatexpress`).
2. **Ancestor fan-out:** Ticketing events dispatch to both the ordering organization and each ancestor up the tree using each ancestor's NET rate. Route `order.issuedTicket` separately from `order.childOrgIssuedTicket`.
3. **PII redaction:** Webhook bodies bypass role-based REST serialization filters. Never log raw payloads with passenger PII, and anchor business logic on `GET /api/v1/bookings/{id}`.
4. **Skip complex server-side filters:** Server-side webhook filters support only 6 strict operators, and malformed filter rules in cancellation flows can halt delivery loops. Ingest unfiltered events and filter locally.

## Partial Multi-Leg Failures, Silent Faults, and Reconciliation Loops

Because webhooks lack a partner-queryable delivery history or replay API, combine event listeners with three scheduled reconciliation sweeps.

- **Partial round-trip issuance:** When an outbound leg issues (`status 10`) while the return leg errors, Ferry VN refunds the failed leg's NET debit and leaves the parent booking out of status `10`. Inspect child `orders` via `GET /api/v1/bookings/{id}` to save the valid outbound ticket and escalate to Ferry ops instead of re-calling `confirmToIssue`.
- **Parent vs child status `6` collision:** Status `6` (`Issue Error`) shares its integer value across parent bookings and leg orders with distinct operational semantics. Namespace `booking.status` and `order.status` enums separately.
- **Disruption and refund sweeps:** Poll `GET /api/v1/disruptions?updated_since=<iso>` (ordered by `updated_at` ascending, zero passenger PII) to capture missed weather closures, and poll individual org states on cancellation requests (allowing up to 15 minutes for root-approval refund sweeps).
- **Silent `HTTP 200 []` guard:** Alert and retry with backoff rather than expiring local orders if a daily sweep returns an unexpected empty array.

For timetable TTLs and Beaufort Force 6 closures, see our [live availability and disruption sync guide](/en/live-availability-inventory-sync-island-ferries/).

## Observability, Alerting, and Go-Live Reliability Checklist

Attach a unique `x-request-id` UUID to every outbound call so logs correlate cleanly across systems, then pass five UAT drills on `https://api.ferryvn.net` (`uatexpress`) before switching to Production keys:

1. **Signed delivery & retry drill:** Run Dashboard **Send test** (`webhook.test`), then force a temporary HTTP `500` on a `uatexpress` UAT booking to verify the ~30-second retry preserves `webhook-id`.
2. **Error & silence alerts:** Page on spikes in `booking.issuedTicketError`, >1% HTTP `429` rates, or zero webhook traffic during peak Vietnam hours (`06:00–22:00` GMT+7).
3. **Zero-downtime rotation drill:** Test one `24h` API key rotation and one `24h` `whsec_...` webhook secret rotation on UAT.
4. **HTTP `403` health probe:** Because internal `90xxxx` auth errors return generic HTTP `403`, probe `/api/v1/locations` during `403` spikes to isolate revoked keys from transient blips.
5. **Daily `00:30` GMT+7 ledger sweep:** Reconcile local issued and refunded counts against `Bookings`, `Transactions`, and `Debt Ledgers`.

Review error definitions in the [live REST API schemas](https://api.ferry.vn/docs) and implementation guides in the [partner webhook and reconciliation docs](https://docs.ferry.vn/en/developers/), or contact `hi@ferry.vn` (`+84 924 299 898`).

## Frequently Asked Questions

| Question | Answer |
| --- | --- |
| Are Ferry VN webhooks signed by default and how many times do they retry? | Signing is opt-in per organization through the Dashboard, where admins create a whsec_... Standard Webhooks HMAC-SHA256 secret. Transient failures (network drops, &gt;2-second timeouts, HTTP 408, 429, or 5xx) retry automatically 3 times at roughly 30 seconds, 5 minutes, and 30 minutes, for 4 total attempts preserving webhook-id . |
| Does the 5-per-60-seconds limit on `confirmToIssue` throttle our entire OTA? | No. Both the HTTP 429 throttler ( client IP + bookingId ) and the cluster-wide HTTP 422 soft cooldown ( 120140 , keyed by bookingId ) isolate throttling per booking. One failing order stops after five confirmation tries in 60 seconds while every other concurrent OTA checkout keeps its own independent budget. |
| How should our system handle a partial failure on a round-trip ferry booking? | When one leg issues and another fails, Ferry VN refunds the failed leg while leaving the issued leg valid and keeping the parent booking out of status 10. Inspect individual child orders via GET /api/v1/bookings/{id} and contact Ferry operations rather than re-running confirmToIssue across the whole booking. |
| Why should we never delete local records when a list endpoint returns HTTP 200 with an empty array? | On transient database or authorization faults, Ferry VN list endpoints can catch internal exceptions and return HTTP 200 with an empty array [] instead of HTTP 500. Always treat unexpected empty responses on active routes as potential transient blips, alert operations, and retry with backoff. |
| Can partners rotate webhook signing secrets without downtime? | Yes. Organization administrators click Rotate secret in the Dashboard and choose a grace window ( 1h , 24h , or 7d ). During grace, Ferry VN sends two space-separated HMAC-SHA256 signatures in webhook-signature , allowing receivers to validate against both the new and previous secrets throughout deployment. |
