InstaWebhook
December 3, 2026By InstaWebhook TeamWebhook Security

Clock Skew, Container Drift, and Timestamp Windows in Webhook Signature Verification

Why naive timestamp checks fail in webhook signature verification due to NTP slew, container drift, and VM pauses—plus how to tune skew tolerances safely without weakening replay protection.

Clock Skew, Container Drift, and Timestamp Windows in Webhook Signature Verification

Clock Skew, Container Drift, and Timestamp Windows in Webhook Signature Verification

Webhook signature verification looks simple on paper. The sender computes an HMAC over the payload with a shared secret. Many senders also bind a Unix timestamp into the signed material and send both in HTTP headers. The receiver recomputes the digest, compares it in constant time, and enforces a freshness check, usually some form of abs(now - timestamp) <= 300.

Five minutes is the default in many libraries. Stripe’s libraries default to a 5-minute tolerance, and so do the reference libraries of the Standard Webhooks specification. On a laptop or a well-synchronized staging cluster the check is invisible. In production it can reject valid events when a node’s clock is off, when a VM pauses, or when your own pipeline delays verification.

This article covers where time errors come from in virtualized and containerized infrastructure, what timestamp checks do and don’t protect against, and how to design the check so it stays strict about replays without making clock problems an outage. It also covers monitoring for skew and keeping host clocks accurate.

How Major Providers Handle Timestamps

Providers differ on whether a timestamp is signed at all, and this affects everything below.

Provider / schemeSigned materialTimestamp in signature?Notes
Stripe (Stripe-Signature: t=…,v1=…)timestamp.payload, HMAC-SHA256, hexYesLibrary default tolerance is 5 minutes. A retried delivery gets a new signature and timestamp.
Standard Webhooks / Svix (webhook-id, webhook-timestamp, webhook-signature)id.timestamp.payload, HMAC-SHA256, base64 (v1,<sig>)YesThe timestamp reflects the delivery attempt and is refreshed on each retry. webhook-id stays constant across retries. Reference libraries apply a 5-minute tolerance in both directions.
GitHub (X-Hub-Signature-256)Raw payload, HMAC-SHA256, hex, prefixed sha256=NoGitHub’s body-only signature does not authenticate a delivery timestamp.
Shopify (X-Shopify-Hmac-SHA256)Raw payload, HMAC-SHA256, base64NoBody-only signature.

Two consequences follow:

  1. Not every provider gives you a timestamp to check. For body-only schemes such as GitHub and Shopify, a freshness window is impossible. Replay protection has to come from deduplicating on a delivery or event ID.
  2. Retries do not carry stale signatures at Stripe or Standard Webhooks senders. Because the timestamp is regenerated per attempt, a timestamp rejection on a retried delivery points to a clock problem on your side or to delay between signing and verification. It does not mean the retry was old. Svix notes that redeliveries from a dead-letter queue or a manual replay also carry the new attempt’s timestamp.

Some providers use millisecond epoch timestamps instead of seconds. Your parser should handle both, as the implementation below does.

Why Timestamp Checks Misfire in Cloud Infrastructure

Developers often treat time.time(), Date.now(), or System.currentTimeMillis() as a monotonic, perfectly accurate source of truth. Wall-clock time on a virtual machine is neither. It is a value that an NTP or PTP client is continuously correcting.

1. Hypervisor Pauses and Live Migration

Cloud providers perform host maintenance by moving running VMs. The process is not entirely invisible to the guest. Google Compute Engine, for example, documents live migration in three stages: a source brownout while memory is copied, a brief blackout when the VM runs nowhere, and a target brownout. The documented disruption is typically much less than one second. Even so:

  • During a blackout, the guest’s system clock can appear to jump forward, by up to 5 seconds. If the blackout exceeds 5 seconds, Google stops the guest and resynchronizes the clock using a daemon in the guest packages.
  • Anything timestamped by your own code across such an event, such as request-arrival times, can show a discontinuity.

Heavy CPU contention or noisy neighbors can also stall a guest, though these effects are harder to characterize than documented migrations. The practical lesson is that the guest clock can be briefly wrong in either direction until its time-sync client catches up. A symmetric 300-second window absorbs most of this, but a tight window or a tight future bound may not.

