Docs/Web & UI/Fast HTTP engine

Fast HTTP engine

Run Fletch on httpengine with WithFastServer for pipelined HTTP/1.1, epoll/kqueue event loops, HTTP/2, non-blocking inline routes, and opt-in prefork.

github.com/fletchhq/fletch/httpengine

fletch/httpenginepkg.go.dev

Updated 2026-12-06 fletch docs show fast-server 7 min read

On this page

github.com/fletchhq/fletch/httpengine is a standalone, pure-Go HTTP/1.1 and HTTP/2 server that you can enable in a Fletch app with fletch.WithFastServer or run on its own with httpengine.New. It builds with CGO_ENABLED=0 and has zero Fletch dependencies.

Introduction

Go's standard net/http server is the right default for most web applications, and Fletch uses it unless you opt in. When your workload is dominated by high-throughput HTTP/1.1 JSON APIs or heavy connection concurrency, allocating an *http.Request and scheduling a goroutine per request becomes a measurable cost.

httpengine removes that overhead on eligible routes. It parses HTTP/1.1 requests directly from the connection buffer without allocating, writes pipelined response batches in one syscall, and runs epoll (Linux) or kqueue (macOS) event loops for fast-path connections. Every request that needs standard net/http features—such as Live views, WebSockets, SSE, HTTP/2, streaming bodies, or custom net/http middleware—moves cleanly to the net/http adapter.

For measured throughput and latency numbers across workloads, see Stability & benchmarks.

Configuration

Enable httpengine on a Fletch app by passing fletch.WithFastServer to fletch.New. Any httpengine.Option values you pass configure the underlying server.

package main

import (
	"time"

	"github.com/fletchhq/fletch"
	"github.com/fletchhq/fletch/httpengine"
)

func main() {
	app := fletch.New(
		fletch.WithFastServer(
			httpengine.WithServerName("acme-api"),
			httpengine.WithMaxBodyBytes(10<<20),
			httpengine.WithWriteTimeout(15*time.Second),
		),
		fletch.WithRoutes(routes),
	)
	fletch.Run(app)
}

When WithFastServer is enabled, fletch.Run, ListenAndServe, and Serve all run on httpengine instead of net/http. Fletch applies httpengine.WithReadHeaderTimeout(10 * time.Second) by default; any timeout option you pass to WithFastServer overrides it.

Core concepts

Choosing between httpengine and net/http

Keep the default net/http server when:

  • Most requests spend their time in Postgres queries, external HTTP calls, or server-rendered HTML templates.
  • Your traffic is primarily HTTP/2 (HTTP/2 requests always take the http.Handler path in httpengine).
  • You run an obs observability middleware on every request (an app whose observability provider wraps HTTP handlers serves through the net/http path rather than ServeFast).

Switch to fletch.WithFastServer when:

  • You serve high-concurrency HTTP/1.1 JSON or plaintext APIs where serialization and dispatch overhead matter.
  • You want strict HTTP/1.1 request-smuggling rejection and batched pipelined writes without leaving Go's http.Handler ecosystem for the rest of your app.

How the fast path and fallback work

httpengine exposes two entry points on every connection:

  1. The fast path (httpengine.FastHandler). Each HTTP/1.x request is offered first to ServeFast(x *httpengine.Context) bool. On a Fletch app, (*App).ServeFast handles typed routes (router.GetJSON, router.GetText, router.GetHTML, and the other typed helpers) whose only middleware is Fletch's default request ID, panic recovery, and lazy request context.
  2. The net/http adapter (http.Handler). If ServeFast returns false, httpengine builds an *http.Request and hands the request to the standard http.Handler with full http.Flusher, http.Hijacker, and http.ResponseController support.

The following requests always take the net/http adapter automatically:

  • Live views, WebSockets, and Server-Sent Events (SSE).
  • Form sessions, CSRF middleware, mounts, and /healthz or /readyz probes.
  • Routes wrapped in custom Use middleware (unless registered with router.UseFastBypass for middleware whose effect the fast path reproduces).
  • Routers configured with router.WithForwarded.
  • HTTP/2 requests (over TLS via ALPN h2, or cleartext h2c).

One behavioral difference to keep in mind: on the fast path, the request context is created lazily when a handler calls c.Context() and ends when the handler returns. Client disconnect cancelation starts only if the handler accesses that context (or runs on the net/http adapter).

Inline routes (router.Inline())

By default, an httpengine event loop hands parsed request batches to a pooled worker goroutine so a slow handler cannot stall other connections on the same loop. For tiny, purely in-memory routes (such as cached JSON, static plaintext, or health checks that do no I/O), you may skip the goroutine handoff by registering them on r.Inline().

func routes(r *router.Router) {
	// Non-blocking routes run directly on the event loop
	fast := r.Inline()
	router.GetText(fast, "/ping", pingHandler)
	router.GetJSON(fast, "/v1/status", statusHandler)

	// Database and I/O routes stay on the default pooled handoff path
	router.GetJSON(r, "/v1/orders/{id}", getOrderHandler)
}

Inline() returns a child *router.Router whose setting carries into nested Group and Host routers. When an app has at least one inline route, fletch.WithFastServer registers the app as an httpengine.InlineHandler, and the event loop asks (*App).InlineFast(x) for each request before deciding whether to run it inline or hand the batch to a worker goroutine.

If every fast-path route in a dedicated microservice is non-blocking, you may also pass httpengine.WithInlineDispatch(true) to run all fast-path requests inline without calling InlineFast.

Common tasks

Wiring a Fletch app into a custom httpengine.Server

