Scrivio Interview library
CodingFoundations7 min read · updated 13 November 2026

Webhooks are HTTP callbacks a platform sends to a customer's URL when something happens. Because anyone can send a request to that URL, the receiver must verify each delivery came from the platform and is not an old message replayed.

How should webhook payloads be signed and verified? Outline the verification code in Java.

The sender computes an HMAC-SHA256 over the message id, a timestamp and the raw body using a secret it shares with that endpoint, and sends the id, timestamp and signature in headers (webhook-id, webhook-timestamp and webhook-signature in the Standard Webhooks convention). The receiver recomputes the HMAC over the exact raw bytes it received, before any JSON parsing, compares it in constant time with MessageDigest.isEqual, rejects timestamps older than about 5 minutes and ids it has already processed, and accepts either of two secrets during rotation.

Background to this question

A webhook endpoint is a public URL that performs real actions, marking orders paid or provisioning accounts, when a request arrives. Anyone who learns or guesses the URL can send it a request, and anyone who captured an old request can send it again. Signatures solve both problems, but only if the receiver verifies them exactly right, and the small details, raw bytes, constant-time comparison and timestamps, are where most implementations go wrong. In this answer, we will recap what an HMAC is, see what the sender signs and why each part is included, write the verification code in Java step by step, add replay protection, and handle secret rotation.

1A Quick Recap of HMAC

An HMAC (hash-based message authentication code) is a fingerprint of a message computed with a secret key. HMAC-SHA256 takes the key and the message and produces 32 bytes. Anyone who has the same key and the same message gets the same 32 bytes; anyone without the key cannot produce them, and changing a single byte of the message changes the result completely.

For webhooks, the platform and the customer share a secret per endpoint, created when the endpoint is registered. The platform signs each delivery with it, and the receiver checks the signature with its copy. A valid signature proves two things: the request came from someone who knows the secret, and the signed content was not modified on the way.

2What the Sender Signs and Why

The sender does not sign only the body. It signs a string made of the message id, the timestamp and the raw body, joined with dots: msg_2Qx7.1763030400.{"type":"invoice.paid",...}. Each part has a job. The body is the content we want to protect. The timestamp lets the receiver reject old messages, and because it is inside the signature, an attacker cannot change it to make an old message look fresh. The id identifies the message, so the receiver can recognise a repeat, and again it cannot be swapped.

The sender then puts the three values in headers. The Standard Webhooks convention, which several webhook providers follow, uses webhook-id, webhook-timestamp (Unix seconds) and webhook-signature, where the signature is written as v1, followed by a comma and the base64-encoded HMAC. The version prefix allows several signatures in one header, separated by spaces, which matters for rotation.

Step throughSigning and verifying one delivery
PlatformReceiver
content = id + '.' + timestamp + '.' + raw body
sig = HMAC-SHA256(secret, content)
POST body + webhook-id, webhook-timestamp, webhook-signature
check timestamp within 5 minutes
recompute HMAC over the raw bytes
constant-time compare, check id not seen
204 No Content

7 messages in order. Play them, or step through them one at a time.

3Verifying in Java, Step by Step

The verification code has to work on the raw bytes of the request body, exactly as they arrived. In Spring, that means reading the body as byte[] or String yourself instead of letting Jackson bind it to an object first.

Java
@PostMapping("/webhooks/billing")
public ResponseEntity<Void> receive(@RequestHeader("webhook-id") String id,
@RequestHeader("webhook-timestamp") String ts,
@RequestHeader("webhook-signature") String sigHeader,
@RequestBody byte[] rawBody) throws Exception {
long sent = Long.parseLong(ts);
long now = Instant.now().getEpochSecond();
if (Math.abs(now - sent) > 300) return ResponseEntity.status(400).build(); // older than 5 minutes
byte[] signed = (id + "." + ts + ".").getBytes(StandardCharsets.UTF_8);
byte[] content = ByteBuffer.allocate(signed.length + rawBody.length)
.put(signed).put(rawBody).array(); // id.timestamp.rawBody
if (!matchesAny(content, sigHeader, secrets.current(), secrets.previous()))
return ResponseEntity.status(401).build(); // forged or modified
if (!events.storeIfNew(id, rawBody)) // unique constraint on the message id
return ResponseEntity.noContent().build(); // replay or retry: already stored
// JSON is parsed later, by the asynchronous processor
return ResponseEntity.noContent().build();
}
static boolean matchesAny(byte[] content, String header, byte[]... keys) throws Exception {
for (byte[] key : keys) {
if (key == null) continue;
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key, "HmacSHA256"));
byte[] expected = mac.doFinal(content); // 32 bytes
for (String part : header.split(" ")) { // "v1,abc= v1,def="
String[] p = part.split(",", 2);
if (p.length == 2 && p[0].equals("v1")
&& MessageDigest.isEqual(expected, Base64.getDecoder().decode(p[1]))) // constant time
return true;
}
}
return false;
}