2. Containers Share the Host Kernel’s Wall Clock

Docker containers and Kubernetes pods do not have their own wall clocks. They share the host kernel’s CLOCK_REALTIME. Linux time namespaces (kernel 5.6 and later) virtualize only CLOCK_MONOTONIC and CLOCK_BOOTTIME, not CLOCK_REALTIME. Every pod on a node therefore inherits that node’s time accuracy, including any problem with the node’s time daemon. Sandboxed runtimes that run a separate guest kernel, such as microVM-based ones, have their own guest clock instead.

Time daemons correct error in one of two ways:

  • Slewing gradually changes the clock rate so time never jumps. The slew rate is bounded and varies by daemon. ntpd limits slewing to 500 ppm, so correcting a 3-second offset takes about 6,000 seconds (100 minutes). chrony is more aggressive: its default maximum slew rate is 83,333 ppm (one twelfth), and on Linux its driver allows up to 100,000 ppm. It also paces corrections with corrtimeratio, so real correction times are longer than the theoretical minimum.
  • Stepping jumps the clock. In chrony, makestep <threshold> <limit> steps the clock when the offset exceeds the threshold, but only during the first <limit> clock updates after startup. A negative limit removes that restriction. Traditional ntpd steps above a 128 ms threshold. A backward step can make a request that has just arrived look as though it carries a future timestamp.

3. Sender Clocks, and Your Own Pipeline

Cloud-hosted senders usually run on well-synchronized clocks, for example the clock services described later in this article. Self-hosted systems, legacy integrations, and edge devices can be much less accurate. A sender whose clock runs fast produces timestamps that look like they come from the future, and a symmetric check treats them the same as stale ones.

Between the moment the sender signs and the moment your code verifies, delay can accumulate:

  1. Sender egress queuing, between signing and obtaining a connection.
  2. Connection setup and routing, including TCP and TLS handshakes on long-distance paths.
  3. Ingress buffering in reverse proxies and API gateways.
  4. Serverless cold starts or pod autoscaling, which delay your middleware from running.
  5. Your own queue. If you enqueue the raw request and verify in a worker, queue wait counts against the freshness window. This is a common self-inflicted failure.

Individually these are small. Because providers sign per attempt, large gaps between signing and verification are uncommon unless your own system introduces them. Verify at the ingress edge, before the work is queued, and move only the verified event ID onward.

What Timestamp Validation Protects Against, and What It Doesn’t

Threat Model: Replay

If an attacker captures a legitimate webhook and its signature, for example through compromised log storage or an unencrypted internal hop, the HMAC remains valid indefinitely, because neither the secret nor the payload has changed. A replayed payment.succeeded event could credit an account or trigger fulfillment a second time.

Binding a timestamp into the signed string, as in Stripe’s t=…,v1=… scheme or the Standard Webhooks id.timestamp.payload format, means a captured request can only be replayed until the timestamp falls out of the tolerance window. An attacker cannot refresh the timestamp without the secret.

Why Timestamps Alone Are Not Enough

A 300-second window does not stop an attacker from replaying the same request many times inside those 300 seconds. OWASP’s webhook guidance pairs an authenticated timestamp tolerance with authenticated event-ID deduplication. The timestamp also bounds how long the deduplication cache has to remember IDs.

Security layerPrimary roleFailure mode when misconfigured
HMAC-SHA256 verificationAuthenticates sender and payload integrityRejects valid traffic after secret rotation mismatches or body re-serialization
Timestamp freshness windowBounds how old (or how far ahead) an accepted request can be, and sizes the replay cacheRejects valid traffic under clock skew, or leaves a long replay window if too loose
Event/delivery ID deduplicationPrevents repeated side effects for the same eventDuplicate fulfillment, double ledger entries, race conditions

With a bounded timestamp check and a deduplication store, a replayed request that is still inside the window hits an already-recorded ID and can be acknowledged without re-running business logic.

Designing Asymmetric Timestamp Windows

