Webhook ingestion pipelines sit at the front of event-driven architectures. Whether the events are Stripe payments, GitHub repository events, or IoT telemetry bursts, an API gateway or ingress proxy has to inspect headers, verify signatures, and discard irrelevant or malformed payloads before anything reaches downstream workers.
Teams have traditionally put this logic directly in the gateway (Go or Rust services), in embedded scripting (Lua in NGINX or Envoy), or in out-of-process plugins such as HashiCorp’s go-plugin, which talks to a plugin subprocess over local RPC. All of these can work well. At high event rates, though, they can add a cost that is easy to overlook: parsing and copying request bodies just to decide whether to throw them away.
This article looks at a different design. The WebAssembly Component Model lets a gateway run sandboxed, tenant-specific filters while keeping the request body in host memory. The guest asks the host questions about the body instead of receiving a copy of it. The idea is old (hand the plugin a handle, not the bytes), but the Component Model gives it a typed, portable, language-neutral form.
A note on terminology: “zero-copy” here is narrow. The kernel still copies data from socket buffers into user space, and TLS decryption still happens. What we avoid is copying the body into the guest’s linear memory and building a second parsed representation of it inside the sandbox.
The Cost of Parsing JSON Bodies in Conventional Gateways
Consider a Go gateway that receives a webhook and needs to read one field, such as event_type, to decide whether to forward it.
1. The Deserialize-to-Inspect Pattern
A common implementation reads the body into a []byte and unmarshals it into a map[string]any or a large struct:
- Body buffering. The body is read from the connection into user-space memory. With TLS, the data is decrypted along the way.
-
Allocation-heavy parsing. Unmarshalling into generic types with
encoding/jsoncreates many small heap objects (maps, slices, strings, boxed values) to represent a document of which you needed one field. - Garbage collection pressure. In a garbage-collected runtime, those short-lived allocations add GC work. If most events end up discarded, that work is spent on payloads that were never going to be forwarded.
- Plugin boundary costs. If filtering is delegated to a plugin, the body (or a transformed version) typically has to cross a process or sandbox boundary, which adds more copies and often a second parse.
None of this is a flaw in Go. It is the cost of general-purpose parsing, and it is worth measuring before you optimize it. For small payloads, or when most events are forwarded anyway, it may not matter.
2. What proxy-wasm Does at the Boundary
proxy-wasm is an ABI specification that Envoy and other proxies implement to run Wasm extensions. It showed that Wasm is a practical way to extend network proxies, and it is still widely used.
Core WebAssembly originally had only numeric value types (i32, i64, f32, f64), so rich data has to be encoded by convention. In proxy-wasm, when a plugin asks for data such as a body range or a header map, the host calls the guest’s exported proxy_on_memory_allocate to get a region of guest linear memory, then writes the bytes into it. The guest can request a byte range with proxy_get_buffer_bytes(buffer_type, start, max_size, ...), so the whole body is not necessarily copied. Header maps are passed in a custom serialized form that the guest must decode.
The point is that the guest’s view of the data is a copy in guest memory, created through a guest-controlled allocator. For a filter that only needs one field, or one signature check, that is more work than necessary.
Defining the Filter Contract with WIT
The WebAssembly Component Model adds typed interfaces on top of core Wasm. Interfaces are described in WIT (Wasm Interface Type), a language-neutral IDL with types such as string, list<T>, option<T>, result<T, E>, record, variant, and resource. A “world” describes the imports a component needs and the exports it provides. Bindings generators such as wit-bindgen produce the glue code for each language.
The standards context has moved recently. WASI 0.2, the first release built on the Component Model, was a stable foundation for several years. WASI 0.3.0 was released on June 11, 2026, adding native async (async func, stream<T>, future<T>) to the Component Model’s canonical ABI. Wasmtime 46.0.0 (June 22, 2026) enabled WASI 0.3.0 and component-model async by default, and runtimes with 0.3 support also run 0.2 components. The filter below is synchronous and does not need the 0.3 async features, so it runs the same way on either version.
The Webhook Filter World
Here is a WIT definition for a filter. The payload is exposed as a host-owned resource instead of a list<u8>:
package edge:webhook-filter@0.2.0;
interface types {
/// An incoming HTTP header.
record header {
name: string,
value: list<u8>,
}
/// The verdict returned by the filter.
variant filter-decision {
/// Forward the event; the string names the destination topic.
accept(string),
/// Reject with an HTTP status code.
reject(u16),
/// Ask the gateway to retry or delay, in milliseconds.
defer(u32),
}
/// A host-owned handle to the request body.
resource payload-view {
/// Total body length in bytes.
size: func() -> u64;
/// Look up a string value by RFC 6901 JSON Pointer.
/// The host scans its own copy of the body; only the result
/// is copied into the guest.
extract-json-string: func(json-pointer: string) -> option<string>;
/// Verify an HMAC-SHA256 signature using a secret the host
/// holds, identified by name. The guest never sees the secret.
verify-hmac-sha256: func(secret-id: string, signature-hex: string) -> bool;
/// Copy a bounded window of the body into the guest.
read-slice: func(offset: u64, length: u32) -> result<list<u8>, string>;
}
}
world webhook-ingress {
use types.{header, filter-decision, payload-view};
/// Host-provided logging.
import log: func(level: u8, message: string);
/// Guest-implemented entry point.
export evaluate: func(
method: string,
path: string,
headers: list<header>,
body: borrow<payload-view>
) -> filter-decision;
}
Why borrow<payload-view> Matters
In the Canonical ABI, a resource crosses the component boundary as an opaque integer handle that indexes a table maintained by the runtime. Passing borrow<payload-view> gives the guest temporary access for the duration of the call, with no transfer of ownership. The body itself stays in host memory.
This changes the cost model:
- If the filter rejects a request based on a header, the body is never copied into guest memory and never parsed inside the sandbox.
- If the filter needs one field, the host extracts it and copies only that value into the guest.
- If a filter really does need raw bytes,
read-slicemakes that an explicit, bounded, auditable operation instead of the default.
The headers and method are still copied into the guest, since they are passed as ordinary WIT values. That is usually small compared with the body.
For contrast, the standard wasi:http interfaces expose bodies to guests as streams that the guest reads, which means the bytes are copied into guest memory as they are consumed. That is the right design for general HTTP handlers, but it is not what you want for a filter that mostly asks yes/no questions about a body it never needs in full.
A Guest Filter in Rust
Using wit-bindgen, the guest implementation looks like this. GitHub signs webhooks with HMAC-SHA256 and sends the result in the X-Hub-Signature-256 header as sha256=<hex digest>, and the pull_request event payload includes a top-level action field.
wit_bindgen::generate!({
world: "webhook-ingress",
path: "wit/webhook.wit",
});
use edge::webhook_filter::types::{FilterDecision, Header, PayloadView};
struct IngressFilter;
impl Guest for IngressFilter {
fn evaluate(
_method: String,
_path: String,
headers: Vec<Header>,
body: &PayloadView,
) -> FilterDecision {
let find = |name: &str| {
headers
.iter()
.find(|h| h.name.eq_ignore_ascii_case(name))
.and_then(|h| std::str::from_utf8(&h.value).ok())
};
// 1. Cheap header checks first; the body is not touched yet.
if find("x-github-event") != Some("pull_request") {
return FilterDecision::Reject(202); // valid but irrelevant
}
let Some(signature) = find("x-hub-signature-256")
.and_then(|s| s.strip_prefix("sha256="))
else {
return FilterDecision::Reject(401);
};
// 2. Signature check, performed by the host over its own buffer.
if !body.verify_hmac_sha256("tenant-prod-secret", signature) {
return FilterDecision::Reject(403);
}
// 3. Targeted field extraction; no full parse inside the sandbox.
match body.extract_json_string("/action").as_deref() {
Some("opened") | Some("synchronize") => {
FilterDecision::Accept("webhooks.github.pull_request".to_string())
}
Some(_) => FilterDecision::Reject(202),
None => FilterDecision::Reject(400),
}
}
}
export!(IngressFilter);
Rust can build this directly as a component with cargo build --target wasm32-wasip2 --release, or with the cargo-component tool. Other languages with component tooling can implement the same world, including Go (via TinyGo) and JavaScript (via componentize-js/jco), so tenants are not forced to use Rust.
Two implementation notes:
- The host’s
verify-hmac-sha256must compare digests in constant time. - Keeping the secret on the host side, referenced only by an ID, means a tenant’s filter code never handles the key material.
Wiring the Host: Buffers, Resources, and Scanning
The host side is where the savings are actually realized. The following assumes a Rust gateway embedding Wasmtime, but the design applies to any runtime that supports host-defined resources.
1. Reference-Counted Request Buffers
Rust HTTP stacks commonly represent body chunks as bytes::Bytes, a reference-counted view of a buffer. Cloning a Bytes handle increments a reference count and does not duplicate the underlying data. Cloudflare’s open-source Pingora framework, for example, works with Bytes-based buffers.
The host flow looks like this:
- Read the body into a
Bytesbuffer, enforcing a maximum body size before invoking any filter. - Create a host-side struct that wraps the buffer and implements the
payload-viewresource, then insert it into Wasmtime’sResourceTable. - Call the guest’s
evaluate, passing the resource as a borrowed handle. - When the call returns, drop the table entry.
One caveat: if the body arrives as several non-contiguous chunks, a scanner that wants a single contiguous slice will need the chunks coalesced first. That is a host-side cost you should account for.
Wasmtime 46 also added direct support for lifting and lowering Bytes and BytesMut in its component-model async integration, which may further reduce friction when bodies flow through streams, though that is separate from the borrowed-resource pattern described here.
2. Host-Side Scanning with SIMD JSON Parsers
When the guest calls extract-json-string("/action"), the call crosses from the guest into a host function. The host can then run an optimized native parser directly over the buffer. Libraries such as simdjson (C++) and sonic-rs (Rust) use SIMD instructions and support lazy or on-demand access patterns, so they can locate a value by path without materializing the whole document as an object tree. simdjson’s on-demand API supports JSON Pointer lookups.
Only the requested value is copied into guest memory. For returned strings, the Canonical ABI uses the guest’s exported cabi_realloc to allocate space, then writes the bytes there.
Two honest caveats:
- A structural scan still has to read the document, and the first pass in these parsers validates and indexes the whole input. You save allocations and copies, not the work of scanning.
- The host parser is native code processing untrusted input, which makes it part of your attack surface. Fuzz it, set depth and size limits, and keep it up to date.
3. When the Guest Needs the Bytes
Some filters need custom logic, such as a tenant-specific regular expression or a proprietary binary format. In that case the body must enter the guest, and a copy is unavoidable. You can still control the cost:
- Use
read-slicefor bounded windows instead of the whole body. - Cap
lengthon the host and return errors for oversized requests. - Consider whether the logic can be offered as a host-side primitive instead (for example, a vetted pattern-matching function), which keeps the data out of the guest.
Comparing the Approaches
The table below is qualitative on purpose. Actual latency depends on payload size, parser choice, hardware, and runtime configuration, so measure your own workload.
| Approach | How the body reaches the filter | Body bytes copied into the filter’s memory |
|---|---|---|
| Out-of-process plugin (e.g. local RPC) | Serialized and sent over a socket or pipe, then parsed by the plugin | Yes, plus an inter-process transfer |
proxy-wasm |
Guest requests ranges; host allocates in guest memory via proxy_on_memory_allocate and copies |
Yes, for the ranges requested |
| Component Model with a borrowed host resource | Guest receives a handle; host answers queries against its own buffer | No, apart from extracted values and any explicit read-slice calls |
4. Keeping Instantiation Cheap
Per-request instantiation can dominate if it is not managed. Wasmtime provides tools for this:
-
Ahead-of-time compilation. Precompile components (
Engine::precompile_component) and load the serialized artifact at startup or when a tenant uploads a new filter, so request handling never pays for compilation. -
Pre-instantiation. Use a
Linkerto create anInstancePreonce per filter, so each request only does the final instantiation step. -
Pooling allocator. Wasmtime’s pooling instance allocator preallocates memory slots and reuses them, which avoids repeated
mmap-style setup costs per instance. -
Fresh
Storeper request. A newStoreper request keeps state, fuel, and memory isolated between requests. Reuse the engine, compiled components, and pooled slots, not request state.
Containing Untrusted Input and Untrusted Filters
An ingress edge faces two separate threats: malicious payloads from the outside, and buggy or hostile filter code from tenants. A Wasm sandbox helps with the second, and with the first only in combination with limits on the host.
1. Bounding CPU Time: Fuel and Epochs
Wasmtime has two complementary mechanisms for stopping runaway guest code:
-
Fuel. With
Config::consume_fuel(true), the compiled code counts as it executes. Most Wasm instructions consume one unit of fuel, while some, such asnop,drop,block, andloop, consume none. You set a budget withStore::set_fuel, and a store starts with zero fuel by default. When fuel runs out, the guest traps. Fuel is deterministic, which makes it good for reproducible limits, but the instrumentation adds overhead. -
Epoch interruption. With
Config::epoch_interruption(true), the engine keeps a global epoch counter that you increment from a timer thread viaEngine::increment_epoch. Compiled code checks the epoch at function entries and loop headers, and a store configured with an epoch deadline traps (or yields) when the deadline passes. Wasmtime’s documentation describes this as much cheaper than fuel, with up to 2–3x faster execution in some measurements, at the cost of being time-based rather than deterministic.
For a latency-sensitive gateway, epoch interruption is usually the better default for wall-clock timeouts. Fuel is useful where you need a strict, reproducible instruction budget. Because fuel counts roughly instructions and not time, choose budgets by benchmarking your real filters, not by assuming a fixed conversion to microseconds.
use wasmtime::{Config, Engine, Store};
let mut config = Config::new();
config.epoch_interruption(true);
config.consume_fuel(true);
let engine = Engine::new(&config)?;
// Per request:
let mut store = Store::new(&engine, host_state);
store.set_fuel(500_000)?; // instruction budget; tune by benchmarking
store.set_epoch_deadline(1); // trap after one epoch tick
store.epoch_deadline_trap();
// A background thread calls engine.increment_epoch() at your chosen interval.
What the gateway does after a trap is policy. Some deployments fail closed (reject the request), others fail open or route to a dead-letter queue. Pick the behavior deliberately and log it.
2. Capping Memory
Even though the body stays on the host, a filter can still allocate inside its own linear memory. Wasmtime’s ResourceLimiter interface lets the host cap memory growth, table sizes, and similar resources. StoreLimitsBuilder provides a ready-made implementation:
use wasmtime::{Store, StoreLimits, StoreLimitsBuilder};
struct HostState {
limits: StoreLimits,
// ... resource table, request buffer, etc.
}
let limits = StoreLimitsBuilder::new()
.memory_size(2 * 1024 * 1024) // 2 MiB (32 Wasm pages of 64 KiB)
.table_elements(1024)
.trap_on_grow_failure(true) // trap instead of returning a failed grow
.build();
let mut store = Store::new(&engine, HostState { limits });
store.limiter(|state| &mut state.limits);
Wasm linear memory is isolated from the host’s address space, and out-of-bounds accesses inside the guest trap instead of reading or writing host memory. This is a strong containment property, but it protects against bugs in the guest. It does not protect you from bugs in host functions you expose, which is why the host-side parser deserves the most scrutiny.
3. Handling Hostile JSON on the Host
A “billion laughs” attack is an XML entity-expansion attack and does not apply to JSON, but JSON has its own problems: extremely deep nesting, very large documents, and pathological inputs for the parser or for guest regular expressions. Defenses belong at the host:
- Enforce a maximum body size before reading or scanning.
- Use a parser with a configurable maximum nesting depth and set it conservatively.
- Return an error from
extract-json-stringon malformed or over-limit input, and let the filter reject the request. - Keep tenant-supplied regular expressions out of the guest where possible. If they must run, rely on fuel or epoch limits and an engine with linear-time matching guarantees.
4. Capability-Based Isolation
A component has no ambient authority. It can only call what its world imports and what the host chooses to link. In the world above, the filter’s only capabilities are the log function and the methods on the borrowed payload view. It cannot open sockets, read the filesystem, read environment variables, or query clocks unless you give it the corresponding WASI interfaces. That limits what a compromised or malicious filter can do: for example, a filter without network imports cannot be used for server-side request forgery.
Capabilities you do grant deserve thought. A log import that accepts arbitrary strings, for instance, needs rate limits and size limits so a tenant cannot flood your logging pipeline.
Architectural Takeaways
- Move routing logic out of gateway releases. Tenants or internal teams can ship filters as independently compiled components. With precompilation, you can load or replace a filter without rebuilding or redeploying the gateway binary. Version the WIT world, since it is your plugin API.
- Reduce copies and parsing where they aren’t needed. Borrowed host resources and host-side extraction mean a request that is rejected on a header never has its body copied into guest memory, and a request that needs one field costs one scan plus one small copy.
- Contain failures. Memory limits, fuel or epoch limits, and capability-based imports mean filter bugs show up as traps and rejected requests, not as crashes or lateral access in the gateway.
- Measure before you commit. The gains depend on payload size, how often requests are discarded, how efficiently the host exposes buffers, and how expensive instantiation is in your setup. Benchmark against your current filter path using real traffic shapes, and watch tail latency, allocation rates, and CPU per request.
Wasm filters are not free. You take on a plugin ABI, a toolchain, and a host-side attack surface. For a team running multi-tenant, user-supplied filter logic at the edge, though, the Component Model offers a typed, portable, sandboxed way to do it without handing every plugin a copy of every payload.
Further Reading
- WASI 0.3 release notes and status: https://wasi.dev/releases/wasi-p3
- Wasmtime 46.0.0 release notes: https://github.com/bytecodealliance/wasmtime/releases/tag/v46.0.0
- proxy-wasm ABI specification: https://github.com/proxy-wasm/spec
Originally published at https://instawebhook.com/blog/zero-copy-webhook-filtering-using-webassembly-wasm-and-the-component-model-at-th
Top comments (0)