*fletch.App implements both httpengine.FastHandler (via ServeFast) and httpengine.InlineHandler (via InlineFast). If you manage your own listener, TLS configuration, or graceful shutdown loop, construct httpengine.New directly and pass the app as both the standard handler and the fast handler:

srv := httpengine.New(
	httpengine.WithHandler(app.Handler()),
	httpengine.WithFastHandler(app),
	httpengine.WithReadHeaderTimeout(10*time.Second),
	httpengine.WithServerName("acme-api"),
)

ln, err := httpengine.Listen("tcp", ":8080")
if err != nil {
	log.Fatal(err)
}

if err := srv.Serve(ln); err != nil && !errors.Is(err, httpengine.ErrServerClosed) {
	log.Fatal(err)
}

Because *fletch.App satisfies httpengine.InlineHandler, passing app to WithFastHandler enables both fast-path dispatch and per-route inline checks automatically. Call srv.RegisterOnShutdown(...) to notify streaming or hijacked connections before calling srv.Shutdown(ctx).

Using httpengine standalone (without Fletch)

Because httpengine has no Fletch imports, you can use it in any Go service with standard http.Handler routes and an optional custom FastHandler:

srv := httpengine.New(
	httpengine.WithHandler(mux),
	httpengine.WithFastHandler(httpengine.FastHandlerFunc(func(x *httpengine.Context) bool {
		if x.Method() == "GET" && x.Path() == "/health" {
			x.SetContentType("text/plain; charset=utf-8")
			x.SetStatus(http.StatusOK)
			x.WriteString("ok\n")
			return true
		}
		return false
	})),
)

log.Fatal(srv.ListenAndServe(":8080"))

Returning false from ServeFast without reading or writing passes the request straight to mux.

Pairing with generated JSON serializers

For hot JSON endpoints on WithFastServer, add a //fletch:json comment above your response struct or slice type and run fletch gen (or fletch dev). Fletch generates an AppendJSON([]byte) []byte method implementing router.JSONAppender that writes directly into the connection buffer, avoiding reflection while keeping byte-identical output to encoding/json.

//fletch:json
type StatusResponse struct {
	OK      bool   `json:"ok"`
	Version string `json:"version"`
}

Advanced usage

Multi-process prefork on Linux

For CPU-bound HTTP/1.1 services on Linux, httpengine.Prefork(ctx, n) spawns n worker processes with GOMAXPROCS=1 that share the same port via SO_REUSEPORT. Call it at the top of main before opening listeners, caches, or database pools:

ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()

worker, err := httpengine.Prefork(ctx, runtime.NumCPU())
if err != nil {
	log.Fatal(err)
}
if !worker {
	return
}

// Start the app inside each worker process.

Each worker runs with HTTPENGINE_PREFORK_WORKER set to its worker number and receives SIGTERM when ctx cancels or if the parent exits. On non-Linux systems (or when n < 2), Prefork returns worker = true immediately and runs in a single process.

Prefork is opt-in because worker processes share no memory: each worker maintains its own in-process caches, Live sessions, and database connection pools. For database-heavy workloads, a single process with a shared connection pool is usually faster and simpler to tune.

Reference

Fletch and router integration

Symbol Package Role
WithFastServer(opts ...httpengine.Option) Option fletch Serves the app with httpengine instead of net/http.
(*App).ServeFast(x *httpengine.Context) bool fletch Implements httpengine.FastHandler for eligible typed routes.
(*App).InlineFast(x *httpengine.Context) bool fletch Implements httpengine.InlineHandler for routes registered on r.Inline().
(*Router).Inline() *router.Router router Marks non-blocking typed routes to run directly on the event loop.
UseFastBypass router Registers middleware whose effect the fast path reproduces without forcing fallback.

httpengine server API

Symbol Role
New(opts ...Option) *Server Constructs a configured HTTP/1.1 and HTTP/2 server.
Listen(network, addr string) (net.Listener, error) Opens a TCP listener configured for httpengine (including SO_REUSEPORT where supported).
(*Server).ListenAndServe(addr string) error Listens on addr and serves until Shutdown or Close.
(*Server).Serve(ln net.Listener) error Accepts and serves connections on ln; returns ErrServerClosed after shutdown.
(*Server).Shutdown(ctx context.Context) error Stops accepting, closes idle connections, sends HTTP/2 GOAWAY, and drains active requests.
(*Server).Close() error Immediately closes listeners and tracked connections.
(*Server).RegisterOnShutdown(f func()) Registers a callback invoked when Shutdown starts.
Prefork(ctx context.Context, n int) (bool, error) Re-execs n GOMAXPROCS=1 workers sharing a port via SO_REUSEPORT on Linux.
ErrServerClosed Alias for http.ErrServerClosed.

httpengine options

Option Default Behavior
WithHandler(h http.Handler) http.NotFoundHandler() Standard net/http fallback handler.
WithFastHandler(h FastHandler) none Fast-path handler offered every HTTP/1.x request first.
WithInlineDispatch(on bool) false Runs all fast-path requests inline on the event loop without asking InlineFast.
WithServerName(name string) none Sets the Server response header when a handler does not set one.
WithMaxHeaderBytes(n int) 1 MiB Caps request line plus header fields.
WithMaxBodyBytes(n int64) 0 (unlimited) Caps request body size; oversized declared bodies receive 413 before running a handler.
WithReadTimeout(d time.Duration) none Bounds reading one full request (headers and body).
WithReadHeaderTimeout(d time.Duration) read timeout (10s via WithFastServer) Bounds reading request headers from the first byte.
WithWriteTimeout(d time.Duration) none Bounds writing each response.