Using abs() treats stale timestamps and future timestamps as the same problem. They have different causes.

  • Past timestamps (now - timestamp > 0) come from legitimate transport delay, queueing, cold starts, and a receiver clock that is ahead.
  • Future timestamps (timestamp - now > 0) cannot occur with synchronized clocks. They arise mainly because the sender’s clock is ahead of yours, or your clock is behind or was stepped backward.

The asymmetric approach is the author’s design recommendation. Stripe’s and the Standard Webhooks reference libraries apply one tolerance in both directions, and there is nothing wrong with doing that if your clocks are healthy. Asymmetry just gives you independent control of each direction:

Code example
valid  ⟺  -Δfuture ≤ (now - timestamp) ≤ Δpast
  • Δpast: the maximum accepted age. Start at 300 seconds, the common library default. Raise it only if your telemetry shows legitimate events arriving near the limit. A larger value lengthens the replay window and the deduplication TTL you must keep.
  • Δfuture: the maximum accepted forward skew. Something like 30 to 60 seconds is a reasonable starting point to absorb ordinary clock disagreement. The future bound does not stop an attacker from pre-signing a far-future timestamp, because that would require the secret. It limits how long a captured request from a badly skewed sender remains replayable, and it determines how long the deduplication record has to live.

Reference Implementation (TypeScript)

This example verifies a Stripe-style scheme: HMAC-SHA256 hex over timestamp.body. Adapt the signed string and encoding if your provider differs. For example, Standard Webhooks signs id.timestamp.body and encodes the result in base64.

Code example
import crypto from "node:crypto";

interface VerificationConfig {
  secret: string;
  maxPastSeconds: number;   // e.g. 300
  maxFutureSeconds: number; // e.g. 30
}

interface VerificationResult {
  valid: boolean;
  reason?: string;
  deltaSeconds: number; // now - timestamp; positive = event is in the past
}

export function verifyWebhookSignature(
  rawBody: Buffer,
  timestampHeader: string,
  signatureHeader: string,
  config: VerificationConfig
): VerificationResult {
  // Strict digits-only parse (rejects "", "0x10", "1e3", etc.)
  if (!/^\d{1,16}$/.test(timestampHeader)) {
    return { valid: false, reason: "INVALID_TIMESTAMP_FORMAT", deltaSeconds: 0 };
  }

  const parsed = Number(timestampHeader);
  // Some senders use epoch milliseconds. Normalize only for the time check;
  // the HMAC must be computed over the timestamp string exactly as sent.
  const timestampSec = parsed > 1e12 ? Math.floor(parsed / 1000) : parsed;

  const nowSec = Math.floor(Date.now() / 1000);
  const deltaSec = nowSec - timestampSec;

  if (deltaSec < -config.maxFutureSeconds) {
    return { valid: false, reason: "TIMESTAMP_IN_FUTURE", deltaSeconds: deltaSec };
  }
  if (deltaSec > config.maxPastSeconds) {
    return { valid: false, reason: "TIMESTAMP_EXPIRED", deltaSeconds: deltaSec };
  }

  const signedPayload = Buffer.concat([
    Buffer.from(`${timestampHeader}.`, "utf8"),
    rawBody,
  ]);

  const expected = Buffer.from(
    crypto.createHmac("sha256", config.secret).update(signedPayload).digest("hex"),
    "utf8"
  );
  const received = Buffer.from(signatureHeader, "utf8");

  // timingSafeEqual throws if lengths differ, so check first.
  if (expected.length !== received.length || !crypto.timingSafeEqual(expected, received)) {
    return { valid: false, reason: "SIGNATURE_MISMATCH", deltaSeconds: deltaSec };
  }

  return { valid: true, deltaSeconds: deltaSec };
}

The Same Check in Python

Code example
import hashlib, hmac, time