Notice the order of the checks. We reject stale timestamps first because it is cheap. We recompute the HMAC over the bytes we received, with Mac.getInstance("HmacSHA256") initialised with the endpoint's secret (with Standard Webhooks, the secret is shown with a whsec_ prefix and is base64-encoded, so we decode it to bytes once at startup). Only after the signature is valid do we look at the id, and only then do we parse the JSON.

4Why Constant-Time Comparison Matters

String.equals and Arrays.equals stop at the first byte that differs. That makes the comparison slightly faster when the first bytes are wrong than when many bytes are right. With enough requests and careful timing, an attacker can learn the correct signature one byte at a time, a timing attack. MessageDigest.isEqual compares all bytes regardless of where they differ (it has been constant time since Java 6u17), so the time it takes reveals nothing. It is a one-word change that removes a whole class of attack.

5Stopping Replays and Rotating Secrets

A valid signature is still valid if someone records the request and sends it again tomorrow. Two checks stop that. The timestamp tolerance, typically 5 minutes, rejects anything older, and because the timestamp is signed it cannot be refreshed. Within those 5 minutes, we remember processed message ids, for example in Redis with SET id 1 NX EX 600 or in a table with a unique constraint, and treat a repeated id as already handled. The id store only needs to keep ids a little longer than the tolerance window. Remembering ids also handles the platform's own retries, which reuse the same id.

Secrets must be rotated, after a leak or as routine. If the sender switched secrets instantly, every receiver that had not updated its configuration would start rejecting deliveries. So rotation has an overlap: during a rotation period, the sender signs each message with both the old and the new secret and puts both signatures in the header. The receiver, as in the code above, accepts the message if either of its configured secrets matches any signature. The customer deploys the new secret at their own pace, and when the overlap ends the old secret is removed on both sides.

Step throughReceiver checks, in order
  1. Timestamp within 5 minutes?
    YesContinueNoReject 400: too old
  2. HMAC over raw bytes matches current or previous secret?
    YesContinueNoReject 401: forged or modified
  3. Message id seen before?
    YesReturn 2xx, do nothingNoStore event, return 2xx
  4. Process the event asynchronouslyparse JSON here, not before

4 steps in order. Play them, or step through them one at a time.

6Follow-up questions

Why is verifying the signature over re-serialised JSON a common bug?

Because the signature covers bytes, not meaning. If the framework parses the body into an object and we serialise it back to compute the HMAC, the result usually differs from what the sender signed: key order, whitespace, number formats such as 1.0 versus 1, escaping of slashes or Unicode can all change. Verification then fails for valid messages, and a team under pressure may 'fix' it by loosening the check. Worse, two different byte sequences can parse to the same object, so verifying a re-serialised form proves less than it seems. Always verify the raw bytes exactly as received, and parse afterwards.

Should the receiver return 401 for a bad signature?

Returning 4xx is fine; the platform will usually retry and eventually mark the delivery as failed, which shows the misconfiguration in its dashboard. Do not return details about why verification failed, to avoid helping an attacker.

7Conclusion

In this answer, we saw that webhook signing uses an HMAC-SHA256 over the message id, timestamp and raw body with a per-endpoint secret, sent in webhook-id, webhook-timestamp and webhook-signature headers. The receiver recomputes the HMAC over the raw bytes before parsing, compares in constant time with MessageDigest.isEqual, rejects messages older than about 5 minutes, remembers processed ids to stop replays, and accepts either of two secrets so rotation needs no downtime.

What to say in the interviewAbout 90 seconds aloud

Open with

The sender and the receiver share a secret per endpoint. For each delivery, the sender builds a string from the message id, a timestamp and the raw body, computes HMAC-SHA256 over it with the secret, and sends the id, timestamp and signature in headers.

Then, if they want more

The Standard Webhooks convention calls them webhook-id, webhook-timestamp and webhook-signature. Including the id and timestamp in the signed content means an attacker cannot change them. On the receiving side in Java, I read the body as raw bytes, not as a parsed object. I first check that the timestamp is within about five minutes.

Then I rebuild id dot timestamp dot body, compute the HMAC with Mac.getInstance HmacSHA256 initialised with the secret, and compare it with the signature using MessageDigest.isEqual, which is constant time, never String.equals, because an early-exit comparison leaks timing information.

Only if it matches do I check the message id against a store of processed ids, which stops replays within the window and also handles the sender's own retries. Then I store the event, return 2xx, and parse and process it asynchronously. Re-serialised JSON is a classic bug: key order or whitespace changes and the signature no longer matches.

For rotation, the sender signs with both old and new secrets during an overlap, and the receiver accepts a match with either.

About this answer

Last updated
13 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How should webhook payloads be signed and verified? Outline the verification code in Java.": https://scrivio-interview-library.netlify.app/architecture/api-design-at-scale/d4c97a8d71/