Designing a Document Signing API: Idempotency Keys, Quota Headers, and Signed Webhooks

When your onboarding or checkout pipeline sends agreements automatically, a network timeout must never email a customer twice or use two documents for one agreement. Here is how idempotent creation and verified webhooks work.

DS
DocMe Sign team
Product team
Published 9 min read
API calls from web, mobile and server apps, a usage dial, and JSON webhook events
Idempotency keys, quota and rate-limit headers, and timestamped HMAC-SHA256 webhooks keep automated agreement pipelines safe under network retries.

Executive Summary & Key Takeaways

  • Send an `Idempotency-Key` header on `POST /api/v1/envelopes` (and on template sends): a retry with the same key returns the agreement already created—`200` with `Idempotency-Replayed: true`—so nobody gets a second email and no second document is used.
  • Answers to live keys carry `X-DocMeSign-Plan`, `X-DocMeSign-Quota-Limit` and `X-DocMeSign-Quota-Remaining`; every answer carries `X-RateLimit-Limit`, `X-RateLimit-Remaining` and `X-RateLimit-Reset` (120 writes and 600 reads a minute per key).
  • Webhook events such as `envelope.sent`, `recipient.verified` and `envelope.completed` are signed with an HMAC-SHA256 of the timestamp and the raw body, so receivers can reject forged or replayed callbacks.
  • Answer webhooks quickly with a `2xx` once the signature checks out, and do slower work (CRM updates, archiving) in the background.

1. Why Agreement APIs Need Strict Payment-Grade Idempotency

Creating and sending a legal agreement has irreversible external side effects—much closer to charging a credit card than updating a CRUD profile record. When your backend sends an agreement during vendor onboarding, a lease checkout or automated HR onboarding, the server stores the PDF, records its SHA-256 fingerprint, uses a document from your plan, and emails a person.

If a transient TLS reset or load-balancer timeout drops the HTTP response after the server commits the envelope, a naive retry loop without idempotency creates a second agreement, sends a second invitation email (confusing the signer), and uses two documents for one business event.

Following the same pattern as Stripe and the IETF `Idempotency-Key` draft, DocMe Sign ties agreement creates (`POST /api/v1/envelopes` and `POST /api/v1/templates/{id}/send`) to a key you supply, scoped to your organization.

2. How Replays Work, Including Two Requests at Once

When a create carries an `Idempotency-Key` (up to 200 characters), DocMe Sign derives the new agreement's identity from your organization and that key. The key is stored with the agreement, so a replay works for at least 24 hours.

Three outcomes keep client state machines predictable: (1) A new key—the agreement is created and sent, one document is used, and the answer is `201 Created`. (2) A key already used—the answer is `200` with the agreement that key created and `Idempotency-Replayed: true` (older clients may also see `Idempotent-Replayed`); nothing is sent or counted again. (3) Two requests with the same key at the same moment—one creates the agreement and the other gets it back as a replay. The key alone decides: a replay returns the first agreement even if the body changed, so use a new key for a new agreement.

3. Quota and Rate-Limit Headers You Can Act On

Testing an API shouldn't need a sales call. Every workspace can create test keys (`dms_test_…`) whose agreements are never emailed or counted, up to 50 a day; live keys come with the Growth & API Pro plan (see pricing). Plans include a fixed number of documents and there is no overage: when they are used, sends answer `402` with code `plan_limit` until the next period or an upgrade.

To avoid silent pipeline stalls, answers carry headers your code can watch—for example to alert your team at 80% of the plan or to slow a batch down before the rate limit.