def verify_webhook(raw_body: bytes, ts_header: str, sig_header: str, secret: bytes,
                   max_past: int = 300, max_future: int = 30):
    if not (ts_header.isascii() and ts_header.isdigit()):
        return False, "INVALID_TIMESTAMP_FORMAT", 0

    ts = int(ts_header)
    ts_sec = ts // 1000 if ts > 10**12 else ts
    delta = int(time.time()) - ts_sec  # positive = event is in the past

    if delta < -max_future:
        return False, "TIMESTAMP_IN_FUTURE", delta
    if delta > max_past:
        return False, "TIMESTAMP_EXPIRED", delta

    signed = ts_header.encode() + b"." + raw_body
    expected = hmac.new(secret, signed, hashlib.sha256).hexdigest()

    # Comparing bytes avoids the TypeError compare_digest raises for non-ASCII str
    if not hmac.compare_digest(expected.encode(), sig_header.encode()):
        return False, "SIGNATURE_MISMATCH", delta
    return True, None, delta

Implementation Details That Commonly Go Wrong

  1. Verify on the raw bytes. Do not re-serialize JSON.stringify(req.body) before computing the HMAC. Whitespace, key order, and Unicode escaping can all change the bytes. Configure your framework to expose the raw body to the verification step.
  2. Mind the comparison function’s edge cases. Node’s crypto.timingSafeEqual throws a RangeError when the buffers have different lengths, so check lengths first. Python’s hmac.compare_digest returns False for different-length inputs of the same type. It raises TypeError for mismatched types or for str arguments containing non-ASCII characters, so compare bytes.
  3. Sign over the original timestamp string. If you normalize milliseconds to seconds for the freshness check, do not substitute the normalized value into the signed string.
  4. Return uniform, minimal errors. OWASP recommends returning 401 for a missing or mismatched signature without saying why. Log the specific reason internally instead. Stripe’s own examples respond with 400, so check what your provider’s retry logic expects. Either way, don’t tell callers how far off their timestamp is.
  5. Verify before you enqueue. As noted above, queue time counts against the window.

Observability: Catching Skew Before It Becomes an Outage

If you tune the windows and never look at the actual deltas, a node that drifts a little further each day looks healthy until the day it crosses the bound.

What to Emit

For each verification attempt, record at minimum:

  • webhook.provider: the upstream sender.
  • webhook.delta_seconds: the signed now - timestamp. Keep the sign. The absolute value hides whether the problem is latency (positive) or a fast sender or slow local clock (negative).
  • k8s.node.name: lets you pin the problem to one host.
  • Clock-sync state for the node, from chronyc tracking or the kernel’s adjtimex status. The STA_UNSYNC bit (0x0040) in the status word indicates an unsynchronized clock.

Reading the Signals

These patterns are illustrative starting points, not fixed thresholds.

PatternLikely causeFirst check
Negative deltas across all providers on one nodeThat node’s clock is behindchronyc tracking on the node. The System time field shows the pending correction.
Negative deltas for one provider across all nodesThat sender’s clock is aheadCompare with other senders, then contact the provider or set a per-provider Δfuture.
Large positive deltas with high varianceQueueing, ingress saturation, slow cold starts, or delay in your own pipelineWhere verification happens relative to queues; worker concurrency; gateway buffering.
Delta shifts abruptly around a pod or node eventA clock step, a VM pause, or a node restartNode events and time-daemon logs around that time.

Metrics and Alerts

Prometheus classic histograms accept negative bucket bounds, so you can track the signed delta directly, for example with buckets like [-60, -30, -10, -5, 0, 1, 5, 15, 60, 180, 300, 600]. Keep labels to provider and node. Don’t label by event ID.

Reasonable starting alerts:

  • Local clock drift (warning): the median delta on one node is persistently negative, for example below -5 seconds over several minutes, across two or more independent providers. Requiring multiple providers rules out one sender’s bad clock.
  • Approaching rejection (critical): deltas regularly fall within roughly 20% of either bound (for example, beyond about -24 seconds against a 30-second future bound). This gives on-call time to react before valid events start failing.

Keeping Host Clocks Accurate

Window tuning should complement accurate timekeeping, not replace it.

