envoy-guide
Module 7 · Going Deeper·10 min·intermediate

Lua filters

Mutate headers and short-circuit responses with a few lines of Lua.

When Lua is the right answer

Not every customisation needs WASM. Sometimes you just want to:

  • Copy :authority into x-forwarded-host.
  • Strip a sensitive header before access logs flush.
  • Short-circuit with a 401 if a header is missing.
  • Inject a request ID derived from the path.

For these, envoy.filters.http.lua embeds a LuaJIT 2.1 interpreter in the request path. No build step, no toolchain — paste script in YAML, restart, done.

Minimal envoy.yaml

YAML
http_filters:
- name: envoy.filters.http.lua
  typed_config:
    "@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.Lua
    default_source_code:
      inline_string: |
        function envoy_on_request(req)
          req:headers():add("x-trace-id", req:headers():get(":path"))
        end
        function envoy_on_response(resp)
          resp:headers():remove("server")
          resp:headers():add("x-edge", "envoy-lua")
        end
    source_codes:
      strip_pii:
        inline_string: |
          function envoy_on_response(h)
            h:headers():remove("x-internal-user-id")
          end
- name: envoy.filters.http.router
  typed_config:
    "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router

Per-route Lua

Reference a named source per route via typed_per_filter_config:

YAML
routes:
- match: { prefix: "/internal/" }
  route: { cluster: backend }
  typed_per_filter_config:
    envoy.filters.http.lua:
      "@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.LuaPerRoute
      name: strip_pii

/internal/* runs the strip_pii script; everything else runs the default_source_code.

Calling out from Lua (the only safe way)

Lua runs on the worker thread, in coroutines that yield. The single safe outbound call is handle:httpCall("cluster", headers, body, timeout_ms):

lua
function envoy_on_request(req)
  local headers, body = req:httpCall(
    "auth_cluster",
    { [":method"] = "GET", [":path"] = "/check", [":authority"] = "auth" },
    "",
    200
  )
  if headers[":status"] ~= "200" then
    req:respond({ [":status"] = "401" }, "no")
  end
end

The auth_cluster is a normal Envoy cluster you've defined elsewhere.

Three pitfalls

Blocking syscalls block the whole worker

Lua is single-threaded per worker. A blocking call — os.execute, io.open, anything from luasocket — blocks that worker's entire event loop, tanking latency for every concurrent request on it. Use handle:httpCall for any network access.

Body access requires opt-in

request_handle:body() returns nil unless you've enabled buffering on the listener (request_body_buffer_limit_bytes) AND the body is small enough. For streaming bodies use bodyChunks() — and accept that you'll see chunks, not the whole payload.

Filter order matters for metadata

When one filter writes dynamic metadata (streamInfo():dynamicMetadata():set("ns", "key", v)) and a later filter reads it, the namespace must match exactly AND the reader must run after the writer in the chain. Reverse the order and you'll get nil with no error.

Hands-on: header glue in 60 seconds

Hands-on · Inject and strip headers

Take any envoy.yaml that proxies to httpbin.org. Add the inline Lua filter from above. Restart and:

Shell
curl -is localhost:10000/headers | head -20

You should see x-edge: envoy-lua in the response, and no server header. Then:

Shell
curl -is localhost:10000/headers | grep x-trace-id

Confirms the request-side Lua ran and added the trace id (visible because httpbin echoes request headers).

Now add a typed_per_filter_config on one route pointing at strip_pii and verify other routes are unaffected.

Real-world example · Northwind Retail (legacy proxy migration)
Problem
Migrating off an Apache reverse proxy with 200 lines of mod_rewrite glue. Most of it is header math: copy CF-Connecting-IP to x-real-ip, redact session cookies from logs, derive x-tenant-id from the first path segment. Building a WASM plugin would be overkill and slow the migration.
Envoy solution
Translate the rules 1:1 into a single Lua source named edge_glue, attach via default_source_code, ship. Build pipeline goes from make + C compiler to git push. Three days instead of three months.

When to reach for Lua (vs WASM, vs ext_proc)

Use Lua when:

  • The script fits in 50 lines.
  • You don't need to call out except via httpCall.
  • You don't need shared state across requests.
  • A YAML-only deploy is more valuable than language ergonomics.

Otherwise reach for WASM (Lesson 22) or ext_proc (Lesson 24).

Quick check

Inside an Envoy Lua script, which call is SAFE to make against an external HTTP service?

Practical task
Finish the quick check and tick off the task to unlock.
Quick checkTasks 0/3