Response headers on the v1 API
HTTP Response HeaderExample ValueMeaning & What to Do
X-DocMeSign-Quota-Limit500Live keys: documents included in this period (the Free plan's 50 are a one-time allowance)
X-DocMeSign-Quota-Remaining7Live keys: documents left; at 0, sends answer 402 with code plan_limit
X-RateLimit-Limit / -Remaining / -Reset120 / 117 / 1795600860Requests allowed this minute for this key (120 writes, 600 reads), how many are left, and when the minute ends (Unix seconds)
Idempotency-ReplayedtrueThis is the agreement an earlier request with the same key created; nothing was sent or counted again
Retry-After12After a 429: seconds to wait (rate limit, the test keys' daily allowance, or a reminder asked for too soon)

4. Verifying Timestamped HMAC-SHA256 Webhooks in Node.js / Next.js

Polling `GET /api/v1/envelopes/{id}` every thirty seconds wastes compute when contracts may sit in an executive's inbox over a weekend. Instead, add an HTTPS webhook endpoint and choose the events it gets: for example `envelope.sent`, `recipient.verified`, `envelope.completed` (with `sha256_completed_pdf` and the agreement, including `sha256_source` and its download link) and `envelope.declined`.

Because webhook URLs are reachable over the public internet, your endpoint must never trust an unsigned JSON POST body. DocMe Sign signs `${timestamp}.${rawBody}` with your endpoint's secret using `HMAC-SHA256` and sends `X-DocMeSign-Timestamp: <unix seconds>` and `X-DocMeSign-Signature: sha256=<hex digest>`. After you rotate the secret, the old one also signs each delivery for 24 hours, in `X-DocMeSign-Signature-Previous`.

Always verify against the exact unparsed UTF-8 raw request bytes, enforce a 300-second clock-skew tolerance to defeat replay attacks, and compare digests with `crypto.timingSafeEqual` to eliminate timing side-channels.

app/api/webhooks/docmesign/route.tstypescript
import crypto from "node:crypto";
import { NextResponse } from "next/server";

const TOLERANCE_SECONDS = 300;

export async function POST(request: Request): Promise<Response> {
  const timestampHeader = request.headers.get("x-docmesign-timestamp") ?? "";
  const signatureHeader = request.headers.get("x-docmesign-signature") ?? "";
  const rawBody = await request.text();
  const secret = process.env.DOCMESIGN_WEBHOOK_SECRET ?? "";

  const timestamp = Number(timestampHeader);
  const receivedHex = signatureHeader.replace(/^sha256=/, "");
  if (!Number.isFinite(timestamp) || !receivedHex || !secret) {
    return NextResponse.json({ error: "Invalid signature headers" }, { status: 401 });
  }

  const ageSeconds = Math.abs(Math.floor(Date.now() / 1000) - timestamp);
  if (ageSeconds > TOLERANCE_SECONDS) {
    return NextResponse.json({ error: "Expired webhook timestamp" }, { status: 401 });
  }

  const expectedHex = crypto
    .createHmac("sha256", secret)
    .update(`${timestampHeader}.${rawBody}`, "utf8")
    .digest("hex");

  const a = Buffer.from(receivedHex, "hex");
  const b = Buffer.from(expectedHex, "hex");
  if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
    return NextResponse.json({ error: "Signature mismatch" }, { status: 401 });
  }

  const event = JSON.parse(rawBody) as { id: string; type: string };
  // Deduplicate on event.id in Postgres/Redis, queue background work, and answer fast:
  return NextResponse.json({ received: true, eventType: event.type });
}

5. Designing At-Least-Once Webhook Consumers

Distributed webhook delivery guarantees at-least-once semantics, not exactly-once: if your server processes `envelope.completed`, writes to S3, and then hits a 504 gateway timeout before returning `200 OK`, DocMe Sign retries it after 1 minute, 5 minutes, 30 minutes, 2 hours and 12 hours, then gives up. The event's `id` stays the same on every attempt, so storing processed `event.id` values in a `webhook_deliveries` table with a `UNIQUE` constraint makes your handler idempotent too—completing the loop from creating the agreement to archiving the signed PDF.

Frequently Asked Questions

Do failed requests or idempotent replays use a document?

No. A document is used only when an agreement is actually sent with a live key. Requests that fail validation, replays of an Idempotency-Key, reminders, reads and downloads don't use one.

Why did HMAC verification fail when I serialized req.body with JSON.stringify()?

JSON parsers strip insignificant whitespace and may reorder keys, changing the byte sequence that was originally signed. Always read the raw request body via await request.text() before calling JSON.parse().

How many times does DocMe Sign retry failed webhook deliveries?

Five more times after the first attempt: after 1 minute, 5 minutes, 30 minutes, 2 hours and 12 hours. Each attempt keeps the event's id and is signed again with a fresh timestamp. You can also send a test event from Settings → Developers or with POST /api/v1/webhooks/{id}/test.

Can we test the API and webhooks before upgrading to a paid plan?

Yes. Test keys (dms_test_…) work on every plan, including Free: their agreements are marked TEST, never emailed and don't count, up to 50 a day, and webhooks fire for them too (with test_mode set to true). Live keys come with Growth & API Pro; see pricing.

Continue reading
View all 7 guides