Skip to main content

dawdler-web-gateway

Module introduction​

The gateway module of dawdler, a lightweight reverse proxy gateway implemented on top of Servlet Filter and Vert.x. Using declarative routes in gateway.yml, requests are matched by rules and forwarded to upstream services; it supports HTTP/HTTPS and WebSocket/wss proxying and can integrate with the registry for service discovery and load balancing.

Main capabilities:

  • Ant-style path matching (**, *, ?), with declaration order as priority.
  • HTTP/HTTPS asynchronous reverse proxy, WebSocket/wss bidirectional pass-through.
  • lb:// protocol integration with the registry, selecting instances by load balancing strategy.
  • Path filters StripPrefix, RewritePath, SetPath, extensible via SPI.
  • Global filters GlobalFilter, which can rewrite request headers, the forwarding path, or short-circuit the response; suitable for cross-cutting concerns such as authentication, logging, and canary releases.
  • Route-level circuit breaker, reusing dawdler-circuit-breaker; when the circuit is open, a local fallback via fallbackUri is supported.

1. Add the dependency in pom​

<groupId>club.dawdler</groupId>
<artifactId>dawdler-web-gateway</artifactId>

2. Processing flow​

The entry point is GatewayFilter (registered via GatewayInitializer implementing the SPI DawdlerFilterInitializer, with URL pattern /*):

  1. After stripping contextPath, match routes by the Ant path predicate; if no route matches, pass through to the subsequent Filter chain.
  2. Validate request header values; any containing control characters or DEL is rejected directly with 400 -- malformed values let through to the proxy stage would be attributed to upstream faults and counted in circuit breaker statistics, and on the WS side could even be injected into the upstream handshake message; rejecting them uniformly at the entry point removes reliance on the sanitization differences between containers (logs record only the header name, not the value).
  3. Branch by the protocol of the target URI:
    • ws/wss/lb:ws/lb:wss: WebSocket proxy.
    • forward: dispatch to a local controller via RequestDispatcher.forward.
    • http/https/lb/lb:http/lb:https: HTTP asynchronous proxy.
    • Any other protocol prefix is treated as a configuration error; return 502 and log a WARN.
  4. lb:// obtains an instance from the registry instance cache (ServiceInstanceCache), selects one via load balancing, and forwards.

3. Route configuration​

The configuration resides in gateway.yml under the classpath; the top level is a routes list and an optional options section, and profile switching via dawdler.profiles.active is supported; if not present on the classpath, it falls back to the unified configuration center. If neither location has configuration, the gateway runs in a route-less form (only forward and pass-through); if configuration exists but fails to parse, startup fails and does not degrade silently.

FieldDescriptionExample
idUnique route identifieruser-facade
uriTarget address (protocol + address), see section 4lb://user-web-api
predicatesPredicate listPath=/api-user/**
filtersPath filter list, see 3.2StripPrefix=1
circuitBreakerRoute-level circuit breaker configuration, see 3.4

Predicates and filters support two equivalent forms:

# Shorthand: the name is before the first '=', the whole remainder is the arguments
filters:
- RewritePath=/api-user/(?<segment>.*), /${segment}

# Structured: name + args are looked up by name without splitting; values may contain any characters (including '=' and ',')
filters:
- name: RewritePath
args:
regexp: /api-user/(?<segment>.*)
replacement: /${segment}

When an argument value needs to contain = or , (e.g. a RewritePath regex using a range quantifier \d{1,3}), the structured form must be used -- the shorthand form truncates in the middle of the value, the rule does not take effect, and a WARN is logged.

3.1 Predicates​

PredicateDescriptionShorthand exampleStructured argument key
PathAnt-style path matchingPath=/api-user/**pattern

Match priority is declaration order; there is no most-specific-first: if /api/** is declared before /api/user/{id}, then /api/user/123 always hits the former. To make a narrower pattern effective, declare the specific pattern first. When building the route cache at startup, a WARN is logged for cases where "a broad pattern comes first and fully covers a later narrow pattern"; matching is indexed into buckets by the pattern's leading literal, and a request matches only patterns in buckets consistent with its prefix, avoiding a full scan under a large number of routes.

3.2 Path filters​

Applied in configuration order, with the output of one becoming the input of the next. Loaded via ServiceLoader and extensible on your own.

FilterShorthand argumentStructured argument keysDescription
StripPrefixNpartsStrip the first N segments of the path
RewritePathregex, replacementregexp + replacementRegex replacement; the replacement may reference capture groups ($1, ${name}); the shorthand splits at the first comma, so the regex cannot contain a comma
SetPathtemplatetemplateOverwrite the whole path by template; {N} references the N-th segment of the original path (1-based); an N beyond the segment count is replaced with an empty string

Effect comparison for the original path /api-user/v1/user/list:

StripPrefix=2 → /user/list
RewritePath=/api-user/(?<s>.*), /${s} → /v1/user/list
SetPath=/user/{4} → /user/list

RewritePath's regex comes from configuration, but the matched path is controlled by the client; to prevent catastrophic backtracking (e.g. (a*)*) there are two layers of protection: at compile time, nested quantifiers inside groups are rejected (can be disabled with -Ddawdler.gateway.rewrite.complexityCheck=false); at match time, the number of steps is bounded by path length. The same regex is compiled only once and cached; when the regex is invalid or a protection triggers, the rule does not take effect, the original path is passed through and a WARN is logged; the request does not fail.

SetPath example (original path /api-user/123/details, segments [1]=api-user [2]=123 [3]=details):

TemplateResult
/user/{2}/user/123
/{1}/{3}/api-user/details
/api/v1/{2}/{3}/api/v1/123/details
/{1}/{5}/api-user/ (the 5th segment does not exist, replaced with an empty string)
/fixed/fixed

Custom filter: implement the GatewayPathFilter interface (getName returns the name, apply(path, args) returns the rewritten path) and register the fully qualified class name in the jar's META-INF/services/club.dawdler.web.gateway.route.filter.GatewayPathFilter; see the built-in StripPrefixFilter, RewritePathFilter, SetPathFilter for reference.

Filter output (as well as the path rewritten by a global filter via setForwardPath) is validated again before local forwarding; if untrusted, 400 is returned directly instead of being handed to RequestDispatcher:

  • Contains backslashes, control characters, or .. backtracking above the root -- rejected
  • Contains ? or # (which the container would treat as query string/fragment) -- rejected
  • The first segment contains : (e.g. //host/path, javascript:..., which the container would parse as a network path with host/scheme) -- rejected
  • Repeated slashes are collapsed and ./.. are dot-segment normalized; forward:/app and /user/list combine into /app/user/list, so /app//user/list never appears, nor does a leading //

For forward://, only the path part of the uri is taken as the base path, and the base path itself is also normalized first; fallbackUri (forward:/path) goes through the same validation as custom filters.

3.3 Global filters (GlobalFilter)​

Unlike path filters, global filters apply to all routes; they execute after route matching and before request forwarding, and can modify request headers, the forwarding path, or short-circuit the response (return directly without forwarding). The design is similar to Spring Cloud Gateway's GlobalFilter.

Implementation classes placed in the scan package path configured by web-conf.xml are discovered automatically (they share the same web-conf.xml package scanning mechanism as Controllers and are injected by GatewayGlobalFilterInjector); no META-INF/services file is needed. Execution order is determined by ascending @Order; not calling chain.filter(exchange) terminates the chain.

@Order(0) // Multiple filters are allowed, ordering is supported, ascending order
public class AuthFilter implements GlobalFilter {
@Override
public void filter(GatewayExchange exchange, GatewayFilterChain chain) {
String token = exchange.getRequest().getHeader("Authorization");
if (token == null || token.isEmpty()) {
exchange.shortCircuit(401, "missing token");
return; // do not call chain.filter, terminate the chain, do not forward
}
exchange.setHeader("X-User-Id", resolveUser(token));
chain.filter(exchange); // continue with subsequent filters
}
}

Make sure the package-paths of web-conf.xml cover the package of this class (see dawdler-client-plug-web component scan package configuration).

Common methods of GatewayExchange:

MethodDescription
getRequest() / getResponse()The original Servlet request/response
getRoute() / getMatchedPath()The matched route / the path after stripping contextPath
getForwardPath() / setForwardPath(path)The forwarding path (with path filters applied); can be rewritten
addHeader / setHeader / removeHeaderAdd/remove/modify request headers; throws IllegalArgumentException when the value contains control characters
shortCircuit(status[, body])Short-circuit: write back the response and mark it as not forwarded

Header modifications take effect for all three forwarding kinds (HTTP/WebSocket/forward); what the downstream receives is the rewritten headers.

Built-in ForwardedHeadersFilter (highest @Order): first strip the origin-identifying headers self-reported by the client (Forwarded, X-Forwarded-* variants, X-Real-IP, etc.), then inject X-Forwarded-For, X-Forwarded-Proto, X-Forwarded-Host, X-Forwarded-Port; see 3.5.3 Forwarded headers for the handling.

3.4 Route-level circuit breaker (circuitBreaker)​

Declaring a circuitBreaker section under a route enables it; it reuses the time-sliding-window circuit breaker of dawdler-circuit-breaker: when the number of requests within the window reaches requestVolumeThreshold and the error rate is not lower than errorThresholdPercentage, the circuit opens; after sleeping for sleepWindowInMilliseconds one trial request is allowed through; on success the circuit closes, on failure it reopens. It applies to HTTP/HTTPS, the lb family, and WebSocket routes; forward:// does not go through the circuit breaker.

routes:
- id: user-facade
uri: lb://user-web-api
predicates:
- Path=/api-user/**
circuitBreaker:
granularity: route # optional, route (default) or interface
breakerKey: user-facade # optional, defaults to the route id
intervalInMs: 3000 # total statistics window length (milliseconds), must be divisible by windowsCount
windowsCount: 2 # number of window slices
sleepWindowInMilliseconds: 5000 # sleep duration after the circuit opens (milliseconds)
requestVolumeThreshold: 5 # minimum number of requests to trigger circuit break evaluation
errorThresholdPercentage: 0.4 # error rate threshold (0~1)
recordFailureStatus: [500, 502, 503, 504] # upstream status codes counted as failures, default all 5xx
openStatus: 503 # status code returned when the circuit is open
fallbackUri: forward:/fallback # optional, when the circuit is open forward to a local controller for fallback
FieldDefault valueDescription
enabledtrueWhether enabled
granularityrouteroute: one circuit breaker for the whole route; interface: independent circuit breaking per matched Path pattern, with key breakerKey#pattern, preventing a single large interface failure from also breaking other interfaces of the same route
breakerKeyRoute idCircuit breaker identifier; routes configured with the same key share circuit state (suitable for aggregation by upstream service dimension)
intervalInMs3000Total statistics window length (milliseconds); must be divisible by windowsCount, otherwise it is treated as no circuit breaker configured
windowsCount2Number of window slices
sleepWindowInMilliseconds5000Sleep duration after the circuit opens (milliseconds)
requestVolumeThreshold5Minimum number of requests within the window
errorThresholdPercentage0.4Error rate threshold (0~1)
recordFailureStatusAll 5xxUpstream status codes counted as failures; 4xx is a caller-side problem and is not counted
openStatus503Status code returned to the client when the circuit is open; the response header carries Retry-After
fallbackUriNoneFallback address in the form forward:/path, forwarded to a local controller via RequestDispatcher.forward; such a request does not go to the upstream and is not counted in circuit breaker statistics; not supported for WebSocket routes

Statistics criteria: connection failures, IO failures, timeouts, and upstream status codes matching recordFailureStatus are counted as failures; cases that do not reach the upstream, such as no available instance from service discovery, local rejection by the gateway (e.g. WS connection quota full), or the client disconnecting midway, are not counted. When granularity is interface, the measurement dimension is the pattern in the configuration rather than the raw URI (measuring by URI would grow unboundedly and none would reach the threshold); for low-traffic interfaces it is recommended to lower requestVolumeThreshold or enable it only for core interfaces.

3.4.1 Authentication​

The gateway does not build in any admission authentication; its responsibility remains pure forwarding. Authentication is performed uniformly on the gateway side through a custom GlobalFilter: choose one of two credentials (a backend jwt token or a distributed session); on validation failure call exchange.shortCircuit(401, ...) to short-circuit, and on success write the identity into a request header and then call chain.filter(exchange) to continue forwarding. The GlobalFilter skeleton below is unchanged; only the value retrieval and validation methods differ:

CredentialDependent moduleRetrievalValidation
JWT tokendawdler-client-plug-jwtAuthorization: Bearer <token> (or cookie/param per the tokenFrom of jwt.properties)JwtOperator.parse verifies the signature and checks exp/nbf/iss/aud
Distributed sessiondawdler-client-plug-sessionContainer HttpSession (sessionId comes from the cookie/header/param configured in identityConfig.properties)getSession(false) exists and the business attribute (e.g. userId) is non-empty

GlobalFilters for the two implementations:

// Option 1: JWT token
import club.dawdler.clientplug.web.jwt.JwtConfig;
import club.dawdler.clientplug.web.jwt.claim.JwtClaims;
import club.dawdler.clientplug.web.jwt.exception.JwtException;
import club.dawdler.clientplug.web.jwt.operator.JwtOperator;

@Order(0)
public class JwtAuthFilter implements GlobalFilter {
private final JwtOperator operator = JwtConfig.getInstance().getJwtOperator();

@Override
public void filter(GatewayExchange exchange, GatewayFilterChain chain) {
String token = exchange.getRequest().getHeader("Authorization");
if (token == null || !token.startsWith("Bearer ")) {
exchange.shortCircuit(401, "missing token");
return;
}
try {
JwtClaims claims = operator.parse(token.substring(7).trim());
exchange.setHeader("X-User-Id", claims.getSubject());
chain.filter(exchange);
} catch (JwtException e) {
exchange.shortCircuit(401, "invalid token");
}
}
}
// Option 2: distributed session
import jakarta.servlet.http.HttpSession;

@Order(0)
public class SessionAuthFilter implements GlobalFilter {
@Override
public void filter(GatewayExchange exchange, GatewayFilterChain chain) {
HttpSession session = exchange.getRequest().getSession(false);
Object userId = session == null ? null : session.getAttribute("userId");
if (userId == null) {
exchange.shortCircuit(401, "not logged in");
return;
}
exchange.setHeader("X-User-Id", userId.toString());
chain.filter(exchange);
}
}

(Both examples share the imports of club.dawdler.core.annotation.Order and club.dawdler.web.gateway.filter.GatewayExchange/GatewayFilterChain/GlobalFilter, and must be placed under a package covered by the package-paths of web-conf.xml.)

Implementation notes:

  • Enable only one option; enabling both at once becomes "allow if any credential passes", which contradicts the intent of choosing one of two.
  • JWT only performs signature verification and does not depend on the upstream JwtContext; the identity is injected via exchange.setHeader (e.g. X-User-Id) and sent to the upstream; validate length and character set according to business rules before injection; when a whitelist needs to be allowed (e.g. /login, /public/**), use exchange.getMatchedPath() for the check, consistent with the excludePaths semantics of the jwt module.
  • The session option must use getSession(false); the gateway side does not create sessions. DawdlerSessionFilter (@Order(-1)) is registered before the gateway's GatewayFilter (@Order(2)), so exchange.getRequest() can access the session directly. The gateway and the upstream must share the same Redis and session serialization configuration; the cookie's SameSite/Secure/domain/path must be consistent with the domains on which the application and the gateway are deployed; see identityConfig.properties description of dawdler-client-plug-session for details.
  • Authentication logic must not rely on client-self-reported headers such as X-Forwarded-*/X-Real-IP: these headers are rewritten by the built-in ForwardedHeadersFilter according to what the gateway observes, so the authentication filter may still see forged values.
  • When requests can bypass the gateway and connect directly to the upstream, the upstream services still need to validate on their own.

3.5 Runtime options (options)​

All fields have defaults tailored to the gateway scenario; omitting the options section or any individual field still works out of the box. Keys are camelCase and match the Java field names exactly.

3.5.1 Vert.x (options.vertx)​
FieldDefault valueDescription
eventLoopPoolSize0Number of event loop threads; 0 = Vert.x default (2 × CPU cores)
workerPoolSize0Worker thread pool size; 0 = Vert.x default (20); generally no adjustment needed
closeTimeoutSeconds30Timeout (seconds) for waiting for vertx.close() on Filter destroy; 0 = do not wait
3.5.2 HTTP/HTTPS proxy (options.httpProxy)​

Time fields are all in milliseconds (idleTimeout/keepAliveTimeout take effect with second precision and are rounded to seconds when passed to Vert.x).

FieldDefault valueDescription
asyncTimeout30000First response header timeout (milliseconds), counted from when the request body finishes sending; on timeout return 504. Since the timing starts after the request body finishes sending, slow large-file uploads are not constrained by this timeout; for the overall hard limit see requestTimeout
requestTimeout300000Overall request timeout (milliseconds), the upper limit of the total proxy duration of a single request counted from when the request enters the gateway; it is orthogonal and complementary to the per-stage idle timeouts: when the connection/request body/response body all have data flowing but the upstream as a whole progresses too slowly, it still aborts as a backstop, preventing requests from hanging indefinitely. If the response has not been committed, return 504; if committed, abort the upstream and truncate the response (the response header carries x-request-timeout-grace); increase it as needed for long polling/SSE/large-file downloads; 0 = no limit
requestTimeoutGrace10000Grace period (milliseconds) for a committed response after the overall timeout triggers, letting the client first read the x-request-timeout-grace header before wrapping up; 0 = keep no grace
uploadIdleTimeout30000Upload idle timeout (milliseconds); if the client body keeps having no data, abort and return 502; the timer restarts on each chunk read, so slow but continuous uploads do not trigger it
responseIdleTimeout60000Response body idle timeout (milliseconds), effective after the first response header arrives; the timer restarts on each chunk arrival; on timeout abort the upstream, return 504 if the response is not committed, stop further forwarding if it is committed, and record NO_RESPONSE
connectTimeout0Connection establishment timeout (milliseconds)
idleTimeout0Connection idle timeout (milliseconds); 0 = no timeout; takes effect with second precision
maxPoolSize200Maximum number of connections in the connection pool; this has the greatest impact on throughput. Each connection processes requests serially, so in-flight requests are limited to maxPoolSize; during load testing, increase it to the target concurrency level (e.g. 500~1000) and use keepAlive to reuse connections (Vert.x natively defaults to only 5)
keepAlivetrueWhether to enable Keep-Alive
keepAliveTimeout0Keep-Alive timeout (milliseconds), how long a connection may sit idle in the pool before being reclaimed; takes effect with second precision
trustAllfalseWhether HTTPS trusts all certificates; default uses the JDK truststore
requestBufferSize8192Buffer size (bytes) for streaming the request body
maxRequestBodyBytes0Upper limit of the request body size (bytes). Requests with Content-Length are pre-checked before forwarding; chunked (or no Content-Length) requests are checked cumulatively during forwarding; when exceeded, return 413 and record LOCAL_REJECTED (not counted in circuit breaker statistics); 0 = unlimited (rely on container-level protection)
useHttp2falseWhether to prefer connecting to the upstream over HTTP/2: http:// upstreams use h2c cleartext upgrade, https:// upstreams use ALPN negotiation; automatically fall back to HTTP/1.1 if the upstream does not support it. This only affects connections from the gateway to the upstream; the client-side protocol is determined by the container
http2MaxPoolSize0HTTP/2 multiplexed connection pool size (per address); 0 = Vert.x default. Effective only when useHttp2 is enabled; a single HTTP/2 connection can run multiple streams in parallel, so generally it does not need to be increased the way maxPoolSize is

Blocking Servlet I/O (request body reading/response body writing) runs on virtual threads created on demand, with completion callbacks dispatched back to the Vert.x event loop; there is no fixed thread limit and no tuning is required.

A response body timeout/upstream stream failure does not proactively refresh a not-yet-committed upstream response, so 504/502 can still be returned when only the upstream response headers have been received and the first body chunk has not been written out. Once the response is committed, the status code cannot be rewritten, and no error body is appended to pollute the original data. The gateway uses the standard Servlet API; stopping forwarding and completing the async request does not equal resetting the downstream connection or HTTP/2 stream; the container may end a chunked response normally, and the client cannot guarantee detection of the missing body solely by the original status code or the x-request-timeout-grace header. Scenarios requiring reliable detection of committed streaming failures should combine application-layer integrity checks or container-level abnormal termination support.

3.5.3 Forwarded headers (options.forwardedHeaders)​

Controls how the built-in ForwardedHeadersFilter handles origin-identifying headers. All origin-identifying headers (RFC 7239 Forwarded, X-Forwarded-* variants, X-Real-IP, etc.) can be forged freely by the client; the gateway always strips the self-reported values first and rewrites them according to its own observation before sending them to the upstream (this applies equally to both the HTTP and WebSocket paths).

FieldDefault valueDescription
xForwardedForModereplaceX-Forwarded-For handling mode: replace overwrites it to only the real peer address, discarding the self-reported chain; append keeps the existing chain and appends the peer address, and must be paired with trustedProxies. An unknown value logs a warning and falls back to replace
trustedProxiesEmptyList of trusted proxy addresses/CIDRs (e.g. 10.0.0.0/8, supporting IPv4/IPv6). Under append, the peer's XFF chain is kept only if the peer matches a trusted range; otherwise it is treated as forged and overwritten to only the peer address

The basis for judgment is the real peer address at the TCP layer (getRemoteAddr(), determined by the three-way handshake, which cannot be forged):

  • Gateway exposed directly to the public network: use the default replace, so XFF is always the real peer address and cannot be forged.
  • A self-owned proxy such as Nginx/LB in front of the gateway: use append + trustedProxies configured with the proxy addresses or intranet ranges; requests from trusted proxies keep the full chain, while direct-connection requests are overwritten.
  • append without trustedProxies: the self-reported chain is always kept; when listening on a public address, a WARN is logged at startup that it can be forged.

X-Forwarded-Proto / X-Forwarded-Host / X-Forwarded-Port are not affected by the mode and are always overwritten with the values observed by the gateway.

3.5.4 WebSocket/wss proxy (options.webSocketProxy)​

Time fields are all in milliseconds.

FieldDefault valueDescription
connectTimeout12000Upstream TCP connection wait timeout
handshakeTimeout15000Upstream handshake wait timeout
netConnectTimeout10000NetClient connection establishment timeout
maxHeaderSize65536Maximum bytes of the handshake response headers; exceeding it is judged as a handshake failure
trustAllfalseWhether wss trusts all certificates; default uses the JDK truststore
readBufferSize8192Buffer size (bytes) for reading client → upstream
maxWsConnections10000Gateway-level maximum number of concurrent WS connections; when the limit is reached, new handshakes return 503 directly without dialing the upstream, and already-upgraded connections are unaffected; 0 = unlimited (when exposed directly to the public network, set it according to capacity)
idleTimeout300000Bridging idle timeout after upgrade (milliseconds); when no data flows in either direction (including ping/heartbeat) for that duration, the connection is closed; bytes in any direction reset the timer; 0 = no timeout
toClientHighWaterMarkBytes262144Buffering high-water mark (bytes) for the upstream → client direction; it still serves as the backpressure pause threshold: reaching it pauses reading from the upstream socket, and it resumes after dropping to half; the per-connection hard byte budget before enqueueing is max(1, toClientHighWaterMarkBytes) * 2L (default 512 KiB), including Buffers in the queue and Buffers being written out to the client but not yet completed

During the handshake phase the servlet thread is released via AsyncContext, and the upstream connection and 101 response are awaited on a virtual thread; during the bridging phase, each upgraded connection is passed through in both directions by two long-lived virtual threads (reader + writer), with no fixed thread limit, and the number of concurrent connections is bounded by maxWsConnections and memory. Both directions have backpressure control, so a slow peer cannot make the gateway buffer the entire stream; upgraded connections are guarded by the idleTimeout idle watchdog, and zombie connections that stay silent in both directions are closed.

In the upstream → client direction, the hard budget is checked before each TCP chunk is enqueued; if including the current chunk would exceed the budget, the whole current chunk is rejected, the connection is closed, and the queue is cleaned up, rather than silently dropping bytes and continuing to forward; if a single TCP chunk itself is larger than the budget, the connection is also closed. This is a TCP pass-through buffering budget, not a WS frame/message length limit, nor a precise heap memory limit: write-out copies, objects, and socket/protocol-stack overhead are not counted toward this budget.

3.5.5 Upstream response header copy-back (options.responseHeaders)​

Controls the copy-back of upstream response headers to the client, shared by both the HTTP and WebSocket proxy paths (non-101 responses). Hop-by-hop headers (Connection/Transfer-Encoding, etc.) are always stripped regardless of this configuration; Content-Length is passed through as-is and not subject to the list -- with a declared length the client can reliably detect a mid-stream upstream disconnection, whereas switching to chunked ending would turn it into a silently corrupted file.

FieldDefault valueDescription
modedeny-listdeny-list passes through all response headers except those in blocked (the normal behavior of a reverse proxy); allow-list passes through only the headers listed in allowed. Any other value fails startup
blockedEmptyResponse header names forbidden from being passed through under deny-list (e.g. X-Powered-By, Server), case-insensitive
allowedEmptyResponse header names allowed to be passed through under allow-list; being empty in this mode fails startup

When the upstream is your own business service, use the default deny-list (Set-Cookie etc. are delivered normally); when the upstream is not fully trusted (third party, multi-tenant), switch to allow-list and list the headers required by the business (at least Content-Type, plus Set-Cookie etc. as needed) in allowed, preventing a compromised upstream from delivering headers such as Set-Cookie to the gateway's domain for session fixation.

3.5.6 Load balancing (options.loadBalance)​
FieldDefault valueDescription
loadBalancerandomThe name of the strategy for selecting instances for lb://, corresponding to the LoadBalance SPI of dawdler-discovery-center-core; random and roundRobin (cursor isolated by service name) are built in; an unknown value logs a warning and falls back to random

Services of lb:// routes should be subscribed by the gateway registry plugin (see Service discovery integration); when a newly added route has not yet completed subscription / failed subscription / the plugin is not deployed, that service is treated as "not subscribed": each resolution queries the registry directly, and DiscoveryCenter.getInstances itself decides whether to use the local cached snapshot.

3.5.7 Observability (options.observability)​

Two independent switches: the access log is on by default, and metrics are off by default (consistent with the baseline of dawdler.server/client/web metrics being off by default).

FieldDefault valueDescription
accessLogEnabledtrueAccess log, logger name dawdler.gateway.access, one line per proxy terminal state: route/method/path/status/durationMs/remote; the deployment side can configure a separate appender for this logger to persist/collect
metricsEnabledfalseRegister the gateway metrics MBean (domain club.dawdler.web.gateway, type GatewayStatus), exposing total requests / status code distribution (2xx~5xx) / local rejections / latency (avg/P50/P95/P99) / summaries merged by route matching pattern; with jmx_prometheus_javaagent they can be mapped to Prometheus metrics without introducing additional client dependencies; when disabled, no MBean is registered and the proxy path has zero overhead

Metric labels use the route's matching pattern (e.g. /api/**) rather than the raw request path, preventing high-cardinality paths from exhausting memory; after the number of route patterns exceeds 1000, new patterns are all merged into overflow. Percentiles come from a ring histogram of the most recent 1024 requests (adjustable via dawdler.gateway.metrics.latency.window), and samples outside the window do not participate in the calculation.

Deployment constraints: the route cache / circuit breaker registry / global filter registry are all class-loader-level static state; GatewayFilter.destroy() only cleans up resources held by this instance and no longer resets this static state; when multiple gateway instances exist under the same classloader (e.g. multiple webapps in a single JVM sharing the gateway dependency), the instances share the same static state, and destroying one instance does not bring down the other live instances. When fully isolated static state is required, the gateway dependency should be placed inside each webapp's own classloader (i.e. each instance carries its own copy of the gateway dependency).

3.5.8 Configuration example​
options:
loadBalance: random
httpProxy:
maxPoolSize: 500
connectTimeout: 5000
idleTimeout: 60000
responseIdleTimeout: 120000
maxRequestBodyBytes: 10485760
useHttp2: true
webSocketProxy:
maxWsConnections: 10000
idleTimeout: 300000
forwardedHeaders:
xForwardedForMode: append
trustedProxies:
- 10.0.0.0/8
observability:
accessLogEnabled: true
metricsEnabled: true
# Switch to allow-list when the upstream is not fully trusted:
# responseHeaders:
# mode: allow-list
# allowed:
# - Content-Type
# - Cache-Control

4. Supported protocols​

The protocol prefix of the route uri determines the forwarding method:

ProtocolDescriptionExample
lb://Load balancing, routed to a microservice via service discovery (http by default)lb://user-web-api
lb:ws:// / lb:wss://Load balancing + WebSocketlb:ws://websocket-service
lb:http:// / lb:https://Load balancing + specified HTTP protocollb:https://secure-http-service
http:// / https://Static external/internal HTTP(S) addresshttp://httpbin.org
ws:// / wss://Static WebSocket endpointws://echo.websocket.org
forward://Dispatch to a local controller via RequestDispatcher.forwardforward:///local/api

An unknown protocol prefix (e.g. grpc://) is treated as a configuration error: when hit, return 502 directly and log a WARN, without passing through to the local application.

5. Configuration example​

routes:
# Load balancing + circuit breaker (see 3.4 for details)
- id: user-facade
uri: lb://user-web-api
predicates:
- Path=/api-user/**
filters:
- StripPrefix=1
circuitBreaker:
errorThresholdPercentage: 0.4
fallbackUri: forward:/fallback

# WebSocket load balancing
- id: websocket-lb
uri: lb:ws://websocket-service
predicates:
- Path=/ws-lb/**
filters:
- StripPrefix=1

# RewritePath shorthand
- id: rewrite-demo
uri: lb://user-web-api
predicates:
- Path=/api-user/**
filters:
- RewritePath=/api-user/(?<segment>.*), /${segment}

# RewritePath structured: when the regex contains ',', the shorthand truncates, so values must be looked up by name
- id: rewrite-named-demo
uri: lb://user-web-api
predicates:
- Path=/api-user/**
filters:
- name: RewritePath
args:
regexp: /api-user/v\d{1,2}/
replacement: /v/

# SetPath template restructuring, {2} references the 2nd segment of the original path
- id: setpath-demo
uri: lb://user-web-api
predicates:
- Path=/api-user/**
filters:
- SetPath=/user/{2}

# Local forwarding, dispatched to beans/controllers within the current Web application
- id: local-forward
uri: forward:///local
predicates:
- Path=/api-local/**
filters:
- StripPrefix=1

forward:// does not go through the reverse proxy; instead it dispatches to a local controller within the current Web application (consistent with dawdler's own AnnotationUrlHandler forwarding). Path resolution: apply the Filter rewrite first; when the URI carries its own path (e.g. forward:///local), it is used as a prefix and concatenated; when it does not, the rewritten path is used directly; the query string is preserved automatically by the container.

# uri: forward:///local, filters: [StripPrefix=1]
/api-local/user/list -> /local/user/list

# uri: forward:///, filters: [StripPrefix=1]
/api-local/user/list -> /user/list

6. Service discovery integration​

The lb:// protocol relies on the registry to provide instance addresses; the gateway itself does not include a registry implementation, so the corresponding registry gateway plugin must be introduced, which maintains the instance cache (additions/removals); at request time the gateway selects an instance to forward to according to the strategy specified by options.loadBalance.

Using Consul as the registry:

<groupId>club.dawdler</groupId>
<artifactId>dawdler-gateway-discovery-center-consul</artifactId>

See dawdler-gateway-discovery-center-consul.

Using Zookeeper as the registry:

<groupId>club.dawdler</groupId>
<artifactId>dawdler-gateway-discovery-center-zookeeper</artifactId>

See dawdler-gateway-discovery-center-zookeeper.

7. Performance tuning​

Throughput is mainly constrained by httpProxy.maxPoolSize: HTTP/1.1 processes requests serially on each connection, and in-flight requests are limited to maxPoolSize (a rule of thumb: throughput ≈ maxPoolSize / single-request round-trip latency). During load testing/high concurrency, first raise it to the target concurrency level to verify that throughput recovers, then gradually approach the level of connecting directly to the upstream. With a large number of WebSocket connections, the total buffering byte budget for the upstream → client direction is concurrent connections × max(1, toClientHighWaterMarkBytes) * 2L (default 512 KiB per connection), covering only queued Buffers and Buffers being written out to the client but not yet completed; it is not a worst-case heap usage estimate: write-out copies, objects, socket/protocol-stack overheads, etc. are not counted, so extra resources should be reserved. For memory-sensitive scenarios the water mark can be lowered; the number of concurrent WS connections is capped by webSocketProxy.maxWsConnections, and connections that stay silent in both directions after upgrade are reclaimed by webSocketProxy.idleTimeout.

Blocking Servlet I/O all runs on virtual threads, created on demand with no fixed upper limit, and requires no tuning; for slow clients that "hold the connection but send/receive no data", rely on container-level timeouts (e.g. Tomcat's connectionTimeout) to reclaim the virtual threads and memory corresponding to dead connections.

8. Distributed tracing (pinpoint)​

dawdler-pinpoint-plug provides gateway tracing: the gateway entry records a DAWDLER_GATEWAY server span, and the forwarding from the gateway to the upstream records a DAWDLER_GATEWAY_PROXY proxy span; both the HTTP proxy and the WebSocket proxy paths are covered, and the ServerMap shows client → DAWDLER_GATEWAY → upstream service. Whether or not the upstream service is dawdler, the trace can continue as long as the pinpoint agent is attached; the plugin strips the client-forged Pinpoint-* request headers, so external requests cannot forge traces. Gateway-side switch profiler.dawdler.gateway.enable (default true); see the plugin README for deployment.