1. Use the Cloud Provider’s Local Time Source

  • AWS: the Amazon Time Sync Service is reachable over NTP at 169.254.169.123, with no internet access or VPC changes required. AWS documents server 169.254.169.123 prefer iburst minpoll 4 maxpoll 4 for chrony. On supported instances with the ENA driver, a PTP hardware clock is also available, for example refclock PHC /dev/ptp0 poll 0 delay 0.000010 prefer.
  • Google Cloud: Compute Engine VMs are preconfigured for NTP, and Google recommends using its internal NTP server at metadata.google.internal and removing external servers from the chrony configuration. For higher accuracy, Google documents a ptp_kvm refclock setup.
  • Azure: recent Linux images expose the host clock as a PTP device, and Microsoft recommends pointing chrony at the stable /dev/ptp_hyperv symlink rather than /dev/ptp0, for example refclock PHC /dev/ptp_hyperv poll 3 dpoll -2 offset 0 stratum 2.

Be careful about leap seconds when mixing sources. AWS’s NTP endpoint smears leap seconds while its PTP hardware clock does not. Google’s clocks smear as well. Avoid combining smearing and non-smearing sources in one configuration.

2. Understand What makestep Actually Does

Many default configurations use something like makestep 1.0 3, meaning chrony may step the clock if the offset exceeds 1 second, but only during the first three updates after startup. If a large offset appears later, chrony slews instead of stepping. With chrony’s default maximum slew rate of 83,333 ppm, the theoretical minimum time to slew away a 12-second offset is about 144 seconds. In practice it takes longer because of correction pacing. This is minutes, not hours, but still a real period of skew.

You can allow stepping at any time:

Code example
# chrony.conf example for ephemeral nodes
server 169.254.169.123 prefer iburst minpoll 4 maxpoll 4

# Step if offset > 0.5 s, at any point in uptime (negative limit = no limit)
makestep 0.5 -1

rtcsync

This comes with a trade-off the chrony documentation states plainly: on most systems it is desirable to step only at boot, before programs that rely on time advancing monotonically forward are running. Backward steps can disturb other software that uses wall-clock time for leases, timeouts, or token expiry. For many fleets, a shorter-lived slew is the safer default, and unrestricted stepping is better reserved for nodes where you’ve considered the impact on everything running there. Whichever you choose, monitor the offset.

3. Size Your Deduplication Store Against the Window

A request with timestamp t is accepted from t - Δfuture through t + Δpast, measured on your clock. The record for each event ID therefore has to survive at least that span, plus a margin for clock error:

Code example
TTL ≥ Δpast + Δfuture + margin

With Δpast = 300 s, Δfuture = 30 s, and a 60-second margin, set the replay-cache TTL to at least 390 seconds. If the TTL were shorter than the window, say 200 seconds, an attacker who captured a request could replay it at 250 seconds, after the ID was evicted but while the timestamp is still acceptable. The OWASP cheat sheet uses a simpler rule for symmetric windows: keep each ID for at least twice the tolerance.

This short replay cache is not a substitute for durable business idempotency. A provider can redeliver the same event much later with a fresh timestamp, as Stripe and Standard Webhooks senders do. Keep a durable record of processed event IDs, for example a unique constraint in your database, for as long as the provider might redeliver. Record the processing state as well, so an event that failed halfway can be retried rather than silently marked done.

Checklist for Production Webhook Receivers

  • Know what your provider signs. Stripe and Standard Webhooks sign a timestamp. GitHub and Shopify sign only the body, so use ID-based deduplication for replay protection.
  • Use a bounded freshness check where a timestamp exists. Start from the 300-second default. Consider separate past and future bounds, for example now - timestamp <= 300 and timestamp - now <= 30.
  • Deduplicate on event or delivery ID. Keep a replay cache with TTL of at least Δpast + Δfuture + margin, and a durable processed-events record for as long as redelivery is possible.
  • Verify at the edge, before queueing, so your own queue delay never counts against the window.
  • Compute the HMAC over raw bytes, sign the timestamp string exactly as sent, and compare in constant time with explicit length and type handling.
  • Log signed delta_seconds per node and per provider, and alert on persistent negative skew and on approach to either bound.
  • Point nodes at the cloud provider’s local time source, and decide deliberately between slewing and stepping after startup.

References