--- title: Configuration description: Complete reference for every MockServer configuration property, including memory limits, log level, TLS options, and environment-variable mappings. layout: page pageOrder: 1 section: 'Operations' subsection: true sitemap: priority: 0.8 changefreq: 'monthly' lastmod: 2019-11-10T08:00:00+01:00 ---
Copy-paste one of these blocks as a starting point. All values can be overridden by system properties or environment variables at runtime.
Low memory footprint, verbose logs, CORS enabled for browser-based testing:
# mockserver.properties — local dev
mockserver.devMode=true
mockserver.logLevel=DEBUG
mockserver.enableCORSForAPI=true
mockserver.enableCORSForAllResponses=true
Or with Docker:
docker run -d --rm -p 1080:1080 \
-e MOCKSERVER_DEV_MODE=true \
-e MOCKSERVER_LOG_LEVEL=DEBUG \
-e MOCKSERVER_ENABLE_CORS_FOR_API=true \
-e MOCKSERVER_ENABLE_CORS_FOR_ALL_RESPONSES=true \
mockserver/mockserver
Cap memory so multiple MockServer instances can run on the same CI node, load expectations from a JSON file, and reduce log noise:
# mockserver.properties — CI
mockserver.logLevel=WARN
mockserver.maxExpectations=1024
mockserver.maxLogEntries=4096
mockserver.initializationJsonPath=/ci/expectations.json
Higher limits, metrics enabled, CORS off, TLS enforced (supply your own certificates):
# mockserver.properties — production
mockserver.logLevel=INFO
mockserver.maxExpectations=16384
mockserver.maxLogEntries=65536
mockserver.metricsEnabled=true
mockserver.enableCORSForAPI=false
mockserver.enableCORSForAllResponses=false
| Property | Env variable | Default | Why you'd change it |
|---|---|---|---|
| devMode | MOCKSERVER_DEV_MODE | false | Enable on your laptop to cap memory (1k expectations / 1k log entries) and avoid wasted heap |
| logLevel | MOCKSERVER_LOG_LEVEL | INFO | Set to DEBUG while debugging a mismatch; set to WARN in CI to reduce noise |
| maxExpectations | MOCKSERVER_MAX_EXPECTATIONS | heap-based (up to 15,000) | Lower to reduce memory on constrained hosts; use a power-of-2 to avoid wasted ring-buffer slots |
| maxLogEntries | MOCKSERVER_MAX_LOG_ENTRIES | heap-based (up to 100,000) | How many log entries are retained in memory before the oldest are overwritten. Lower for high-throughput or large-body workloads; each HTTP request generates 2–3 log entries |
| ringBufferSize | MOCKSERVER_RING_BUFFER_SIZE | min(maxLogEntries, 16,384) | Size of the in-flight log event buffer (separate from maxLogEntries retention). You rarely need to change this — raise it only if you see dropped log events under sustained extreme load; lower it to save memory on a high-retention, low-throughput workload. Rounded up to a power of 2 |
| maxSocketTimeout | MOCKSERVER_MAX_SOCKET_TIMEOUT | 20,000 ms | Maximum time to wait for the first response byte when forwarding/proxying. Increase when your system-under-test is slow to start responding — e.g. a reasoning LLM backend can take minutes to emit its first token, so a low value 502s a healthy call; decrease to fail fast in unit tests. Also accepted as maxSocketTimeoutInMillis / MOCKSERVER_MAX_SOCKET_TIMEOUT_IN_MILLIS (the same setting under the name used by the Java API and the configuration JSON) |
| enableCORSForAPI | MOCKSERVER_ENABLE_CORS_FOR_API | false | Enable when calling the MockServer REST API from a browser-based test |
| enableCORSForAllResponses | MOCKSERVER_ENABLE_CORS_FOR_ALL_RESPONSES | false | Enable to allow browsers to receive mock responses from a different origin |
| initializationJsonPath | MOCKSERVER_INITIALIZATION_JSON_PATH | (none) | Load a set of expectations from a JSON file when MockServer starts — useful for shared or CI setups |
| metricsEnabled | MOCKSERVER_METRICS_ENABLED | false | Enable to expose Prometheus metrics at /mockserver/metrics |
| proxyRemotePort + proxyRemoteHost | MOCKSERVER_PROXY_REMOTE_PORT | (none) | Forward unmatched requests to a real upstream server, turning MockServer into a selective proxy |
Filter the full list of configuration properties. Click a property name to jump to its detail — the accordion expands automatically.
Note: configuration properties loaded from property files and environment variables are read once at startup and cached. Changes to property files or environment variables after MockServer has started will not take effect. To change configuration at runtime, use the REST API (PUT /mockserver/configuration) or programmatic ConfigurationProperties method calls. System property changes via ConfigurationProperties static methods are read dynamically for properties that support runtime changes (e.g., logLevel).
See also: Chaos Testing & Fault Injection for injecting errors, latency, and outages into mocked and proxied responses using declarative chaos profiles.
Properties can be set by:
@MockServerTest annotation (per-instance Configuration object)Each level overrides the levels below it. For example, a system property overrides the same key in a property file, which in turn overrides an environment variable.
When using @MockServerTest, properties prefixed with mockserver. (e.g. mockserver.initializationClass=...) are applied to the per-instance Configuration object, not to global system properties. This makes them safe for parallel test execution.
Some properties need to be set before MockServer starts because they are only read at start-up, for example, nioEventLoopThreadCount.
Other values are read continuously and so can be changed at any time, for example, logLevel.
There are two ways to set properties programmatically, as follows:
The property file defaults to filename mockserver.properties in the current working directory of MockServer.
This location of the property file can be changed by setting the mockserver.propertyFile system property or MOCKSERVER_PROPERTY_FILE environment property, for example:
-Dmockserver.propertyFile=/config/mockserver.properties
A full example / template properties file can be found in github
An limited properties file example is, as follows:
###############################
# MockServer & Proxy Settings #
###############################
# Socket & Port Settings
# socket timeout in milliseconds (default 20000)
mockserver.maxSocketTimeout=20000
# Certificate Generation
# dynamically generated CA key pair (if they don't already exist in specified directory)
mockserver.dynamicallyCreateCertificateAuthorityCertificate=true
# save dynamically generated CA key pair in working directory
mockserver.directoryToSaveDynamicSSLCertificate=.
# certificate domain name (default "localhost")
mockserver.sslCertificateDomainName=localhost
# comma separated list of ip addresses for Subject Alternative Name domain names (default empty list)
mockserver.sslSubjectAlternativeNameDomains=www.example.com,www.another.com
# comma separated list of ip addresses for Subject Alternative Name ips (default empty list)
mockserver.sslSubjectAlternativeNameIps=127.0.0.1
# maximum number of dynamically-discovered SANs the auto-generated certificate will accumulate (default 100)
mockserver.maxSubjectAlternativeNames=100
# number of days the auto-generated leaf certificate is valid for (default 397)
mockserver.sslCertificateLeafValidityInDays=397
# CORS (both default to false; set to true to enable)
# enable CORS for MockServer REST API
mockserver.enableCORSForAPI=true
# enable CORS for all responses
mockserver.enableCORSForAllResponses=true
MockServer also supports configuration via a JSON file. To use a JSON configuration file, set the mockserver.propertyFile system property or MOCKSERVER_PROPERTY_FILE environment variable to a file path ending with .json, for example:
-Dmockserver.propertyFile=/config/mockserver.json
The JSON format uses camelCase property names without the mockserver. prefix. An example JSON configuration file:
{
"logLevel": "INFO",
"maxSocketTimeout": 120000,
"dynamicallyCreateCertificateAuthorityCertificate": true,
"directoryToSaveDynamicSSLCertificate": ".",
"sslCertificateDomainName": "localhost",
"sslSubjectAlternativeNameDomains": ["www.example.com", "www.another.com"],
"sslSubjectAlternativeNameIps": ["127.0.0.1"],
"maxSubjectAlternativeNames": 100,
"sslCertificateLeafValidityInDays": 397,
"enableCORSForAPI": true,
"enableCORSForAllResponses": true
}
Note: enableCORSForAPI and enableCORSForAllResponses both default to false. The examples above set them to true to illustrate enabling CORS.
The JSON property names are the camelCase equivalents of the mockserver.* property names listed below, with the mockserver. prefix removed. For example, mockserver.maxExpectations becomes maxExpectations in JSON. The complete list of supported JSON keys can be obtained by calling GET /mockserver/configuration, which returns all properties with their current values, except credentials (see below). This output can be saved as a JSON configuration file and reloaded at startup.
Credentials are never read back. Properties that hold a secret — passwords, bearer tokens, API keys, private keys, cloud access keys and connection strings, such as proxyAuthenticationPassword, dataPlaneBearerAuthenticationToken, clusterFanInPeerAuthToken, llmApiKey and blobStoreSecretAccessKey — are write-only: you can set them with PUT /mockserver/configuration, but GET /mockserver/configuration either omits them or returns ***REDACTED*** in their place, so anyone who can read the configuration cannot lift a credential from it. This means the saved output does not contain the credentials MockServer holds, and that taking the output of a GET and sending it straight back with a PUT leaves the credentials MockServer already holds untouched — but also that a configuration file produced this way needs its credentials supplied again (by property, environment variable or a later PUT) when used to configure a fresh instance.
Five properties come back masked rather than omitted, so you can read and edit the rest of the configuration around them. They fall into two groups, and the editing rule differs between them.
Whole-value credentials — replace the entire mask. llmApiKey, prometheusRemoteWriteBearerToken and prometheusRemoteWriteBasicAuthPassword come back as nothing but ***REDACTED***, because the whole value is the secret. To change one, type the new secret on its own in place of the entire ***REDACTED*** — do not type text next to the mask. A value that still contains ***REDACTED*** anywhere in it (for example sk-***REDACTED***) is not a credential MockServer can use, so it is ignored and a warning is logged, leaving the credential already in force unchanged. Sending the mask back untouched is the normal round trip: it changes nothing and logs nothing. Setting the value to an empty string still clears the credential.
Credentials inside a value — leave the masks you are not changing exactly as they came back. prometheusRemoteWriteHeaders is masked one header at a time and llmBackendsConfig one credential-named field at a time (apiKey, token, secret, password and similar), so the headers and backends around the secret stay readable. Sending such a value back containing ***REDACTED*** is the supported edit, not an error: MockServer puts the real secret back into each untouched mask and applies everything you did change. So to rename a header, add one, or change X-Scope-OrgID from tenant-a to tenant-b, edit just that part and leave Api-Key=***REDACTED*** as it is — never paste the real secret back in to work around the mask. To rotate a secret, type the new one on its own in place of that item's whole ***REDACTED***. A mask with text welded onto it (for example Api-Key=***REDACTED***-new, Authorization=Bearer ***REDACTED***) leaves MockServer unable to tell which secret you meant; it then applies none of that value and logs a warning saying so.
Do not copy a ***REDACTED*** out of GET /mockserver/config or --print-config into a PUT body. Those two outputs (and the dashboard's Server Info tab) mask every credential-named property, but most of those properties — proxyAuthenticationPassword, dataPlaneBearerAuthenticationToken, clusterFanInPeerAuthToken, blobStoreSecretAccessKey, privateKeyPath and the rest — are not returned masked by GET /mockserver/configuration at all, so a ***REDACTED*** arriving for one of them did not come from a round trip of the endpoint you are writing to. MockServer will not store it: it keeps the credential it already holds, logs a warning naming the property so a PUT that wrote nothing does not simply answer 200 OK in silence, and applies every other change in the same body normally. Set those properties to their real value, or to an empty value to remove one.
When enabled, applies a developer-friendly configuration profile that reduces memory usage for laptop and test-suite workloads. The following defaults are overridden (only for properties the user has not explicitly set via system property, environment variable, or properties file):
This is useful when running MockServer locally during development, where retaining tens of thousands of log entries is unnecessary and wastes memory.
Type: boolean Default: false
Java Code:
ConfigurationProperties.devMode(boolean enable)
System Property:
-Dmockserver.devMode=...
Environment Variable:
MOCKSERVER_DEV_MODE=...
Property File:
mockserver.devMode=...
Command Line:
mockserver run -p 1080 --dev
Maximum number of expectations held in the in-memory ring buffer. Expectations are stored in a circular queue so once this limit is reached the oldest and lowest priority expectations are overwritten.
Type: int Default: minimum of (free heap space in KB / 10) and 15000
The default is calculated automatically based on available JVM heap memory. Each expectation typically uses 4-10 KB of heap for small response bodies. Expectations with large response bodies use significantly more: a 10 KB response body results in ~15-20 KB per expectation, a 50 KB response body results in ~55-75 KB per expectation. With a 256 MB heap, the default is approximately 15,000. You can override this if you need more or want to reduce memory usage. On JVMs that do not report a usable heap maximum (for example GraalVM native images), the default falls back to a floor of 1,000 — set the property explicitly to override.
Power-of-2 sizing: the ring buffer is implemented on top of the LMAX Disruptor, which rounds the configured size up to the next power of 2. Setting maxExpectations=10000 actually allocates 16,384 slots (a 63.8% overhead). To minimise wasted heap, pick a power-of-2 value yourself: 1,024 / 2,048 / 4,096 / 8,192 / 16,384 / 32,768 / 65,536.
Java Code:
ConfigurationProperties.maxExpectations(int count)
System Property:
-Dmockserver.maxExpectations=...
Environment Variable:
MOCKSERVER_MAX_EXPECTATIONS=...
Property File:
mockserver.maxExpectations=...
Example:
-Dmockserver.maxExpectations="2000"
Maximum number of log entries to hold in memory, this includes recorded requests, expectation match failures and other log entries. Log entries are stored in a circular queue so once this limit is reached the oldest entries are overwritten. The lower the log level the more log entries will be captured, particularly at TRACE level logging.
Type: int Default: minimum of (free heap space in KB / 8) and 100000
The default is calculated automatically based on available JVM heap memory. Each log entry typically uses 4-10 KB of heap for small request/response bodies, but log entries for large responses are proportionally larger (e.g., a 100 KB response body produces log entries of ~100+ KB each). Each HTTP request generates 2-3 log entries (request recording, expectation match, and response) that are always stored regardless of log level. With a 256 MB heap the default of approximately 20,000 entries covers around 7,000-10,000 HTTP requests before the oldest entries are evicted. For high-throughput use cases or large response bodies, reduce this value to limit memory usage and GC pressure. On JVMs that do not report a usable heap maximum (for example GraalVM native images), the default falls back to a floor of 1,000 — set the property explicitly to override. See troubleshooting performance for detailed guidance.
Independent of the ring buffer: maxLogEntries controls how much history is retained, not the size of the in-flight log event ring buffer. The ring buffer is a separate, smaller buffer sized by ringBufferSize (default min(maxLogEntries, 16,384)), so raising maxLogEntries for more retention no longer inflates the ring buffer's fixed memory. You can set maxLogEntries to any value — it does not need to be a power of 2.
Java Code:
ConfigurationProperties.maxLogEntries(int count)
System Property:
-Dmockserver.maxLogEntries=...
Environment Variable:
MOCKSERVER_MAX_LOG_ENTRIES=...
Property File:
mockserver.maxLogEntries=...
Example:
-Dmockserver.maxLogEntries="20000"
Number of slots in the in-memory log event ring buffer. This buffer holds log events briefly while they are passed from the threads handling requests to the single thread that writes them to the log — it is not the retained log history (that is controlled separately by maxLogEntries). The ring buffer only needs to absorb short bursts of log events, so it can be much smaller than the retained history.
Type: int Default: minimum of maxLogEntries and 16,384 (rounded up to the next power of 2)
You rarely need to change this. Raise it only if MockServer reports dropped log events (the mock_server_dropped_log_events metric is non-zero and growing) under sustained extreme load. Lower it to save a little memory on a workload that retains a lot of history but receives requests slowly. The value is rounded up to the next power of 2 because the underlying LMAX Disruptor requires it.
Previously the ring buffer was sized from maxLogEntries, so a large retention setting (e.g. maxLogEntries=100000) forced a 131,072-slot ring (~14.7 MB of pre-allocated, mostly-empty slots). The default 16,384 ceiling caps that overhead while leaving small deployments unchanged.
Java Code:
ConfigurationProperties.ringBufferSize(int size)
System Property:
-Dmockserver.ringBufferSize=...
Environment Variable:
MOCKSERVER_RING_BUFFER_SIZE=...
Property File:
mockserver.ringBufferSize=...
Example:
-Dmockserver.ringBufferSize="8192"
OOM guard for the in-memory event log. The log is normally bounded only by entry count (maxLogEntries), not by size — so a few thousand large request/response bodies (e.g. LLM tool schemas, growing conversation context, or accumulated SSE chunks) can exhaust the heap even when the entry count is low. When this is set to a value > 0, the log also enforces a body-byte budget: once exceeded, the oldest entries are evicted (oldest-first) until the budget fits, in addition to the existing count bound.
The budget measures primary request and response body bytes only (using LogEntry.estimatedHeapSize()). Actual heap retention is a small multiple of that figure (headers, metadata, etc.), so set this well under the JVM heap. For a 2 GB heap, 256 MB (268435456) is a reasonable starting point.
When 0 (the default), the byte budget is disabled and the log is bounded only by entry count.
See Proxying LLM / Large-Body Traffic Without OOM for the recommended combo with disk capture.
Type: long Default: 0 (disabled)
Java Code:
ConfigurationProperties.maxEventLogSizeInBytes(long bytes)
Configuration.maxEventLogSizeInBytes(Long bytes)
System Property:
-Dmockserver.maxEventLogSizeInBytes=...
Environment Variable:
MOCKSERVER_MAX_EVENT_LOG_SIZE_IN_BYTES=...
Property File:
mockserver.maxEventLogSizeInBytes=...
Example:
-Dmockserver.maxEventLogSizeInBytes="268435456"
Secondary memory valve. When set to a value > 0, request and response bodies kept in memory in the event log are truncated beyond this many bytes. A x-mockserver-body-truncated: <originalLength> header is added to the in-memory copy so a reader can tell the body was clipped and how large it originally was.
This is symmetric with the existing maxStreamingCaptureBytes cap (default 256 KB) applied to SSE streams.
Important: if disk capture (persistRecordedRequestsToDisk) is also enabled, the disk archive always records the full body — the disk write happens before truncation. For full-fidelity off-line processing, leave this at 0 and rely on the byte-budget eviction (maxEventLogSizeInBytes) to bound the in-memory window instead.
When 0 (the default), bodies are kept in full in the event log (no truncation).
Type: int Default: 0 (unlimited)
Java Code:
ConfigurationProperties.maxLoggedBodyBytes(int bytes)
Configuration.maxLoggedBodyBytes(Integer bytes)
System Property:
-Dmockserver.maxLoggedBodyBytes=...
Environment Variable:
MOCKSERVER_MAX_LOGGED_BODY_BYTES=...
Property File:
mockserver.maxLoggedBodyBytes=...
Example:
-Dmockserver.maxLoggedBodyBytes="262144"
Maximum number of remote (not the same JVM) method callbacks (i.e. web sockets) registered for expectations. The web socket client registry entries are stored in a circular queue so once this limit is reach the oldest are overwritten.
Type: int Default: 1500
Java Code:
ConfigurationProperties.maxWebSocketExpectations(int count)
System Property:
-Dmockserver.maxWebSocketExpectations=...
Environment Variable:
MOCKSERVER_MAX_WEB_SOCKET_EXPECTATIONS=...
Property File:
mockserver.maxWebSocketExpectations=...
Example:
-Dmockserver.maxWebSocketExpectations="2000"
Maximum number of WebSocket frames recorded per proxied (passthrough) WebSocket connection. When MockServer proxies a WebSocket upgrade to a real upstream server (no matching WebSocket expectation), the relayed frames (text, binary, ping, pong, close) are captured into a per-connection transcript that is written to the request log when the connection closes, so retrieveRecordedRequests and the dashboard show the WebSocket traffic. Once this limit is reached the remaining frames on that connection are still relayed but not recorded, which bounds memory on long-lived connections.
Type: int Default: 1000 (set to 0 to disable frame recording; the upgrade handshake is still recorded)
Java Code:
ConfigurationProperties.webSocketProxyMaxRecordedFrames(int count)
System Property:
-Dmockserver.webSocketProxyMaxRecordedFrames=...
Environment Variable:
MOCKSERVER_WEB_SOCKET_PROXY_MAX_RECORDED_FRAMES=...
Property File:
mockserver.webSocketProxyMaxRecordedFrames=...
Example:
-Dmockserver.webSocketProxyMaxRecordedFrames="500"
Idle timeout, in seconds, for a proxied (passthrough) WebSocket connection. When set to a positive value, a relayed WebSocket connection whose two directions have both been idle (no message sent either way) for this many seconds is closed, reaping half-open or abandoned relays.
The default is 0, which disables idle reaping — long-lived WebSocket connections that are legitimately idle (for example waiting for server-pushed events) are left open and rely on TCP keep-alive. Raise it only if you need MockServer to bound how long an idle passthrough relay is held open.
Type: int Default: 0 (disabled)
Java Code:
ConfigurationProperties.webSocketProxyIdleTimeoutSeconds(int seconds)
System Property:
-Dmockserver.webSocketProxyIdleTimeoutSeconds=...
Environment Variable:
MOCKSERVER_WEB_SOCKET_PROXY_IDLE_TIMEOUT_SECONDS=...
Property File:
mockserver.webSocketProxyIdleTimeoutSeconds=...
Example:
-Dmockserver.webSocketProxyIdleTimeoutSeconds="300"
Output JVM memory usage metrics to CSV file periodically called memoryUsage_<yyyy-MM-dd>.csv
Type: boolean Default: false
Java Code:
ConfigurationProperties.outputMemoryUsageCsv(boolean enable)
System Property:
-Dmockserver.outputMemoryUsageCsv=...
Environment Variable:
MOCKSERVER_OUTPUT_MEMORY_USAGE_CSV=...
Property File:
mockserver.outputMemoryUsageCsv=...
Example:
-Dmockserver.outputMemoryUsageCsv="true"
Directory to output JVM memory usage metrics CSV files to when outputMemoryUsageCsv enabled
Type: String Default: "."
Java Code:
ConfigurationProperties.memoryUsageCsvDirectory(String directory)
System Property:
-Dmockserver.memoryUsageCsvDirectory=...
Environment Variable:
MOCKSERVER_MEMORY_USAGE_CSV_DIRECTORY=...
Property File:
mockserver.memoryUsageCsvDirectory=...
Example:
-Dmockserver.memoryUsageCsvDirectory="."
Experimental. UDP port for the experimental HTTP/3 (QUIC) listener. When set to a non-zero value MockServer starts an HTTP/3 server on this port in addition to the normal HTTP port(s); leave unset or 0 to disable (the default). When enabled, MockServer also advertises the HTTP/3 endpoint via an Alt-Svc header on all TCP (HTTP/1.1 and HTTP/2) responses so HTTP/3-capable clients automatically upgrade to QUIC (see http3AdvertiseAltSvc and http3AltSvcMaxAge). Requires the BoringSSL/QUIC native library for the runtime platform. See HTTP/3 (QUIC) Support for details and current limitations.
Type: int Default: 0 (disabled)
Java Code:
ConfigurationProperties.http3Port(int port)
System Property:
-Dmockserver.http3Port=...
Environment Variable:
MOCKSERVER_HTTP3_PORT=...
Property File:
mockserver.http3Port=...
Example:
-Dmockserver.http3Port="1080"
Experimental. Maximum idle timeout in milliseconds for QUIC connections. After this period of inactivity, the QUIC connection is closed. Increase this value if clients need to keep long-lived idle HTTP/3 connections open (e.g. for SSE or streaming scenarios).
Type: long Default: 5000
Java Code:
ConfigurationProperties.http3MaxIdleTimeout(long millis)
System Property:
-Dmockserver.http3MaxIdleTimeout=...
Environment Variable:
MOCKSERVER_HTTP3_MAX_IDLE_TIMEOUT=...
Property File:
mockserver.http3MaxIdleTimeout=...
Example:
-Dmockserver.http3MaxIdleTimeout="30000"
Experimental. Connection-level flow control limit in bytes for QUIC. This is the maximum amount of data the peer can send across all streams combined before receiving a flow-control update. The default (10 MB) is generous for testing. Reduce this if you want to simulate a constrained connection or increase it for very large request/response bodies.
Type: long Default: 10000000
Java Code:
ConfigurationProperties.http3InitialMaxData(long bytes)
System Property:
-Dmockserver.http3InitialMaxData=...
Environment Variable:
MOCKSERVER_HTTP3_INITIAL_MAX_DATA=...
Property File:
mockserver.http3InitialMaxData=...
Example:
-Dmockserver.http3InitialMaxData="50000000"
Experimental. Per-stream flow control limit in bytes for bidirectional QUIC streams. Applied to both local and remote bidirectional streams. Each HTTP/3 request uses one bidirectional stream, so this controls how much request/response data can be in flight per request before flow-control kicks in.
Type: long Default: 1000000
Java Code:
ConfigurationProperties.http3InitialMaxStreamDataBidirectional(long bytes)
System Property:
-Dmockserver.http3InitialMaxStreamDataBidirectional=...
Environment Variable:
MOCKSERVER_HTTP3_INITIAL_MAX_STREAM_DATA_BIDIRECTIONAL=...
Property File:
mockserver.http3InitialMaxStreamDataBidirectional=...
Example:
-Dmockserver.http3InitialMaxStreamDataBidirectional="5000000"
Experimental. Maximum number of concurrent bidirectional streams per QUIC connection. Each HTTP/3 request uses one bidirectional stream. The default (100) allows 100 concurrent requests per connection. Increase this if you need more parallelism per connection.
Type: long Default: 100
Java Code:
ConfigurationProperties.http3InitialMaxStreamsBidirectional(long maxStreams)
System Property:
-Dmockserver.http3InitialMaxStreamsBidirectional=...
Environment Variable:
MOCKSERVER_HTTP3_INITIAL_MAX_STREAMS_BIDIRECTIONAL=...
Property File:
mockserver.http3InitialMaxStreamsBidirectional=...
Example:
-Dmockserver.http3InitialMaxStreamsBidirectional="200"
Experimental. Maximum capacity in bytes of the QPACK dynamic table used for HTTP/3 header compression. QPACK uses a dynamic table to compress frequently repeated headers (similar to HPACK in HTTP/2). Set to 0 (the default) to disable the dynamic table entirely and use only the static table. Enable and increase this when you want HTTP/3 header compression to be more efficient for repeated headers at the cost of additional memory per connection.
Type: long Default: 0 (dynamic table disabled)
Java Code:
ConfigurationProperties.http3QpackMaxTableCapacity(long bytes)
System Property:
-Dmockserver.http3QpackMaxTableCapacity=...
Environment Variable:
MOCKSERVER_HTTP3_QPACK_MAX_TABLE_CAPACITY=...
Property File:
mockserver.http3QpackMaxTableCapacity=...
Example:
-Dmockserver.http3QpackMaxTableCapacity="4096"
Experimental. Max-age in seconds for the Alt-Svc header that MockServer adds to TCP (HTTP/1.1 and HTTP/2) responses when http3Port is set. This tells HTTP/3-capable clients how long to cache the Alt-Svc advertisement. After the max-age expires, clients will re-discover via the next response. Only relevant when http3Port > 0 and http3AdvertiseAltSvc is true.
Type: long Default: 86400 (24 hours)
Java Code:
ConfigurationProperties.http3AltSvcMaxAge(long seconds)
System Property:
-Dmockserver.http3AltSvcMaxAge=...
Environment Variable:
MOCKSERVER_HTTP3_ALT_SVC_MAX_AGE=...
Property File:
mockserver.http3AltSvcMaxAge=...
Example:
-Dmockserver.http3AltSvcMaxAge="3600"
Experimental. Whether to add an Alt-Svc header advertising HTTP/3 to responses served over the TCP (HTTP/1.1 and HTTP/2) paths when http3Port is set. When true (the default), HTTP/3-capable clients will automatically upgrade to QUIC on subsequent requests and fall back to HTTP/2 or HTTP/1.1 if QUIC is unavailable. Set to false to keep HTTP/3 enabled for direct QUIC clients without advertising it to TCP clients.
Type: boolean Default: true
Java Code:
ConfigurationProperties.http3AdvertiseAltSvc(boolean advertise)
System Property:
-Dmockserver.http3AdvertiseAltSvc=...
Environment Variable:
MOCKSERVER_HTTP3_ADVERTISE_ALT_SVC=...
Property File:
mockserver.http3AdvertiseAltSvc=...
Example:
-Dmockserver.http3AdvertiseAltSvc="false"
Experimental. Enable the CONNECT-UDP (MASQUE, RFC 9298) forward proxy on the HTTP/3 server. When enabled, the server advertises SETTINGS_ENABLE_CONNECT_PROTOCOL (RFC 9220) and extended-CONNECT requests with :protocol=connect-udp are relayed: MockServer opens a UDP socket to the target authority and forwards datagrams in both directions, so an HTTP/3 client can tunnel UDP through MockServer. Normal (non-CONNECT) HTTP/3 requests are unaffected regardless of this setting.
Security — restrict the relay target. By default the relay can reach any UDP host:port reachable from MockServer (including private networks, loopback, and cloud metadata endpoints such as 169.254.169.254), so it is intended for controlled test environments only. To constrain it, set http3ConnectUdpAllowedTargets (an allowlist) and/or enable forwardProxyBlockPrivateNetworks (which now also blocks private/loopback/metadata CONNECT-UDP targets, exactly as it does for forwarded requests). Even so, leave CONNECT-UDP disabled (the default) unless needed and do not expose a CONNECT-UDP–enabled HTTP/3 port to untrusted clients.
Type: boolean Default: false
Java Code:
ConfigurationProperties.http3ConnectUdpEnabled(boolean enabled)
System Property:
-Dmockserver.http3ConnectUdpEnabled=...
Environment Variable:
MOCKSERVER_HTTP3_CONNECT_UDP_ENABLED=...
Property File:
mockserver.http3ConnectUdpEnabled=...
Example:
-Dmockserver.http3ConnectUdpEnabled="true"
Experimental. Restrict which targets the HTTP/3 CONNECT-UDP (MASQUE) relay may reach, as a comma-separated allowlist of host or host:port entries (bracket IPv6 literals, e.g. [::1]:53). Matching is exact and case-insensitive; an entry without a port permits the host on any port. Only relevant when http3ConnectUdpEnabled is true.
When empty (the default) the allowlist is not enforced and the relay may reach any target (still subject to forwardProxyBlockPrivateNetworks). When set, a CONNECT-UDP request to a target that does not match any entry is refused with 403 and no datagrams are relayed — use this to limit the relay's SSRF exposure to a known set of destinations.
Type: string Default: "" (not enforced)
Java Code:
ConfigurationProperties.http3ConnectUdpAllowedTargets(String allowedTargets)
System Property:
-Dmockserver.http3ConnectUdpAllowedTargets=...
Environment Variable:
MOCKSERVER_HTTP3_CONNECT_UDP_ALLOWED_TARGETS=...
Property File:
mockserver.http3ConnectUdpAllowedTargets=...
Example:
-Dmockserver.http3ConnectUdpAllowedTargets="dns.example.com:53,[::1]:9090"
Maximum time in milliseconds to wait for the first response byte when forwarding/proxying
Type: long Default: 20000
Java Code:
ConfigurationProperties.maxSocketTimeout(long milliseconds)
System Property:
-Dmockserver.maxSocketTimeout=...
Environment Variable:
MOCKSERVER_MAX_SOCKET_TIMEOUT=...
Property File:
mockserver.maxSocketTimeout=...
Example:
-Dmockserver.maxSocketTimeout="10000"
Also accepted under the unit-bearing name maxSocketTimeoutInMillis / MOCKSERVER_MAX_SOCKET_TIMEOUT_IN_MILLIS, which matches the Java API and the value reported in the configuration JSON. The two names are the same setting; set whichever you prefer.
Maximum time in milliseconds allowed to connect to a socket
Type: long Default: 20000
Java Code:
ConfigurationProperties.socketConnectionTimeout(long milliseconds)
System Property:
-Dmockserver.socketConnectionTimeout=...
Environment Variable:
MOCKSERVER_SOCKET_CONNECTION_TIMEOUT=...
Property File:
mockserver.socketConnectionTimeout=...
Example:
-Dmockserver.socketConnectionTimeout="10000"
Also accepted under the unit-bearing name socketConnectionTimeoutInMillis / MOCKSERVER_SOCKET_CONNECTION_TIMEOUT_IN_MILLIS, which matches the Java API and the value reported in the configuration JSON. The two names are the same setting; set whichever you prefer.
If true socket connections will always be closed after a response is returned, if false connection is only closed if request header indicate connection should be closed.
Type: boolean Default: false
Java Code:
ConfigurationProperties.alwaysCloseSocketConnections(boolean alwaysClose)
System Property:
-Dmockserver.alwaysCloseSocketConnections=...
Environment Variable:
MOCKSERVER_ALWAYS_CLOSE_SOCKET_CONNECTIONS=...
Property File:
mockserver.alwaysCloseSocketConnections=...
Example:
-Dmockserver.alwaysCloseSocketConnections="true"
The local IP address to bind to for accepting new socket connections
Type: string Default: "" (empty string; binds to all interfaces, equivalent to 0.0.0.0)
Java Code:
ConfigurationProperties.localBoundIP(String localBoundIP)
System Property:
-Dmockserver.localBoundIP=...
Environment Variable:
MOCKSERVER_LOCAL_BOUND_IP=...
Property File:
mockserver.localBoundIP=...
Example:
-Dmockserver.localBoundIP="0.0.0.0"
By default MockServer matches the request method, path and regex body case-insensitively, so an expectation for path /Path also matches a request to /path. Enable this setting to make matching of those fields case-sensitive (exact case), so /Path only matches /Path. (Exact string bodies are already matched case-sensitively, so they are unaffected by this setting.)
This also affects response verification: when enabled, the response reason-phrase matcher in a verification (httpResponse.reasonPhrase) is also compared case-sensitively.
This only affects the request method, path, string/regex body, and response reason-phrase. Header names and values, cookie names and values, and query string parameters are always matched case-insensitively regardless of this setting (HTTP header names in particular are case-insensitive by specification, and some web containers normalise their case).
Type: boolean Default: false
Java Code:
ConfigurationProperties.matchExactCase(boolean enable)
System Property:
-Dmockserver.matchExactCase=...
Environment Variable:
MOCKSERVER_MATCH_EXACT_CASE=...
Property File:
mockserver.matchExactCase=...
Example:
-Dmockserver.matchExactCase="true"
Maximum size the first line of an HTTP request
Type: int Default: Integer.MAX_VALUE
Java Code:
ConfigurationProperties.maxInitialLineLength(int length)
System Property:
-Dmockserver.maxInitialLineLength=...
Environment Variable:
MOCKSERVER_MAX_INITIAL_LINE_LENGTH=...
Property File:
mockserver.maxInitialLineLength=...
Example:
-Dmockserver.maxInitialLineLength="8192"
Maximum size HTTP request headers
Type: int Default: Integer.MAX_VALUE
Java Code:
ConfigurationProperties.maxHeaderSize(int size)
System Property:
-Dmockserver.maxHeaderSize=...
Environment Variable:
MOCKSERVER_MAX_HEADER_SIZE=...
Property File:
mockserver.maxHeaderSize=...
Example:
-Dmockserver.maxHeaderSize="16384"
Maximum size of HTTP chunks in request or responses
Type: int Default: Integer.MAX_VALUE
Java Code:
ConfigurationProperties.maxChunkSize(int size)
System Property:
-Dmockserver.maxChunkSize=...
Environment Variable:
MOCKSERVER_MAX_CHUNK_SIZE=...
Property File:
mockserver.maxChunkSize=...
Example:
-Dmockserver.maxChunkSize="16384"
Maximum aggregated body size (in bytes) accepted on inbound HTTP/1.1 and HTTP/2 requests. Requests larger than this are rejected — HTTP/1.1 clients typically receive a 413 Payload Too Large response, while HTTP/2 streams are reset. Bounding the inbound body protects MockServer from memory exhaustion when a misbehaving or malicious client uploads an extremely large payload.
Type: int Default: 10485760 (10 MiB)
Raise this only if you intentionally mock large uploads. Very large limits make MockServer susceptible to OOM when many concurrent uploads arrive.
Java Code:
ConfigurationProperties.maxRequestBodySize(int size)
System Property:
-Dmockserver.maxRequestBodySize=...
Environment Variable:
MOCKSERVER_MAX_REQUEST_BODY_SIZE=...
Property File:
mockserver.maxRequestBodySize=...
Example:
-Dmockserver.maxRequestBodySize="52428800"
Maximum size (in bytes) of a single decoded gRPC message. A request message larger than this is rejected with grpc-status: 8 (RESOURCE_EXHAUSTED) — the status the gRPC specification uses for exceeding the receive-message-size limit, so your client can tell "message too big" apart from "the server broke".
Type: int Default: 4194304 (4 MiB)
The default matches gRPC-Java and gRPC-Go, so a message MockServer accepts is one a real gRPC server would accept too. The limit is also applied while decompressing, so a small compressed message cannot expand past it.
This is separate from maxRequestBodySize, which bounds the whole HTTP body: one HTTP body can carry several gRPC messages (client streaming), and this limit applies to each message. Raise it only if you intentionally mock large gRPC messages — it is what stops a declared message length from allocating unbounded memory.
Java Code:
ConfigurationProperties.maxGrpcMessageSize(int size)
System Property:
-Dmockserver.maxGrpcMessageSize=...
Environment Variable:
MOCKSERVER_MAX_GRPC_MESSAGE_SIZE=...
Property File:
mockserver.maxGrpcMessageSize=...
Example:
-Dmockserver.maxGrpcMessageSize="16777216"
Maximum aggregated body size (in bytes) accepted on responses received from upstream servers when MockServer is acting as a proxy or forwarder.
Type: int Default: 52428800 (50 MiB)
Java Code:
ConfigurationProperties.maxResponseBodySize(int size)
System Property:
-Dmockserver.maxResponseBodySize=...
Environment Variable:
MOCKSERVER_MAX_RESPONSE_BODY_SIZE=...
Property File:
mockserver.maxResponseBodySize=...
Example:
-Dmockserver.maxResponseBodySize="104857600"
Maximum time (in milliseconds) allowed for evaluating a single regular expression during request matching. A pathological pattern (e.g. (a+)+b) that exceeds this budget is treated as a non-match and a WARN log entry is written, so the server cannot be wedged by exponential regex backtracking from a malicious expectation or input. Set to 0 or a negative value to disable the timeout.
Performance note: the timeout is enforced by evaluating each regular expression on a shared executor and waiting for the result, which adds a thread hand-off per regex, per matcher, per request. Setting this to 0 runs regex evaluation inline on the request thread, removing that hand-off — a measurable speed-up for matchers that evaluate many regular expressions per request. Only do this when your expectations and request inputs use trusted, non-pathological patterns, because it also removes the backtracking guard (a single catastrophic pattern can then block a worker thread). This is a global switch; there is intentionally no per-pattern “inline this one” option, as even a short pattern can backtrack catastrophically.
Type: long Default: 5000
Java Code:
ConfigurationProperties.regexMatchingTimeoutMillis(long milliseconds)
System Property:
-Dmockserver.regexMatchingTimeoutMillis=...
Environment Variable:
MOCKSERVER_REGEX_MATCHING_TIMEOUT_MILLIS=...
Property File:
mockserver.regexMatchingTimeoutMillis=...
Example:
-Dmockserver.regexMatchingTimeoutMillis="2000"
Maximum time (in milliseconds) allowed for evaluating a single XPath expression against an XML document during request matching. Exceeding this budget is treated as a non-match and a WARN log entry is written, protecting MockServer from XPath-based denial-of-service. Set to 0 or a negative value to disable the timeout.
Type: long Default: 5000
Java Code:
ConfigurationProperties.xpathMatchingTimeoutMillis(long milliseconds)
System Property:
-Dmockserver.xpathMatchingTimeoutMillis=...
Environment Variable:
MOCKSERVER_XPATH_MATCHING_TIMEOUT_MILLIS=...
Property File:
mockserver.xpathMatchingTimeoutMillis=...
Example:
-Dmockserver.xpathMatchingTimeoutMillis="2000"
Fully qualified name of a class that registers custom json-unit matchers, so JSON body expectations can validate dynamic values (e.g. "price must be greater than 100") with the ${json-unit.matches:name} placeholder.
The class must have a public no-arg constructor and implement org.mockserver.matchers.CustomJsonUnitMatcherProvider, returning a Map<String, org.hamcrest.Matcher<?>> keyed by the placeholder name. If the class cannot be loaded, does not implement the interface, or its constructor throws, MockServer logs a WARN and JSON matching falls back to its built-in behaviour.
Type: string Default: "" (no custom matchers)
Example provider:
public class MyJsonUnitMatchers implements CustomJsonUnitMatcherProvider {
public Map<String, Matcher<?>> jsonUnitMatchers() {
Map<String, Matcher<?>> matchers = new HashMap<>();
matchers.put("largerThan", new BaseMatcher<Object>() {
public boolean matches(Object actual) {
return new BigDecimal(actual.toString()).compareTo(BigDecimal.valueOf(100)) > 0;
}
public void describeTo(Description d) { d.appendText("a number larger than 100"); }
});
return matchers;
}
}
Then reference the matcher from the JSON body of an expectation:
{ "price": "${json-unit.matches:largerThan}" }
Java Code:
ConfigurationProperties.customJsonUnitMatchersClass(String className)
System Property:
-Dmockserver.customJsonUnitMatchersClass=...
Environment Variable:
MOCKSERVER_CUSTOM_JSON_UNIT_MATCHERS_CLASS=...
Property File:
mockserver.customJsonUnitMatchersClass=...
Example:
-Dmockserver.customJsonUnitMatchersClass="com.example.MyJsonUnitMatchers"
Controls whether JSON Schema body matchers are permitted to fetch remote $ref URIs (http, https, file, jar). By default MockServer blocks remote resolution to prevent server-side request forgery (SSRF): a schema body that contains "$ref": "https://attacker.example/evil.json" would otherwise cause MockServer to make an outbound HTTP request when matching any incoming request against that expectation. Schemas that use only inline definitions or internal anchors (#/...) are unaffected by this setting.
Set to true only when you control all schema $ref URIs and genuinely need cross-document resolution.
Note: this property is read from the JVM system property at schema-build time via System.getProperty; it is not available as an environment variable or in a properties file.
Type: boolean Default: false
System Property:
-Dmockserver.jsonSchemaAllowRemoteRefs=...
Example:
-Dmockserver.jsonSchemaAllowRemoteRefs="true"
When enabled, if no expectation matches an incoming request the 404 response carries the verbose closest-match diagnostic: an x-mockserver-closest-match header plus a JSON body describing which expectation came closest to matching and which fields differed. This lets you see why a mock did not match directly from the response, without checking the MockServer logs or dashboard.
Useful when debugging in test environments. Leave it disabled (the default) for any production-facing use, as the diagnostic exposes expectation internals in the response body.
This is the verbose, opt-in counterpart of closestMatchHintEnabled (a compact, header-only hint that is on by default). The two use different header names and are independent: if both are enabled an unmatched 404 carries both headers (x-mockserver-closest-match with the JSON body, and x-mockserver-closest-match-hint with the one-line summary).
Type: boolean Default: false
Java Code:
ConfigurationProperties.attachMismatchDiagnosticToResponse(boolean enable)
System Property:
-Dmockserver.attachMismatchDiagnosticToResponse=...
Environment Variable:
MOCKSERVER_ATTACH_MISMATCH_DIAGNOSTIC_TO_RESPONSE=...
Property File:
mockserver.attachMismatchDiagnosticToResponse=...
Example:
-Dmockserver.attachMismatchDiagnosticToResponse="true"
When enabled (the default), if no expectation matches an incoming request the 404 response carries a single concise x-mockserver-closest-match-hint header naming the closest expectation and the first field that differed (for example expectation 1a2b: method did not match (expected POST but was GET)). This answers “why didn’t my mock match?” straight from the response, without opening the MockServer logs or dashboard.
The hint is header-only and length-bounded — it never adds a response body, so it cannot leak large or sensitive expectation contents. That is what makes it safe to enable by default. Its verbose counterpart, attachMismatchDiagnosticToResponse (off by default), additionally writes a full JSON diff body under a different header (x-mockserver-closest-match); the two are independent, so enabling both yields both headers on an unmatched 404.
Type: boolean Default: true
Set this to false if you need unmatched 404 responses to be byte-for-byte free of the extra header (for example a test that asserts the exact response).
Java Code:
ConfigurationProperties.closestMatchHintEnabled(boolean enable)
System Property:
-Dmockserver.closestMatchHintEnabled=...
Environment Variable:
MOCKSERVER_CLOSEST_MATCH_HINT_ENABLED=...
Property File:
mockserver.closestMatchHintEnabled=...
Example:
-Dmockserver.closestMatchHintEnabled="true"
When enabled, MockServer rejects forward and proxy targets that resolve to loopback, link-local, RFC 1918 private, or cloud metadata addresses (such as 169.254.169.254). This blocks server-side request forgery (SSRF) attacks where a malicious expectation would otherwise forward through MockServer to internal infrastructure.
Type: boolean Default: false
The default is false because MockServer is most commonly used to mock services running on localhost, Docker bridge networks, or Kubernetes service IPs — blocking those by default would break the common case. Enable this in hardened or multi-tenant deployments where untrusted callers can register expectations.
Java Code:
ConfigurationProperties.forwardProxyBlockPrivateNetworks(boolean block)
System Property:
-Dmockserver.forwardProxyBlockPrivateNetworks=...
Environment Variable:
MOCKSERVER_FORWARD_PROXY_BLOCK_PRIVATE_NETWORKS=...
Property File:
mockserver.forwardProxyBlockPrivateNetworks=...
Example:
-Dmockserver.forwardProxyBlockPrivateNetworks="true"
Whether to honour TLSv1 and TLSv1.1 in tlsProtocols. Both protocols are deprecated by RFC 8996 and vulnerable to BEAST and POODLE.
Type: boolean Default: true
The default is true for backwards compatibility — MockServer's tlsProtocols default still includes TLSv1 and TLSv1.1. Set this to false to opt into a hardened profile: any TLSv1 or TLSv1.1 entries in tlsProtocols are filtered out before the SSL context is built. A future major release is expected to flip this default to false.
Java Code:
ConfigurationProperties.tlsAllowInsecureProtocols(boolean allow)
System Property:
-Dmockserver.tlsAllowInsecureProtocols=...
Environment Variable:
MOCKSERVER_TLS_ALLOW_INSECURE_PROTOCOLS=...
Property File:
mockserver.tlsAllowInsecureProtocols=...
Example:
-Dmockserver.tlsAllowInsecureProtocols="false"
If true semicolons are treated as a separator for a query parameter string, if false the semicolon is treated as a normal character that is part of a query parameter value.
Type: boolean Default: true
Java Code:
ConfigurationProperties.useSemicolonAsQueryParameterSeparator(boolean useSemicolonAsQueryParameterSeparator)
System Property:
-Dmockserver.useSemicolonAsQueryParameterSeparator=...
Environment Variable:
MOCKSERVER_USE_SEMICOLON_AS_QUERY_PARAMETER_SEPARATOR=...
Property File:
mockserver.useSemicolonAsQueryParameterSeparator=...
Example:
-Dmockserver.useSemicolonAsQueryParameterSeparator="false"
If true (the default) MockServer sends itself a single warm-up request in the background immediately after it starts listening.
The very first request handled by a freshly started MockServer is noticeably slower than every request after it (typically a few hundred milliseconds) because the code that handles requests is only loaded and initialised the first time it is used. The warm-up request pays that one-off cost in the background so the first request from your test or application — including a readiness poll such as Testcontainers — is fast.
The warm-up runs on a background thread and never delays start up. Leave it enabled unless you want to avoid the single extra loopback request during start up, for example in a tightly locked-down environment where MockServer must not connect to itself.
Type: boolean Default: true
Java Code:
ConfigurationProperties.startupWarmup(boolean enable)
System Property:
-Dmockserver.startupWarmup=...
Environment Variable:
MOCKSERVER_STARTUP_WARMUP=...
Property File:
mockserver.startupWarmup=...
Example:
-Dmockserver.startupWarmup="false"
If false requests are assumed as binary if the method isn't one of "GET", "POST", "PUT", "HEAD", "OPTIONS", "PATCH", "DELETE", "TRACE" or "CONNECT"
Type: boolean Default: false
Java Code:
ConfigurationProperties.assumeAllRequestsAreHttp(boolean assumeAllRequestsAreHttp)
System Property:
-Dmockserver.assumeAllRequestsAreHttp=...
Environment Variable:
MOCKSERVER_ASSUME_ALL_REQUESTS_ARE_HTTP=...
Property File:
mockserver.assumeAllRequestsAreHttp=...
Example:
-Dmockserver.assumeAllRequestsAreHttp="true"
If false HTTP/2 is disabled so MockServer no longer advertises h2 during TLS ALPN negotiation (and does not detect the HTTP/2 cleartext h2c upgrade). HTTP/2 capable clients then fall back to HTTP/1.1, which is useful for testing how a client behaves over HTTP/1.1 without changing the client itself.
Type: boolean Default: true
Java Code:
ConfigurationProperties.http2Enabled(boolean http2Enabled)
System Property:
-Dmockserver.http2Enabled=...
Environment Variable:
MOCKSERVER_HTTP2_ENABLED=...
Property File:
mockserver.http2Enabled=...
Example:
-Dmockserver.http2Enabled="false"
If true, MockServer uses a per-stream HTTP/2 multiplex pipeline (Http2FrameCodec + Http2MultiplexHandler) instead of the connection-level adapter for HTTP/2 connections where gRPC descriptors are loaded. This is a prerequisite for true client-streaming and bidirectional-streaming gRPC support (to be enabled in a future release). When enabled, the pipeline re-aggregates stream frames so existing unary and server-streaming gRPC behaviour is unchanged.
Requires gRPC to be enabled with descriptors loaded. When false (the default) or when no gRPC descriptors are loaded, the existing connection-level HTTP/2 adapter is used.
Type: boolean Default: false
Java Code:
ConfigurationProperties.grpcBidiStreamingEnabled(boolean enable)
System Property:
-Dmockserver.grpcBidiStreamingEnabled=...
Environment Variable:
MOCKSERVER_GRPC_BIDI_STREAMING_ENABLED=...
Property File:
mockserver.grpcBidiStreamingEnabled=...
Example:
-Dmockserver.grpcBidiStreamingEnabled="true"
Headers that MockServer stamps onto every response it returns — mock responses, the control‑plane / dashboard responses, and forwarded / proxied responses. Use this to add organisation‑wide headers (for example a Server header, a build or trace id, or custom org headers) without repeating them on every individual expectation.
Add‑if‑absent: a default header is only added when the response does not already contain a header with that name (matched case‑insensitively), so a header explicitly set on the matched expectation / response always wins.
Format: a pipe (|) separated list of name=value pairs, for example Server=MockServer|X-Trace-Id=abc123. A header value may itself contain commas (for example Cache-Control=no-cache, no-store) — only | separates headers and only the first = in each pair separates the name from the value. Leading / trailing whitespace around each name and value is trimmed.
Type: string Default: "" (no default response headers are added, so behaviour is unchanged)
Java Code:
ConfigurationProperties.defaultResponseHeaders(String defaultResponseHeaders)
System Property:
-Dmockserver.defaultResponseHeaders=...
Environment Variable:
MOCKSERVER_DEFAULT_RESPONSE_HEADERS=...
Property File:
mockserver.defaultResponseHeaders=...
Example:
-Dmockserver.defaultResponseHeaders="Server=MockServer|X-Trace-Id=abc123"
Note: HTTP/2 proxying has limitations. When MockServer forwards requests to downstream services, HTTP/2 requests are downgraded to HTTP/1.1. MockServer can accept HTTP/2 connections and serve mock responses over HTTP/2, but forwarded/proxied requests are always sent as HTTP/1.1. See HTTP/2 proxy limitations for details.
When set to true, MockServer generates a unique Certificate Authority (CA) key pair on first startup and saves it to directoryToSaveDynamicSSLCertificate (default: the working directory). This is equivalent to enabling dynamicallyCreateCertificateAuthorityCertificate but is exposed as a single, easy-to-remember flag for proxy setups.
Use this flag for any shared, persistent, or team-facing setup. Without it, MockServer uses the built-in default CA whose private key is published in the MockServer git repository — safe only for isolated local development.
For standalone launches (JAR, Docker, CLI), the startup "Proxy Setup" log block and the mockserver-ca.pem file are written automatically. The CA certificate and proxy configuration are always available on demand from GET /mockserver/proxyConfiguration, regardless of how MockServer was started.
Type: boolean Default: false
System Property:
-Dmockserver.proxySetup=...
Environment Variable:
MOCKSERVER_PROXY_SETUP=...
Property File:
mockserver.proxySetup=...
Example:
-Dmockserver.proxySetup="true"
Controls whether MockServer prints a "Proxy Setup" block to the log at startup. The block contains the absolute path to the CA certificate file and the environment variable exports to set (HTTPS_PROXY, NODE_EXTRA_CA_CERTS, SSL_CERT_FILE, REQUESTS_CA_BUNDLE) in both Unix export and Windows PowerShell $env: forms, ready to paste into a terminal.
The default is false, but the standalone launcher (the executable JAR, Docker image, and mockserver CLI) automatically enables this at startup, so anyone running MockServer as a proxy sees the block without any extra configuration. Embedded usage (new ClientAndServer(...) inside a test suite) stays silent by default to avoid polluting test output on every JUnit run; set this to true explicitly if the block is needed in embedded mode.
When this setting is enabled, MockServer writes the CA certificate to mockserver-ca.pem in the dynamic-SSL directory at startup and prints the "Proxy Setup" log block. When this setting is disabled (e.g. embedded usage), the CA file is instead written on the first call to GET /mockserver/proxyConfiguration. The endpoint itself is always available regardless of this setting.
Type: boolean Default: false (auto-enabled by the standalone launcher)
System Property:
-Dmockserver.proxySetupLogging=...
Environment Variable:
MOCKSERVER_PROXY_SETUP_LOGGING=...
Property File:
mockserver.proxySetupLogging=...
Example:
-Dmockserver.proxySetupLogging="true"
If true (the default) when no matching expectation is found, and the host header of the request does not match MockServer's host, then MockServer attempts to proxy the request. If the upstream server is unreachable (connection refused, TLS error, timeout, etc.) a 502 Bad Gateway is returned. If no matching expectation is found and the request is not eligible for proxying, a 404 is returned.
If false when no matching expectation is found, and MockServer is not being used as a proxy, then MockServer always returns a 404 immediately.
Note: this property only triggers proxy behaviour when the Host header in the request differs from MockServer's own local addresses (e.g., localhost, 127.0.0.1, or the machine's hostname). If the Host header matches MockServer's address, the request is not forwarded regardless of this setting. In Docker, set this via environment variable: MOCKSERVER_ATTEMPT_TO_PROXY_IF_NO_MATCHING_EXPECTATION=true.
Type: boolean Default: true
Java Code:
ConfigurationProperties.attemptToProxyIfNoMatchingExpectation(boolean enable)
System Property:
-Dmockserver.attemptToProxyIfNoMatchingExpectation=...
Environment Variable:
MOCKSERVER_ATTEMPT_TO_PROXY_IF_NO_MATCHING_EXPECTATION=...
Property File:
mockserver.attemptToProxyIfNoMatchingExpectation=...
Example:
-Dmockserver.attemptToProxyIfNoMatchingExpectation="false"
If true, binary (non-HTTP) requests that are forwarded upstream are sent without waiting for a response from the upstream server (fire-and-forget). This is useful for one-way binary protocols where no response is expected.
If false (the default), MockServer waits for the upstream server to respond before completing the forwarded binary request.
Type: boolean Default: false
Java Code:
ConfigurationProperties.forwardBinaryRequestsWithoutWaitingForResponse(boolean forwardBinaryRequestsAsynchronously)
System Property:
-Dmockserver.forwardBinaryRequestsWithoutWaitingForResponse=...
Environment Variable:
MOCKSERVER_FORWARD_BINARY_REQUESTS_WITHOUT_WAITING_FOR_RESPONSE=...
Property File:
mockserver.forwardBinaryRequestsWithoutWaitingForResponse=...
Example:
-Dmockserver.forwardBinaryRequestsWithoutWaitingForResponse="true"
By default (true) MockServer pools idle keep-alive HTTP/1.1 upstream connections (keyed by host, port and scheme) and reuses them for subsequent requests to the same upstream. Reusing the upstream's keep-alive connections eliminates repeated TCP and TLS handshakes, significantly improves throughput for proxy-heavy workloads that repeatedly call the same upstream, and avoids ephemeral-port exhaustion under sustained forward load (where opening a fresh connection per request can exhaust the operating system's available local ports and cause request failures). Set this to false to open a fresh upstream connection per request that is closed once the response is received (the historical behaviour) — useful only for unusual upstreams.
Pooling is safe to leave on: a connection is only returned to the pool when it is genuinely clean — its HTTP client codec must have no leftover undecoded bytes after the response, and any uncertainty closes the connection instead of pooling it. MockServer's error() action (which deliberately returns raw, non-HTTP bytes and/or drops the connection) — or any malformed upstream reply — is therefore never pooled, so a later request can never reuse a corrupted connection.
Only plain HTTP/1.1 keep-alive connections are pooled. HTTP/2, HTTP/3, binary forwarding, streaming (Server-Sent Events) responses, and proxy-tunnelled connections are never pooled. A connection the upstream closed, that returned Connection: close, or that returned a reply which did not parse as valid HTTP is never reused and falls back to a fresh connection.
Type: boolean Default: true
Java Code:
ConfigurationProperties.forwardConnectionPoolEnabled(boolean enable)
System Property:
-Dmockserver.forwardConnectionPoolEnabled=...
Environment Variable:
MOCKSERVER_FORWARD_CONNECTION_POOL_ENABLED=...
Property File:
mockserver.forwardConnectionPoolEnabled=...
Example:
-Dmockserver.forwardConnectionPoolEnabled="false"
The maximum number of idle keep-alive upstream connections retained per upstream (host, port and scheme) when connection pooling is enabled. When this limit is reached, surplus connections are closed rather than pooled, so the pool degrades gracefully under load and never blocks. Values below 1 are treated as 1. Only relevant when forwardConnectionPoolEnabled is true.
Type: int Default: 8
Java Code:
ConfigurationProperties.forwardConnectionPoolMaxIdlePerKey(int maxIdlePerKey)
System Property:
-Dmockserver.forwardConnectionPoolMaxIdlePerKey=...
Environment Variable:
MOCKSERVER_FORWARD_CONNECTION_POOL_MAX_IDLE_PER_KEY=...
Property File:
mockserver.forwardConnectionPoolMaxIdlePerKey=...
Example:
-Dmockserver.forwardConnectionPoolMaxIdlePerKey="16"
How long in milliseconds an idle pooled upstream connection is retained before it is closed and evicted when connection pooling is enabled. Set to 0 to disable idle eviction (connections are still discarded when the upstream closes them). Only relevant when forwardConnectionPoolEnabled is true.
Type: long Default: 30000
Java Code:
ConfigurationProperties.forwardConnectionPoolIdleTimeoutMillis(long idleTimeoutMillis)
System Property:
-Dmockserver.forwardConnectionPoolIdleTimeoutMillis=...
Environment Variable:
MOCKSERVER_FORWARD_CONNECTION_POOL_IDLE_TIMEOUT_MILLIS=...
Property File:
mockserver.forwardConnectionPoolIdleTimeoutMillis=...
Example:
-Dmockserver.forwardConnectionPoolIdleTimeoutMillis="60000"
By default, when a burst of forwarded or proxied requests finishes, the pool keeps only up to forwardConnectionPoolMaxIdlePerKey idle connections per upstream and closes the rest. Under very high request rates against a fast upstream (responses returning in well under a millisecond) this can cause connection churn: requests are dispatched faster than earlier connections are returned to the pool, so each opens a fresh connection and the surplus is then closed — capping throughput on connection setup rather than on real work.
Enable this setting to keep those connections warm instead of closing them: idle keep-alive connections are retained on release up to forwardConnectionPoolMaxTotalPerKey per upstream, so the warm pool grows to match the offered concurrency and is then reused, eliminating the churn. Warm connections are still closed and evicted once they have been idle for forwardConnectionPoolIdleTimeoutMillis, so the pool drains back down when load stops.
The default (off) leaves the pool's behaviour exactly as before. Enable it for sustained high-throughput forwarding or load injection against a fast upstream. Only relevant when forwardConnectionPoolEnabled is true.
Type: boolean Default: false
Java Code:
ConfigurationProperties.forwardConnectionPoolKeepAlive(boolean enable)
System Property:
-Dmockserver.forwardConnectionPoolKeepAlive=...
Environment Variable:
MOCKSERVER_FORWARD_CONNECTION_POOL_KEEP_ALIVE=...
Property File:
mockserver.forwardConnectionPoolKeepAlive=...
Example:
-Dmockserver.forwardConnectionPoolKeepAlive="true"
The maximum number of warm (idle) keep-alive upstream connections retained per upstream (host, port and scheme) when forwardConnectionPoolKeepAlive is enabled. This bounds the warm pool so it cannot grow without limit; connections offered beyond this ceiling are closed. The effective ceiling is never below forwardConnectionPoolMaxIdlePerKey (keeping connections warm only ever raises retention, never lowers it). Has no effect unless both forwardConnectionPoolEnabled and forwardConnectionPoolKeepAlive are true.
Type: int Default: 2000
Java Code:
ConfigurationProperties.forwardConnectionPoolMaxTotalPerKey(int maxTotalPerKey)
System Property:
-Dmockserver.forwardConnectionPoolMaxTotalPerKey=...
Environment Variable:
MOCKSERVER_FORWARD_CONNECTION_POOL_MAX_TOTAL_PER_KEY=...
Property File:
mockserver.forwardConnectionPoolMaxTotalPerKey=...
Example:
-Dmockserver.forwardConnectionPoolMaxTotalPerKey="4000"
Enables TCP keepalive (SO_KEEPALIVE) on the connections the forward / proxy client opens to upstream servers. Keepalive lets the operating system detect dead or half-open upstream connections faster (most useful during long-lived or streaming requests) and keeps NAT and firewall connection mappings warm so they are not silently dropped while a pooled connection sits idle. It complements — it does not replace — the connection pool's own liveness checks and idle eviction.
On Linux with the native epoll transport the keepalive timers are tuned (see the idle / interval / count settings below) so a dead peer is detected in about a minute or two rather than the operating-system default of around two hours. On other platforms (macOS, Windows) or when native transport is disabled, only SO_KEEPALIVE is enabled and the operating-system default timers apply.
This is on by default. It is a small, benign change from older versions (which set no keepalive): it is standard for production HTTP clients, costs only an occasional probe packet on otherwise-idle connections, and improves detection of broken upstream connections. Set to false to restore the previous behaviour of no socket keepalive. If you enable keep-warm pooling against a real upstream, also keep forwardConnectionPoolIdleTimeoutMillis below the upstream/NAT idle window so idle connections are reaped before they are silently dropped; keepalive helps detect any that slip through as half-open.
Type: boolean Default: true
Java Code:
ConfigurationProperties.forwardSocketKeepAlive(boolean enable)
System Property:
-Dmockserver.forwardSocketKeepAlive=...
Environment Variable:
MOCKSERVER_FORWARD_SOCKET_KEEP_ALIVE=...
Property File:
mockserver.forwardSocketKeepAlive=...
Example:
-Dmockserver.forwardSocketKeepAlive="false"
How long (in seconds) an upstream connection may sit idle before the first TCP keepalive probe is sent. Only applied on the native epoll transport (Linux) when forwardSocketKeepAlive is enabled. Values below 1 are treated as 1.
Type: int Default: 60
Java Code:
ConfigurationProperties.forwardSocketKeepAliveIdleSeconds(int idleSeconds)
System Property:
-Dmockserver.forwardSocketKeepAliveIdleSeconds=...
Environment Variable:
MOCKSERVER_FORWARD_SOCKET_KEEP_ALIVE_IDLE_SECONDS=...
Property File:
mockserver.forwardSocketKeepAliveIdleSeconds=...
Example:
-Dmockserver.forwardSocketKeepAliveIdleSeconds="120"
How long (in seconds) between successive TCP keepalive probes once probing has started. Only applied on the native epoll transport (Linux) when forwardSocketKeepAlive is enabled. Values below 1 are treated as 1.
Type: int Default: 15
Java Code:
ConfigurationProperties.forwardSocketKeepAliveIntervalSeconds(int intervalSeconds)
System Property:
-Dmockserver.forwardSocketKeepAliveIntervalSeconds=...
Environment Variable:
MOCKSERVER_FORWARD_SOCKET_KEEP_ALIVE_INTERVAL_SECONDS=...
Property File:
mockserver.forwardSocketKeepAliveIntervalSeconds=...
Example:
-Dmockserver.forwardSocketKeepAliveIntervalSeconds="30"
The number of unacknowledged TCP keepalive probes after which an upstream connection is considered dead and closed. Only applied on the native epoll transport (Linux) when forwardSocketKeepAlive is enabled. Values below 1 are treated as 1. With the defaults (idle 60s, interval 15s, count 4) a dead peer is detected roughly 60 + 4×15 = 120 seconds after it goes idle.
Type: int Default: 4
Java Code:
ConfigurationProperties.forwardSocketKeepAliveCount(int count)
System Property:
-Dmockserver.forwardSocketKeepAliveCount=...
Environment Variable:
MOCKSERVER_FORWARD_SOCKET_KEEP_ALIVE_COUNT=...
Property File:
mockserver.forwardSocketKeepAliveCount=...
Example:
-Dmockserver.forwardSocketKeepAliveCount="6"
By default every forwarded request is sent to its upstream over HTTP/1.1, regardless of the protocol the incoming request used. Enable this setting to preserve the incoming request's protocol when forwarding, so a request that arrived over HTTP/2 is forwarded to the upstream over HTTP/2 as well.
HTTP/2 forwarding only happens over TLS using ALPN negotiation. A non-secure (plain HTTP) request is always forwarded over HTTP/1.1 even when this setting is enabled, because HTTP/2 without TLS (h2c) is not supported for forwarding. HTTP/2 upstream connections are also not reused across requests — the upstream connection pool only applies to HTTP/1.1 — so enable this only when your upstream needs to receive HTTP/2.
The default (off) is unchanged from previous behaviour: all forwarded requests use HTTP/1.1.
Type: boolean Default: false
Java Code:
ConfigurationProperties.forwardProxyHttp2Enabled(boolean enable)
System Property:
-Dmockserver.forwardProxyHttp2Enabled=...
Environment Variable:
MOCKSERVER_FORWARD_PROXY_HTTP2_ENABLED=...
Property File:
mockserver.forwardProxyHttp2Enabled=...
Example:
-Dmockserver.forwardProxyHttp2Enabled="true"
By default a forwarded request is only sent over HTTP/2 when the incoming request itself used HTTP/2 (and "Forward Upstream Requests Using HTTP/2" is enabled). Enable this setting to forward a secure (TLS) request to its upstream over HTTP/2 via ALPN even when the incoming client used HTTP/1.1, with automatic fallback to HTTP/1.1 if the upstream does not negotiate HTTP/2.
This is useful when an upstream sends a streaming (Server-Sent Events) response head immediately over HTTP/2 but withholds it over HTTP/1.1 — forwarding over HTTP/2 lets MockServer relay the response head to the client promptly instead of waiting for the whole stream. HTTP/2 only happens over TLS using ALPN (there is no plain-HTTP h2c path, so a non-secure request is unaffected and stays HTTP/1.1). HTTP/2 upstream connections are not reused across requests.
It applies to both matched forward expectations and the transparent (HTTPS) proxy path used to capture a tool's traffic — so it is the recommended setting when recording a coding-assistant CLI (for example the opencode CLI, whose OpenAI Codex backend withholds its SSE head over HTTP/1.1) through MockServer as an HTTPS proxy, where it otherwise surfaces as a streaming header timeout.
The default (off) is unchanged from previous behaviour.
Type: boolean Default: false
Java Code:
ConfigurationProperties.forwardProxyHttp2Upgrade(boolean enable)
System Property:
-Dmockserver.forwardProxyHttp2Upgrade=...
Environment Variable:
MOCKSERVER_FORWARD_PROXY_HTTP2_UPGRADE=...
Property File:
mockserver.forwardProxyHttp2Upgrade=...
Example:
-Dmockserver.forwardProxyHttp2Upgrade="true"
The maximum number of times MockServer retries a forwarded or proxied request to an upstream after a transient failure — a connection error (refused/reset), a timeout, or an upstream response of 502, 503 or 504. Retries reduce flakiness when the real upstream is briefly unavailable.
To avoid executing a request twice, only requests using an idempotent HTTP method (GET, HEAD, OPTIONS, PUT, DELETE, TRACE) are retried; non-idempotent methods (POST, PATCH) are never retried. The default (0) forwards each request exactly once, unchanged from previous behaviour.
Type: int Default: 0
Java Code:
ConfigurationProperties.forwardProxyRetryCount(int retryCount)
System Property:
-Dmockserver.forwardProxyRetryCount=...
Environment Variable:
MOCKSERVER_FORWARD_PROXY_RETRY_COUNT=...
Property File:
mockserver.forwardProxyRetryCount=...
Example:
-Dmockserver.forwardProxyRetryCount="3"
The base back-off in milliseconds applied between forward/proxy retry attempts. The delay grows linearly with the attempt number (the first retry waits one base delay, the second waits two, and so on) so a flaky upstream is not hammered. Set to 0 to retry immediately. Only relevant when forwardProxyRetryCount is greater than 0.
Type: long Default: 100
Java Code:
ConfigurationProperties.forwardProxyRetryBackoffMillis(long backoffMillis)
System Property:
-Dmockserver.forwardProxyRetryBackoffMillis=...
Environment Variable:
MOCKSERVER_FORWARD_PROXY_RETRY_BACKOFF_MILLIS=...
Property File:
mockserver.forwardProxyRetryBackoffMillis=...
Example:
-Dmockserver.forwardProxyRetryBackoffMillis="250"
By default every forwarded or proxied request is attempted against its upstream, however many previous requests failed. Enable this setting to add a per-upstream circuit breaker (keyed by host and port): after forwardProxyCircuitBreakerFailureThreshold consecutive failures to one upstream the breaker trips open and subsequent requests fail fast with a 503 for forwardProxyCircuitBreakerWindowMillis milliseconds, instead of waiting on a dead upstream. After the window a single trial request is allowed through (half-open); a success closes the breaker, a failure re-opens it for another window.
When metrics are enabled the number of currently-open upstreams is exported as the mock_server_upstream_circuit_open Prometheus gauge. The default (off) is unchanged from previous behaviour.
Type: boolean Default: false
Java Code:
ConfigurationProperties.forwardProxyCircuitBreakerEnabled(boolean enable)
System Property:
-Dmockserver.forwardProxyCircuitBreakerEnabled=...
Environment Variable:
MOCKSERVER_FORWARD_PROXY_CIRCUIT_BREAKER_ENABLED=...
Property File:
mockserver.forwardProxyCircuitBreakerEnabled=...
Example:
-Dmockserver.forwardProxyCircuitBreakerEnabled="true"
The number of consecutive failures to a single upstream (host and port) that trips the forward/proxy circuit breaker open. Only relevant when forwardProxyCircuitBreakerEnabled is true. Values below 1 are treated as 1.
Type: int Default: 5
Java Code:
ConfigurationProperties.forwardProxyCircuitBreakerFailureThreshold(int failureThreshold)
System Property:
-Dmockserver.forwardProxyCircuitBreakerFailureThreshold=...
Environment Variable:
MOCKSERVER_FORWARD_PROXY_CIRCUIT_BREAKER_FAILURE_THRESHOLD=...
Property File:
mockserver.forwardProxyCircuitBreakerFailureThreshold=...
Example:
-Dmockserver.forwardProxyCircuitBreakerFailureThreshold="10"
How long in milliseconds the forward/proxy circuit breaker stays open (failing requests fast with a 503) for an upstream before it transitions to half-open and lets a single trial request through. Only relevant when forwardProxyCircuitBreakerEnabled is true. Values below 1 are treated as 1.
Type: long Default: 30000
Java Code:
ConfigurationProperties.forwardProxyCircuitBreakerWindowMillis(long windowMillis)
System Property:
-Dmockserver.forwardProxyCircuitBreakerWindowMillis=...
Environment Variable:
MOCKSERVER_FORWARD_PROXY_CIRCUIT_BREAKER_WINDOW_MILLIS=...
Property File:
mockserver.forwardProxyCircuitBreakerWindowMillis=...
Example:
-Dmockserver.forwardProxyCircuitBreakerWindowMillis="45000"
Use HTTP proxy (i.e. via Host header) for all outbound / forwarded requests
Type: string Default: null
Java Code:
ConfigurationProperties.forwardHttpProxy(String hostAndPort)
System Property:
-Dmockserver.forwardHttpProxy=...
Environment Variable:
MOCKSERVER_FORWARD_HTTP_PROXY=...
Property File:
mockserver.forwardHttpProxy=...
Example:
-Dmockserver.forwardHttpProxy="127.0.0.1:1090"
Use HTTPS proxy (i.e. HTTP CONNECT) for all outbound / forwarded requests, supports TLS tunnelling of HTTPS requests
Type: string Default: null
Java Code:
ConfigurationProperties.forwardHttpsProxy(String hostAndPort)
System Property:
-Dmockserver.forwardHttpsProxy=...
Environment Variable:
MOCKSERVER_FORWARD_HTTPS_PROXY=...
Property File:
mockserver.forwardHttpsProxy=...
Example:
-Dmockserver.forwardHttpsProxy="127.0.0.1:1090"
Use SOCKS proxy for all outbound / forwarded requests, support TLS tunnelling of TCP connections
Type: string Default: null
Java Code:
ConfigurationProperties.forwardSocksProxy(String hostAndPort)
System Property:
-Dmockserver.forwardSocksProxy=...
Environment Variable:
MOCKSERVER_FORWARD_SOCKS_PROXY=...
Property File:
mockserver.forwardSocksProxy=...
Example:
-Dmockserver.forwardSocksProxy="127.0.0.1:1090"
Username for proxy authentication when using HTTPS proxy (i.e. HTTP CONNECT) for all outbound / forwarded requests
Note: 8u111 Update Release Notes state that the Basic authentication scheme has been deactivated when setting up an HTTPS tunnel. To resolve this clear or set to an empty string the following system properties: jdk.http.auth.tunneling.disabledSchemes and jdk.http.auth.proxying.disabledSchemes.
Type: string Default: null
Java Code:
ConfigurationProperties.forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername)
System Property:
-Dmockserver.forwardProxyAuthenticationUsername=...
Environment Variable:
MOCKSERVER_FORWARD_PROXY_AUTHENTICATION_USERNAME=...
Property File:
mockserver.forwardProxyAuthenticationUsername=...
Example:
-Dmockserver.forwardProxyAuthenticationUsername=john.doe
Password for proxy authentication when using HTTPS proxy (i.e. HTTP CONNECT) for all outbound / forwarded requests
Note: 8u111 Update Release Notes state that the Basic authentication scheme has been deactivated when setting up an HTTPS tunnel. To resolve this clear or set to an empty string the following system properties: jdk.http.auth.tunneling.disabledSchemes and jdk.http.auth.proxying.disabledSchemes.
Type: string Default: null
Java Code:
ConfigurationProperties.forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword)
System Property:
-Dmockserver.forwardProxyAuthenticationPassword=...
Environment Variable:
MOCKSERVER_FORWARD_PROXY_AUTHENTICATION_PASSWORD=...
Property File:
mockserver.forwardProxyAuthenticationPassword=...
Example:
-Dmockserver.forwardProxyAuthenticationPassword="p@ssw0rd"
The authentication realm for proxy authentication to MockServer
Type: string Default: MockServer HTTP Proxy
Java Code:
ConfigurationProperties.proxyAuthenticationRealm(String proxyAuthenticationRealm)
System Property:
-Dmockserver.proxyAuthenticationRealm=...
Environment Variable:
MOCKSERVER_PROXY_SERVER_REALM=...
Property File:
mockserver.proxyAuthenticationRealm=...
Example:
-Dmockserver.proxyAuthenticationRealm="MockServer HTTP Proxy"
The required username for proxy authentication to MockServer
Note: 8u111 Update Release Notes state that the Basic authentication scheme has been deactivated when setting up an HTTPS tunnel. To resolve this clear or set to an empty string the following system properties: jdk.http.auth.tunneling.disabledSchemes and jdk.http.auth.proxying.disabledSchemes.
Type: string Default:
Java Code:
ConfigurationProperties.proxyAuthenticationUsername(String proxyAuthenticationUsername)
System Property:
-Dmockserver.proxyAuthenticationUsername=...
Environment Variable:
MOCKSERVER_PROXY_AUTHENTICATION_USERNAME=...
Property File:
mockserver.proxyAuthenticationUsername=...
Example:
-Dmockserver.proxyAuthenticationUsername=john.doe
The required password for proxy authentication to MockServer
Note: 8u111 Update Release Notes state that the Basic authentication scheme has been deactivated when setting up an HTTPS tunnel. To resolve this clear or set to an empty string the following system properties: jdk.http.auth.tunneling.disabledSchemes and jdk.http.auth.proxying.disabledSchemes.
Type: string Default:
Java Code:
ConfigurationProperties.proxyAuthenticationPassword(String proxyAuthenticationPassword)
System Property:
-Dmockserver.proxyAuthenticationPassword=...
Environment Variable:
MOCKSERVER_PROXY_AUTHENTICATION_PASSWORD=...
Property File:
mockserver.proxyAuthenticationPassword=...
Example:
-Dmockserver.proxyAuthenticationPassword="p@ssw0rd"
Configure reverse proxy mappings that route incoming requests by path prefix to upstream servers with automatic path rewriting. This provides Apache-style ProxyPass functionality.
Value is a JSON array of objects. Each object has:
Path rewriting example: with pathPrefix="/api/" and targetUri="https://backend:8443/services/", a request to GET /api/users/123 is forwarded as GET /services/users/123 to backend:8443 over HTTPS.
Mappings are evaluated in order; the first matching prefix wins. ProxyPass is evaluated after expectations and CORS, but before the speculative proxy attempt.
Type: JSON array Default: []
Java Code:
ConfigurationProperties.proxyPass("[{\"pathPrefix\":\"/api/\",\"targetUri\":\"https://backend:8443/services/\"}]")
System Property:
-Dmockserver.proxyPass=...
Environment Variable:
MOCKSERVER_PROXY_PASS=...
Property File:
mockserver.proxyPass=[{"pathPrefix":"/api/","targetUri":"https://backend:8443/services/"}]
Example:
MOCKSERVER_PROXY_PASS='[{"pathPrefix":"/api/","targetUri":"https://backend:8443/services/"},{"pathPrefix":"/auth/","targetUri":"http://auth-server:9090/","preserveHost":true}]'
Comma-separated list of hostnames that MockServer should not proxy to. When a request's Host header matches one of these hosts, MockServer will return a 404 instead of forwarding the request. This applies both to direct proxying and to upstream proxy bypass.
Supports exact hostnames (e.g. example.com), wildcard prefixes (e.g. *.internal.corp), and IP addresses (e.g. 192.168.1.1).
Type: string Default: ""
Java Code:
ConfigurationProperties.noProxyHosts(String noProxyHosts)
System Property:
-Dmockserver.noProxyHosts=...
Environment Variable:
MOCKSERVER_NO_PROXY_HOSTS=...
Property File:
mockserver.noProxyHosts=...
Example:
-Dmockserver.noProxyHosts="*.internal.corp,localhost,192.168.1.1"
If true (the default) the Host header will be automatically adjusted to match the target server when forwarding requests via HttpOverrideForwardedRequest or template-based forwards. This prevents HTTP 421 Misdirected Request errors when the target server validates Host headers.
If false the original Host header is preserved unless explicitly overridden in the request override.
Note: When an explicit Host header is provided in the request override, it is always preserved regardless of this setting. Similarly, when a template explicitly sets the Host header to a value different from the original request, it is preserved. Header changes made via requestModifier are still subject to auto-adjustment. This setting only applies when the Host header is not explicitly overridden and a socketAddress is specified for routing.
Type: boolean Default: true
Java Code:
ConfigurationProperties.forwardAdjustHostHeader(boolean enable)
System Property:
-Dmockserver.forwardAdjustHostHeader=...
Environment Variable:
MOCKSERVER_FORWARD_ADJUST_HOST_HEADER=...
Property File:
mockserver.forwardAdjustHostHeader=...
Example:
-Dmockserver.forwardAdjustHostHeader="false"
Set a default Host header value to use when forwarding requests. When set, the Host header will be overridden with this value for all forwarded requests, regardless of the target server's address. This is useful when the target proxy server routes requests based on the Host header.
Type: string Default: null
Java Code:
ConfigurationProperties.forwardDefaultHostHeader(String hostHeader)
System Property:
-Dmockserver.forwardDefaultHostHeader=...
Environment Variable:
MOCKSERVER_FORWARD_DEFAULT_HOST_HEADER=...
Property File:
mockserver.forwardDefaultHostHeader=...
Example:
-Dmockserver.forwardDefaultHostHeader="foo.com"
The hostname of the remote server to forward all unmatched requests to. When set together with proxyRemotePort, MockServer acts as a forward proxy, sending any request that does not match an expectation to the specified remote host. The Host header is automatically updated to match the configured remote host unless forwardDefaultHostHeader is set. This works in all deployment modes including WAR deployments.
Type: string Default: "" (unset)
Java Code:
ConfigurationProperties.proxyRemoteHost(String hostname)
System Property:
-Dmockserver.proxyRemoteHost=...
Environment Variable:
MOCKSERVER_PROXY_REMOTE_HOST=...
Property File:
mockserver.proxyRemoteHost=...
Example:
-Dmockserver.proxyRemoteHost="www.mock-server.com"
The port of the remote server to forward all unmatched requests to. Must be specified together with proxyRemoteHost. Valid values are 1-65535.
Type: integer Default: null
Java Code:
ConfigurationProperties.proxyRemotePort(Integer port)
System Property:
-Dmockserver.proxyRemotePort=...
Environment Variable:
MOCKSERVER_PROXY_REMOTE_PORT=...
Property File:
mockserver.proxyRemotePort=...
Example:
-Dmockserver.proxyRemotePort="443"
These properties optionally require authentication on the mocked endpoints (the data plane), separate from the control plane (/mockserver/*) and the HTTP CONNECT proxy. The feature is opt-in and off by default — when disabled (the default) MockServer behaves exactly as before and mocked endpoints are open.
When enabled, configure one or more schemes (HTTP Basic, Bearer token and/or API key). A request is accepted if it satisfies any one of the configured schemes. Requests with missing or wrong credentials receive 401 Unauthorized before the request reaches expectation matching. The control plane and the health/status/ready probes are not affected, so you can still administer a server whose data plane is locked down.
Fail-closed: if you set dataPlaneAuthenticationRequired=true but configure no scheme, every mocked request is rejected (rather than allowed) — this prevents a misconfiguration from silently leaving the data plane open.
Enable authentication of data-plane (mocked endpoint) requests. When true, every request to a mocked endpoint must present credentials matching one of the configured data-plane schemes; requests that do not are rejected with 401 Unauthorized. Control-plane requests, health/status/ready probes and CONNECT proxy requests are not affected.
Type: boolean Default: false
Java Code:
ConfigurationProperties.dataPlaneAuthenticationRequired(boolean enable)
System Property:
-Dmockserver.dataPlaneAuthenticationRequired=...
Environment Variable:
MOCKSERVER_DATA_PLANE_AUTHENTICATION_REQUIRED=...
Property File:
mockserver.dataPlaneAuthenticationRequired=...
Example:
-Dmockserver.dataPlaneAuthenticationRequired=true
The username required for data-plane HTTP Basic authentication. Basic is only active when both the username and password are set.
Type: string Default:
Java Code:
ConfigurationProperties.dataPlaneBasicAuthenticationUsername(String dataPlaneBasicAuthenticationUsername)
System Property:
-Dmockserver.dataPlaneBasicAuthenticationUsername=...
Environment Variable:
MOCKSERVER_DATA_PLANE_BASIC_AUTHENTICATION_USERNAME=...
Property File:
mockserver.dataPlaneBasicAuthenticationUsername=...
Example:
-Dmockserver.dataPlaneBasicAuthenticationUsername=john.doe
The password required for data-plane HTTP Basic authentication. Basic is only active when both the username and password are set.
Type: string Default:
Java Code:
ConfigurationProperties.dataPlaneBasicAuthenticationPassword(String dataPlaneBasicAuthenticationPassword)
System Property:
-Dmockserver.dataPlaneBasicAuthenticationPassword=...
Environment Variable:
MOCKSERVER_DATA_PLANE_BASIC_AUTHENTICATION_PASSWORD=...
Property File:
mockserver.dataPlaneBasicAuthenticationPassword=...
Example:
-Dmockserver.dataPlaneBasicAuthenticationPassword="p@ssw0rd"
The realm advertised in the WWW-Authenticate: Basic realm="..." challenge returned on a 401 when Basic is configured.
Type: string Default: MockServer
Java Code:
ConfigurationProperties.dataPlaneBasicAuthenticationRealm(String dataPlaneBasicAuthenticationRealm)
System Property:
-Dmockserver.dataPlaneBasicAuthenticationRealm=...
Environment Variable:
MOCKSERVER_DATA_PLANE_BASIC_AUTHENTICATION_REALM=...
Property File:
mockserver.dataPlaneBasicAuthenticationRealm=...
Example:
-Dmockserver.dataPlaneBasicAuthenticationRealm="My Mocked API"
The token required for data-plane Bearer authentication (Authorization: Bearer <token>). Bearer is active when this value is set.
Type: string Default:
Java Code:
ConfigurationProperties.dataPlaneBearerAuthenticationToken(String dataPlaneBearerAuthenticationToken)
System Property:
-Dmockserver.dataPlaneBearerAuthenticationToken=...
Environment Variable:
MOCKSERVER_DATA_PLANE_BEARER_AUTHENTICATION_TOKEN=...
Property File:
mockserver.dataPlaneBearerAuthenticationToken=...
Example:
-Dmockserver.dataPlaneBearerAuthenticationToken="eyJhbGciOi..."
The name of the header carrying the data-plane API key (e.g. X-API-Key). API-key authentication is only active when both the header name and the value are set.
Type: string Default:
Java Code:
ConfigurationProperties.dataPlaneApiKeyAuthenticationHeader(String dataPlaneApiKeyAuthenticationHeader)
System Property:
-Dmockserver.dataPlaneApiKeyAuthenticationHeader=...
Environment Variable:
MOCKSERVER_DATA_PLANE_API_KEY_AUTHENTICATION_HEADER=...
Property File:
mockserver.dataPlaneApiKeyAuthenticationHeader=...
Example:
-Dmockserver.dataPlaneApiKeyAuthenticationHeader="X-API-Key"
The expected value of the data-plane API-key header. API-key authentication is only active when both the header name and the value are set.
Type: string Default:
Java Code:
ConfigurationProperties.dataPlaneApiKeyAuthenticationValue(String dataPlaneApiKeyAuthenticationValue)
System Property:
-Dmockserver.dataPlaneApiKeyAuthenticationValue=...
Environment Variable:
MOCKSERVER_DATA_PLANE_API_KEY_AUTHENTICATION_VALUE=...
Property File:
mockserver.dataPlaneApiKeyAuthenticationValue=...
Example:
-Dmockserver.dataPlaneApiKeyAuthenticationValue="super-secret-key"
These properties control how MockServer handles streaming responses (Server-Sent Events with Content-Type: text/event-stream) when acting as a proxy. This is particularly relevant when proxying LLM API traffic from AI coding agents. See Inspect AI Agent Traffic for a full usage guide.
If true (the default) streaming responses (Server-Sent Events with Content-Type: text/event-stream) received while proxying are relayed to the client incrementally as they arrive, instead of being fully buffered before being forwarded. This keeps streaming APIs such as LLM APIs (Anthropic, OpenAI) responsive when proxied. Streaming is auto-detected from the Content-Type response header and does not affect non-streaming responses. Ordinary chunked responses (without text/event-stream) are always aggregated normally.
Set to false to revert to the previous behaviour of fully buffering every proxied response before forwarding it.
Type: boolean Default: true
Java Code:
ConfigurationProperties.streamingResponsesEnabled(boolean enable)
System Property:
-Dmockserver.streamingResponsesEnabled=...
Environment Variable:
MOCKSERVER_STREAMING_RESPONSES_ENABLED=...
Property File:
mockserver.streamingResponsesEnabled=...
Example:
-Dmockserver.streamingResponsesEnabled="false"
The maximum number of bytes of a streaming response body captured into the event log while relaying it. The full stream is always relayed to the client; this only bounds how much is retained for the dashboard Traffic Inspector and the retrieve API. Once this limit is exceeded, the logged body is truncated and the response is flagged with x-mockserver-stream-truncated: true. Increase this value if you need to capture full LLM completions longer than 256 KB.
Type: int Default: 262144 (256 KB)
Java Code:
ConfigurationProperties.maxStreamingCaptureBytes(int bytes)
System Property:
-Dmockserver.maxStreamingCaptureBytes=...
Environment Variable:
MOCKSERVER_MAX_STREAMING_CAPTURE_BYTES=...
Property File:
mockserver.maxStreamingCaptureBytes=...
Example:
-Dmockserver.maxStreamingCaptureBytes="524288"
The maximum inbound request body size (in bytes) that LLM conversation-aware matchers will parse when evaluating predicates such as whenLatestMessageContains or whenContainsToolResultFor. Requests larger than this value skip conversation-aware parsing entirely and are treated as no-match by those predicates, which protects the matcher from crafted JSON inputs designed to consume CPU or memory. Values outside the supported range are clamped at startup.
Type: int Default: 1048576 (1 MiB) Range: [16384, 67108864] (16 KiB – 64 MiB)
Java Code:
ConfigurationProperties.maxLlmConversationBodySize(int bytes)
System Property:
-Dmockserver.maxLlmConversationBodySize=...
Environment Variable:
MOCKSERVER_MAX_LLM_CONVERSATION_BODY_SIZE=...
Property File:
mockserver.maxLlmConversationBodySize=...
Example:
-Dmockserver.maxLlmConversationBodySize="2097152"
Some optional LLM features need MockServer to call a real LLM you already run — for example drift detection (replaying recorded fixtures against the live provider) and exploratory semantic prompt matching. These features are off unless a backend is configured, and they fail closed: if a configured backend times out or errors, the feature behaves exactly as if it were unconfigured and logs a single line. A real LLM call is never placed on the deterministic assertion/matching path.
A backend can be supplied three ways (simplest first):
Supported providers reuse the existing provider list: Anthropic, OpenAI, OpenAI Responses, Gemini, Azure OpenAI, Ollama, and Bedrock. Ollama is the easiest to start with — it needs no key and runs locally. The API key is a secret and is redacted (***) anywhere configuration is logged.
llmBackendsConfig takes the path of a backends JSON file, and the path is shown as you set it — the keys live in the file, which MockServer never returns. If you set the JSON document itself as the value instead, every apiKey in it is masked with ***REDACTED*** when the configuration is read back, and the rest of the document is shown so you can still see which backends are configured. A value that contains JSON but cannot be read as exactly one document is masked in full rather than shown, so nothing hidden inside it can leak. Sending a masked document back is safe, but if you rename or re-order a backend whose key you only ever saw masked, MockServer can no longer tell which key belongs to it — it then applies none of the document and logs a warning, rather than saving a backend with its key silently removed. Supply that backend's real key alongside the rename.
Type: String Default: unset (runtime-LLM features disabled)
Java Code:
ConfigurationProperties.llmProvider(String provider)
ConfigurationProperties.llmApiKey(String apiKey)
ConfigurationProperties.llmModel(String model)
ConfigurationProperties.llmBaseUrl(String baseUrl)
ConfigurationProperties.llmBackendsConfig(String jsonFilePath)
ConfigurationProperties.llmRequestTimeoutMillis(long millis)
System Property:
-Dmockserver.llmProvider=... -Dmockserver.llmApiKey=... -Dmockserver.llmModel=... -Dmockserver.llmBaseUrl=... -Dmockserver.llmBackendsConfig=... -Dmockserver.llmRequestTimeoutMillis=...
Environment Variable:
MOCKSERVER_LLM_PROVIDER=... MOCKSERVER_LLM_API_KEY=... MOCKSERVER_LLM_MODEL=... MOCKSERVER_LLM_BASE_URL=... MOCKSERVER_LLM_BACKENDS_CONFIG=... MOCKSERVER_LLM_REQUEST_TIMEOUT_MILLIS=...
Property File:
mockserver.llmProvider=OLLAMA
mockserver.llmRequestTimeoutMillis=30000
Example (OpenAI default backend):
-Dmockserver.llmProvider="OPENAI" -Dmockserver.llmApiKey="sk-..."
Exploratory semantic matching — opt in to the fuzzy, LLM-judged semanticMatch conversation predicate. Off by default and ignored unless a backend (above) also resolves. It calls a live model to judge intent, so it is non-deterministic and must never gate a CI assertion — use it for exploration only. Type: boolean Default: false
ConfigurationProperties.llmSemanticMatchingEnabled(boolean enabled)
-Dmockserver.llmSemanticMatchingEnabled=... MOCKSERVER_LLM_SEMANTIC_MATCHING_ENABLED=...
Approximate usage inference — when true, a mocked LLM completion that does not specify usage has approximate prompt_tokens / completion_tokens filled in (estimated from the request and response text). The counts are an estimate using a simple character/word heuristic, not a provider's exact token billing. Off by default so responses are unchanged unless you opt in; a completion that already specifies usage is never altered. Type: boolean Default: false
ConfigurationProperties.llmInferUsageEnabled(boolean enabled)
-Dmockserver.llmInferUsageEnabled=... MOCKSERVER_LLM_INFER_USAGE_ENABLED=...
Controls for recording LLM/MCP traffic to committable fixture files and replaying it deterministically (see the record_llm_fixtures and load_expectations_from_file MCP tools).
Body field redaction — comma-separated JSON field names whose values are redacted from recorded request/response bodies, in addition to the always-redacted sensitive headers. Empty by default.
Type: String Default: unset
Java Code:
ConfigurationProperties.fixtureBodyRedactFields(String commaSeparatedFields)
System Property:
-Dmockserver.fixtureBodyRedactFields=...
Environment Variable:
MOCKSERVER_FIXTURE_BODY_REDACT_FIELDS=...
Example:
-Dmockserver.fixtureBodyRedactFields="api_key,password,token"
Strict VCR mode — when true, loading a fixture registers a low-priority catch-all per cassette path so a request matching no recorded entry returns HTTP 599 rather than falling through. Useful for catching un-recorded calls in tests. Default false (can also be set per call via the load_expectations_from_file strict parameter).
Type: boolean Default: false
Java Code:
ConfigurationProperties.llmVcrStrict(boolean strict)
System Property:
-Dmockserver.llmVcrStrict=...
Environment Variable:
MOCKSERVER_LLM_VCR_STRICT=...
Example:
-Dmockserver.llmVcrStrict="true"
Optimisation report size limit — the maximum number of captured LLM calls included in an optimisation report or brief (the GET /mockserver/llm/optimisationReport endpoint and the export_optimisation_report MCP tool). Bounds the report size for very long sessions; the most recent calls are kept. Default 200.
Type: int Default: 200
Java Code:
ConfigurationProperties.llmOptimisationMaxCalls(int maxCalls)
System Property:
-Dmockserver.llmOptimisationMaxCalls=...
Environment Variable:
MOCKSERVER_LLM_OPTIMISATION_MAX_CALLS=...
Example:
-Dmockserver.llmOptimisationMaxCalls="500"
Controls for mock drift detection and semantic drift analysis. See Drift Detection for full details.
Drift detection enabled — the master switch for mock drift detection. When true (the default), MockServer compares each forwarded upstream response against any matching mock so it can detect when the real service has drifted away from your mocks. When false, this comparison is skipped entirely, which removes the small per-request overhead it adds — useful if you are proxying at high volume and do not need drift reporting.
Type: boolean Default: true
Java Code:
ConfigurationProperties.driftDetectionEnabled(boolean enabled)
System Property:
-Dmockserver.driftDetectionEnabled=...
Environment Variable:
MOCKSERVER_DRIFT_DETECTION_ENABLED=...
Example:
-Dmockserver.driftDetectionEnabled="false"
Drift sample rate — the fraction of forwarded responses to analyse for drift, between 0.0 and 1.0. The default 1.0 analyses every forwarded response. Lower it (for example 0.1 for 10%) to sample only a portion of traffic and reduce overhead when you are proxying at high volume but still want periodic drift signals. Values outside the range are clamped to the nearest bound. Has no effect when driftDetectionEnabled is false.
Type: double Default: 1.0
Java Code:
ConfigurationProperties.driftSampleRate(double rate)
System Property:
-Dmockserver.driftSampleRate=...
Environment Variable:
MOCKSERVER_DRIFT_SAMPLE_RATE=...
Example:
-Dmockserver.driftSampleRate="0.1"
Semantic drift analysis — when true and a runtime LLM backend is configured, each structural drift record is enriched with an LLM-classified severity (BREAKING, WARNING, or INFORMATIONAL) and a one-sentence explanation. Off by default (opt-in). Enrichment is best-effort: if the LLM is unavailable, drift records are stored with structural data only.
Type: boolean Default: false
Java Code:
ConfigurationProperties.driftSemanticAnalysisEnabled(boolean enabled)
System Property:
-Dmockserver.driftSemanticAnalysisEnabled=...
Environment Variable:
MOCKSERVER_DRIFT_SEMANTIC_ANALYSIS_ENABLED=...
Example:
-Dmockserver.driftSemanticAnalysisEnabled="true"
Performance drift threshold — p95 response time threshold in milliseconds. When set to a positive value, a PERFORMANCE drift record is emitted whenever the p95 response time for an expectation exceeds this threshold. MockServer tracks the last 100 response times per expectation in a sliding window. Set to 0 to disable.
Type: long Default: 0 (disabled)
Java Code:
ConfigurationProperties.driftResponseTimeThresholdMs(long thresholdMs)
System Property:
-Dmockserver.driftResponseTimeThresholdMs=...
Environment Variable:
MOCKSERVER_DRIFT_RESPONSE_TIME_THRESHOLD_MS=...
Example:
-Dmockserver.driftResponseTimeThresholdMs="500"
Drift alert webhook — when true and a URL is set, MockServer sends a fire-and-forget HTTP POST to that URL every time a drift of sufficient severity is detected, carrying the drift record as JSON. This lets a CI job, chat-ops bot, or alerting pipeline react immediately instead of polling GET /mockserver/drift. Off by default. The webhook is best-effort: a failed, slow, or unreachable endpoint never affects drift detection or the response returned to the client.
Type: boolean Default: false
Java Code:
ConfigurationProperties.driftAlertWebhookEnabled(boolean enabled)
System Property:
-Dmockserver.driftAlertWebhookEnabled=...
Environment Variable:
MOCKSERVER_DRIFT_ALERT_WEBHOOK_ENABLED=...
Example:
-Dmockserver.driftAlertWebhookEnabled="true"
Drift alert webhook URL — the URL the drift-alert webhook POSTs to. Empty by default; leaving it empty keeps the webhook off even when enabled. The POST body is a JSON envelope {"event":"mockserver.drift.alert","epochTimeMs":...,"severity":...,"drift":{...}}.
Type: string Default: "" (empty)
Java Code:
ConfigurationProperties.driftAlertWebhookUrl(String url)
System Property:
-Dmockserver.driftAlertWebhookUrl=...
Environment Variable:
MOCKSERVER_DRIFT_ALERT_WEBHOOK_URL=...
Example:
-Dmockserver.driftAlertWebhookUrl="https://hooks.example.com/mockserver-drift"
Drift alert severity threshold — the minimum severity at which a drift fires the webhook: BREAKING, WARNING, or INFORMATIONAL. BREAKING is the most severe and fires least often; INFORMATIONAL fires on every drift. When semantic drift analysis is off, severity is inferred structurally from the drift type (status-code and removed/changed-schema drifts are BREAKING, header changes are WARNING, additive changes are INFORMATIONAL).
Type: string Default: BREAKING
Java Code:
ConfigurationProperties.driftAlertSeverityThreshold(String severity)
System Property:
-Dmockserver.driftAlertSeverityThreshold=...
Environment Variable:
MOCKSERVER_DRIFT_ALERT_SEVERITY_THRESHOLD=...
Example:
-Dmockserver.driftAlertSeverityThreshold="WARNING"
Drift alert cooldown — de-duplication window in milliseconds. The same drift (same expectation, drift type, and field) fires the webhook at most once per window, so a drift that recurs on every request does not flood the endpoint. Default 60000 (60 seconds).
Type: long Default: 60000
Java Code:
ConfigurationProperties.driftAlertCooldownMillis(long cooldownMillis)
System Property:
-Dmockserver.driftAlertCooldownMillis=...
Environment Variable:
MOCKSERVER_DRIFT_ALERT_COOLDOWN_MILLIS=...
Example:
-Dmockserver.driftAlertCooldownMillis="30000"
An append-only, bounded, in-memory log of control-plane changes (such as registering or clearing expectations) so a shared MockServer can record who changed mock state, when, and from where. It is off by default, is not request/response traffic logging, and never stores request headers or bodies — only structural metadata with secrets redacted. Retrieve it with GET /mockserver/audit (optionally ?limit=<n>, default 200, capped at 1000).
Enabled — when true, each authorised control-plane change is recorded. When false (the default) nothing is recorded and control-plane behaviour is unchanged.
Type: boolean Default: false
Java Code:
ConfigurationProperties.controlPlaneAuditEnabled(boolean enabled)
System Property:
-Dmockserver.controlPlaneAuditEnabled=...
Environment Variable:
MOCKSERVER_CONTROL_PLANE_AUDIT_ENABLED=...
Example:
-Dmockserver.controlPlaneAuditEnabled="true"
Max entries — how many recent audit entries to keep; the oldest is dropped once the limit is reached. This value is read once when MockServer starts.
Type: int Default: 1000
Java Code:
ConfigurationProperties.controlPlaneAuditMaxEntries(int maxEntries)
System Property:
-Dmockserver.controlPlaneAuditMaxEntries=...
Environment Variable:
MOCKSERVER_CONTROL_PLANE_AUDIT_MAX_ENTRIES=...
Example:
-Dmockserver.controlPlaneAuditMaxEntries="5000"
Audit reads — when true, read-only control-plane requests (such as GET calls and /retrieve or /verify) are also recorded. By default only changes are recorded. Has no effect unless the audit log is enabled.
Type: boolean Default: false
Java Code:
ConfigurationProperties.controlPlaneAuditReads(boolean enabled)
System Property:
-Dmockserver.controlPlaneAuditReads=...
Environment Variable:
MOCKSERVER_CONTROL_PLANE_AUDIT_READS=...
Example:
-Dmockserver.controlPlaneAuditReads="true"
Audit log file — an optional path to a durable audit log file. When set (and the audit log is enabled), every recorded entry is also appended as one JSON object per line (newline-delimited JSON) to this file, giving a restart-surviving trail that outlives the in-memory log — which is bounded and is wiped by the very reset it records. Empty by default (the file sink is off and behaviour is unchanged). The path is resolved once, on the first entry written, and missing parent directories are created. The file grows append-only; use external log rotation (for example logrotate) if it needs to be capped. If the file cannot be opened or written, a single warning is logged and the file sink is disabled — request handling and the in-memory log are never affected.
Type: string Default: "" (off)
Java Code:
ConfigurationProperties.auditLogFile(String path)
System Property:
-Dmockserver.auditLogFile=...
Environment Variable:
MOCKSERVER_AUDIT_LOG_FILE=...
Example:
-Dmockserver.auditLogFile="/var/log/mockserver/audit.ndjson"
Require control-plane (admin) requests — such as registering, retrieving, or clearing expectations — to carry a valid OIDC Bearer JWT, verified against an external identity provider's published keys. This protects a shared MockServer so that only callers holding a token from your identity provider can change or read mock state. It is off by default, and applies only to the control-plane API, never to the mocked traffic MockServer serves on behalf of your application.
When enabled, each control-plane request must include an Authorization: Bearer <jwt> header. MockServer verifies the token's signature against the provider's JWKS, checks the issuer and/or audience, and (optionally) checks for required scopes. The verified subject (sub) is recorded as the principal in the control-plane audit log. At least one of issuer or audience must be configured.
Authentication required — when true, control-plane requests must carry a valid OIDC Bearer JWT verified against the provider's JWKS. When false (the default) no token is required and control-plane behaviour is unchanged.
Type: boolean Default: false
Java Code:
ConfigurationProperties.controlPlaneOidcAuthenticationRequired(boolean enabled)
System Property:
-Dmockserver.controlPlaneOidcAuthenticationRequired=...
Environment Variable:
MOCKSERVER_CONTROL_PLANE_OIDC_AUTHENTICATION_REQUIRED=...
Example:
-Dmockserver.controlPlaneOidcAuthenticationRequired="true"
Issuer — the expected token issuer (the iss claim). It is used to assert the issuer on incoming tokens and, if no JWKS URI is set, to discover the JWKS from the issuer's /.well-known/openid-configuration document.
Type: string Default: ""
Java Code:
ConfigurationProperties.controlPlaneOidcIssuer(String issuer)
System Property:
-Dmockserver.controlPlaneOidcIssuer=...
Environment Variable:
MOCKSERVER_CONTROL_PLANE_OIDC_ISSUER=...
Example:
-Dmockserver.controlPlaneOidcIssuer="https://login.example.com/"
JWKS URI — the JWKS endpoint used to fetch the public keys that verify control-plane token signatures. If left blank it is discovered from the issuer's OpenID configuration. For a remote host this must be an https URL.
Type: string Default: ""
Java Code:
ConfigurationProperties.controlPlaneOidcJwksUri(String jwksUri)
System Property:
-Dmockserver.controlPlaneOidcJwksUri=...
Environment Variable:
MOCKSERVER_CONTROL_PLANE_OIDC_JWKS_URI=...
Example:
-Dmockserver.controlPlaneOidcJwksUri="https://login.example.com/.well-known/jwks.json"
Audience — the expected token audience (the aud claim). At least one of issuer or audience must be configured for OIDC authentication to be valid.
Type: string Default: ""
Java Code:
ConfigurationProperties.controlPlaneOidcAudience(String audience)
System Property:
-Dmockserver.controlPlaneOidcAudience=...
Environment Variable:
MOCKSERVER_CONTROL_PLANE_OIDC_AUDIENCE=...
Example:
-Dmockserver.controlPlaneOidcAudience="mockserver-control-plane"
Required scopes — a comma- or space-separated list of scopes the token must contain to be accepted. When empty (the default) any validly-signed, in-audience token is accepted.
Type: string Default: ""
Java Code:
ConfigurationProperties.controlPlaneOidcRequiredScopes(Set<String> requiredScopes)
System Property:
-Dmockserver.controlPlaneOidcRequiredScopes=...
Environment Variable:
MOCKSERVER_CONTROL_PLANE_OIDC_REQUIRED_SCOPES=...
Example:
-Dmockserver.controlPlaneOidcRequiredScopes="mockserver.write,mockserver.read"
Scope claim — the JWT claim that carries the token's scopes (for example scope or roles), used when checking required scopes.
Type: string Default: scope
Java Code:
ConfigurationProperties.controlPlaneOidcScopeClaim(String scopeClaim)
System Property:
-Dmockserver.controlPlaneOidcScopeClaim=...
Environment Variable:
MOCKSERVER_CONTROL_PLANE_OIDC_SCOPE_CLAIM=...
Example:
-Dmockserver.controlPlaneOidcScopeClaim="roles"
Authorize control-plane operations against a scope-to-operation mapping, so fine-grained token scopes can gate individual admin actions (for example, allowing some callers to read mock state but not change it). This builds on Control-Plane OIDC Authentication — a verified principal is required — and is off by default.
Authorization enabled — when true, control-plane operations are authorized against the scope-to-operation mapping below. When false (the default) no per-operation authorization is applied.
Type: boolean Default: false
Java Code:
ConfigurationProperties.controlPlaneAuthorizationEnabled(boolean enabled)
System Property:
-Dmockserver.controlPlaneAuthorizationEnabled=...
Environment Variable:
MOCKSERVER_CONTROL_PLANE_AUTHORIZATION_ENABLED=...
Example:
-Dmockserver.controlPlaneAuthorizationEnabled="true"
Scope mapping — maps required scopes (or groups) to control-plane operations such as read and write, letting fine-grained scopes gate which admin actions a caller may perform. Has effect only when control-plane authorization is enabled.
Type: string Default: ""
Java Code:
ConfigurationProperties.controlPlaneScopeMapping(Map<String, ControlPlaneRole> scopeMapping)
System Property:
-Dmockserver.controlPlaneScopeMapping=...
Environment Variable:
MOCKSERVER_CONTROL_PLANE_SCOPE_MAPPING=...
Example:
-Dmockserver.controlPlaneScopeMapping="platform-admins=admin,qa-team=mutate,viewers=read"
Interactive breakpoints let you pause proxied or forwarded exchanges at four phases: request (before forwarding), response (after receiving from upstream), stream frame (each frame of a streaming response), and inbound frame (each client-to-server frame on a bidirectional connection). You can inspect, modify, continue, or abort the exchange via the callback WebSocket (or the dashboard Breakpoints panel). This is useful for debugging, manual testing, and step-through inspection of live traffic.
Breakpoints are activated by registering a request matcher via PUT /mockserver/breakpoint/matcher — there are no global on/off flags. An exchange pauses only when its request matches a registered breakpoint matcher for that phase. When no matchers are registered, breakpoints have zero overhead.
When a breakpoint-paused exchange is not resolved within the timeout, it is automatically continued. The breakpointMaxHeld cap prevents resource exhaustion — when the cap is reached, new exchanges bypass the breakpoint and proceed normally. The implementation is fully non-blocking: paused exchanges do not consume scheduler threads or event-loop threads while waiting for resolution.
See Interactive Breakpoints for the full matcher registration API and usage guide.
Timeout — maximum time in milliseconds an exchange or frame may be held at a breakpoint before it is automatically continued. Shared by request, response, stream frame, and inbound frame breakpoints. Default is 30000 (30 seconds).
Type: long Default: 30000
Java Code:
ConfigurationProperties.breakpointTimeoutMillis(long millis)
System Property:
-Dmockserver.breakpointTimeoutMillis=...
Environment Variable:
MOCKSERVER_BREAKPOINT_TIMEOUT_MILLIS=...
Max held — maximum number of exchanges (request + response combined) that can be simultaneously held at breakpoints. When this cap is reached, new exchanges bypass the breakpoint and proceed normally. Default is 50.
Type: int Default: 50
Java Code:
ConfigurationProperties.breakpointMaxHeld(int maxHeld)
System Property:
-Dmockserver.breakpointMaxHeld=...
Environment Variable:
MOCKSERVER_BREAKPOINT_MAX_HELD=...
Example (10-second timeout, max 20 held simultaneously):
-Dmockserver.breakpointTimeoutMillis="10000" -Dmockserver.breakpointMaxHeld="20"
A safety circuit-breaker for service-scoped chaos experiments. When enabled, MockServer counts error-class chaos faults — synthetic 5xx errors (error), dropped connections (drop), and quota-limit responses (quota) — in a sliding time window. If the count exceeds the configured threshold, all active service-scoped chaos profiles are automatically disabled, preventing a chaos experiment from causing cascading failures.
Benign fault types such as latency, slow, truncate, malformed, and graphql do not count toward the threshold. This means a latency-only chaos experiment will never auto-halt.
This provides the "steady-state guardrail" SREs expect: chaos experiments automatically stop if they produce too many destructive errors too quickly. The auto-halt state is reflected in the mock_server_active_service_chaos gauge (all values drop to 0) and a mock_server_chaos_auto_halt_total counter is incremented.
Enable chaos auto-halt — master switch for the circuit-breaker. Default is false (feature off — no overhead when disabled).
Type: boolean Default: false
Java Code:
ConfigurationProperties.chaosAutoHaltEnabled(boolean enable)
System Property:
-Dmockserver.chaosAutoHaltEnabled=...
Environment Variable:
MOCKSERVER_CHAOS_AUTO_HALT_ENABLED=...
Error threshold — the number of error-class chaos faults (5xx/dropped/quota) within the window that triggers the halt. Default is 50.
Type: long Default: 50
Java Code:
ConfigurationProperties.chaosAutoHaltErrorThreshold(long threshold)
System Property:
-Dmockserver.chaosAutoHaltErrorThreshold=...
Environment Variable:
MOCKSERVER_CHAOS_AUTO_HALT_ERROR_THRESHOLD=...
Window duration — the sliding window in milliseconds over which errors are counted. Default is 60000 (60 seconds).
Type: long Default: 60000
Java Code:
ConfigurationProperties.chaosAutoHaltWindowMillis(long millis)
System Property:
-Dmockserver.chaosAutoHaltWindowMillis=...
Environment Variable:
MOCKSERVER_CHAOS_AUTO_HALT_WINDOW_MILLIS=...
Example (halt chaos if more than 20 errors in 30 seconds):
-Dmockserver.chaosAutoHaltEnabled="true" -Dmockserver.chaosAutoHaltErrorThreshold="20" -Dmockserver.chaosAutoHaltWindowMillis="30000"
An expectation can carry a rateLimit clause that returns a deterministic 429 Too Many Requests (with Retry-After and X-RateLimit-* headers) once the matched requests exceed a limit, instead of the normal response. Each named limit (or, when no name is given, each expectation) keeps its own counter. This property caps how many such counters MockServer holds in memory at once.
Once the cap is reached, a request for a brand-new counter is allowed (fails open) rather than starting to reject traffic — so a large or unbounded set of rate-limit names can never exhaust memory or surprise you with unexpected throttling. The default of 10000 is comfortably high for normal use; raise it only if you genuinely use more than 10,000 distinct rate-limit names at once.
Type: int Default: 10000
Java Code:
ConfigurationProperties.rateLimitMaxNamedQuotas(int maxNamedQuotas)
System Property:
-Dmockserver.rateLimitMaxNamedQuotas=...
Environment Variable:
MOCKSERVER_RATE_LIMIT_MAX_NAMED_QUOTAS=...
Example expectation (fixed window — at most 100 requests per minute for one account):
{
"httpRequest": { "path": "/api/widgets" },
"httpResponse": { "statusCode": 200, "body": "ok" },
"rateLimit": {
"name": "widgets-account",
"algorithm": "fixed_window",
"limit": 100,
"windowMillis": 60000,
"retryAfter": "60"
}
}
Example expectation (token bucket — burst of 20, refilling 5 tokens per second):
{
"httpRequest": { "path": "/api/widgets" },
"httpResponse": { "statusCode": 200, "body": "ok" },
"rateLimit": {
"algorithm": "token_bucket",
"burst": 20,
"refillPerSecond": 5
}
}
Connection-lifecycle faults let you reproduce the failure patterns that appear when a server crashes mid-response or signals a graceful shutdown: a host-scoped mid-response TCP reset (resetMidResponse), a slow socket close (slowCloseDelay), and an HTTP/2 GOAWAY (http2GoAway), all registered via PUT /mockserver/tcpChaos. The same feature powers the preemption simulation (PUT /mockserver/preemption), which makes the server cordon itself — new data-plane requests are turned away (HTTP/1.1 gets 503 + Retry-After + Connection: close; HTTP/2 clients receive a GOAWAY) while in-flight requests drain — so you can test how your clients react to a Kubernetes node drain, Spot reclamation, or pre-SIGTERM sequence. It is a simulation only and never stops the server. Control-plane requests (/mockserver/...) are always exempt from the cordon.
Enable connection-lifecycle chaos — master switch for the mid-response RST / slow-close / HTTP/2 GOAWAY response-path faults and the preemption cordon. When false these faults are never applied and add no overhead. Default is true (the response path is byte-for-byte unchanged unless a fault is actually registered).
Type: boolean Default: true
Java Code:
ConfigurationProperties.connectionLifecycleChaosEnabled(boolean enable)
System Property:
-Dmockserver.connectionLifecycleChaosEnabled=...
Environment Variable:
MOCKSERVER_CONNECTION_LIFECYCLE_CHAOS_ENABLED=...
Preemption max drain — a safety hard cap (in milliseconds) applied to both the drain window and the TTL dead-man's-switch of a preemption simulation, so a mistaken value can never cordon the server for longer than this. Default is 86400000 (24 hours).
Type: long Default: 86400000
Java Code:
ConfigurationProperties.preemptionSimulationMaxDrainMillis(long millis)
System Property:
-Dmockserver.preemptionSimulationMaxDrainMillis=...
Environment Variable:
MOCKSERVER_PREEMPTION_SIMULATION_MAX_DRAIN_MILLIS=...
Count lifecycle RST toward auto-halt — when true, a mid-response TCP reset (resetMidResponse) is counted as a destructive fault toward the chaos auto-halt circuit-breaker, so a storm of mid-response resets can trip the breaker. The graceful signals (HTTP/2 GOAWAY and the preemption 503 cordon) are never counted. Set to false to exclude lifecycle resets from the breaker. Default is true.
Type: boolean Default: true
Java Code:
ConfigurationProperties.connectionLifecycleAutoHaltCountsRst(boolean enable)
System Property:
-Dmockserver.connectionLifecycleAutoHaltCountsRst=...
Environment Variable:
MOCKSERVER_CONNECTION_LIFECYCLE_AUTO_HALT_COUNTS_RST=...
Records a windowed sample (latency, error flag, scope, host) for each forwarded upstream round-trip so you can ask MockServer for a resilience verdict via PUT /mockserver/verifySLO. Post a set of objectives (for example "p95 latency < 500ms" or "error rate < 1%") and MockServer evaluates them against the recorded samples, returning PASS/FAIL/INCONCLUSIVE. This lets a test assert against observed proxy behaviour the same way it asserts against an SLO in production.
Sample tracking is off by default and is independent of metricsEnabled — you do not need Prometheus metrics to use SLO verdicts. The verifySLO endpoint returns 403 when tracking is disabled (a 400 means the criteria themselves are malformed), so enable it before verifying.
SLO Tracking Enabled — master switch that turns on in-process SLI sample tracking; required for PUT /mockserver/verifySLO. Default is false (feature off — the forward path records nothing).
Type: boolean Default: false
Java Code:
ConfigurationProperties.sloTrackingEnabled(boolean enable)
System Property:
-Dmockserver.sloTrackingEnabled=...
Environment Variable:
MOCKSERVER_SLO_TRACKING_ENABLED=...
Window Retention — the maximum age in milliseconds of retained SLI samples (the upper bound of the sliding window). Samples older than this relative to the newest sample are evicted, so verdicts reflect only recent behaviour. Lower this to evaluate a shorter window; raise it to keep more history. Default is 600000 (10 minutes).
Type: long Default: 600000
Java Code:
ConfigurationProperties.sloWindowRetentionMillis(long millis)
System Property:
-Dmockserver.sloWindowRetentionMillis=...
Environment Variable:
MOCKSERVER_SLO_WINDOW_RETENTION_MILLIS=...
Window Max Samples — the maximum number of SLI samples retained for verdict evaluation, bounding memory use. When the store is full the oldest sample is evicted. Lower this on memory-constrained deployments; raise it for high-throughput proxies where you need a larger sample set. Default is 50000.
Type: int Default: 50000
Java Code:
ConfigurationProperties.sloWindowMaxSamples(int maxSamples)
System Property:
-Dmockserver.sloWindowMaxSamples=...
Environment Variable:
MOCKSERVER_SLO_WINDOW_MAX_SAMPLES=...
Example (enable SLO tracking with a 5-minute window capped at 10000 samples):
-Dmockserver.sloTrackingEnabled="true" -Dmockserver.sloWindowRetentionMillis="300000" -Dmockserver.sloWindowMaxSamples="10000"
Lets MockServer drive load at a target on demand, organised as a registry of named load scenarios. You first load (register) a scenario by name with PUT /mockserver/loadScenario — this does not run it — then trigger one or many by name with PUT /mockserver/loadScenario/start to run them concurrently, each with its own optional start delay. A scenario is an ordered list of request steps fired through a sequence of stages (a load profile): each stage holds/ramps the concurrent virtual users (VU, closed model), holds/ramps an arrival rate in iterations per second (RATE, open model), or pauses. Ramp stages use a curve of LINEAR, QUADRATIC, or EXPONENTIAL. Per-iteration data variation is supported via templates (for example $iteration.index). MockServer reports per-scenario progress via GET /mockserver/loadScenario (list) / GET /mockserver/loadScenario/{name} and stops runs on PUT /mockserver/loadScenario/stop. The generated traffic feeds the same samples used by PUT /mockserver/verifySLO. Scenarios can be preloaded at startup from a JSON file. See Performance Testing / Load Injection for the full reference.
Loading is always allowed; triggering a run is off by default: PUT /mockserver/loadScenario/start returns 403 until you enable load generation, so MockServer never self-generates traffic unless asked. Even when enabled, hard caps plus a live in-flight limit and request-rate limit prevent a scenario from overloading the server.
Load Generation Enabled — master switch on triggering runs. When false, PUT /mockserver/loadScenario/start returns 403 (loading/registering is still allowed). Default is false.
Type: boolean Default: false
Java Code:
ConfigurationProperties.loadGenerationEnabled(boolean enable)
System Property:
-Dmockserver.loadGenerationEnabled=...
Environment Variable:
MOCKSERVER_LOAD_GENERATION_ENABLED=...
Suppress Event Log — keep the server's own load-generation traffic out of the request event log. When true (the default) requests generated by a load scenario are flagged with an in-process-only marker so they are skipped by the driver's bounded event log, leaving it free for the requests under test. The marker is never sent on the wire, so it cannot reach an upstream target and disable that target's logging. Set to false to record load-generation traffic in the driver's event log too. Default is true.
Type: boolean Default: true
ConfigurationProperties.loadGenerationSuppressEventLog(boolean suppress)
-Dmockserver.loadGenerationSuppressEventLog=... MOCKSERVER_LOAD_GENERATION_SUPPRESS_EVENT_LOG=...
Max Virtual Users — hard cap on the concurrent virtual users a scenario may drive; a profile asking for more is rejected. Default is 50.
Type: int Default: 50
ConfigurationProperties.loadGenerationMaxVirtualUsers(int maxVirtualUsers)
-Dmockserver.loadGenerationMaxVirtualUsers=... MOCKSERVER_LOAD_GENERATION_MAX_VIRTUAL_USERS=...
Max In-Flight Requests — hard cap on outstanding (not-yet-completed) requests, enforced live so a slow target cannot let the scenario queue unbounded work. Default is 200.
Type: int Default: 200
ConfigurationProperties.loadGenerationMaxInFlightRequests(int maxInFlightRequests)
-Dmockserver.loadGenerationMaxInFlightRequests=... MOCKSERVER_LOAD_GENERATION_MAX_IN_FLIGHT_REQUESTS=...
Max Requests Per Second — hard cap on dispatch rate, enforced live by a token bucket. Default is 500.
Type: int Default: 500
ConfigurationProperties.loadGenerationMaxRequestsPerSecond(int maxRequestsPerSecond)
-Dmockserver.loadGenerationMaxRequestsPerSecond=... MOCKSERVER_LOAD_GENERATION_MAX_REQUESTS_PER_SECOND=...
Max Duration — hard cap (milliseconds) on how long a scenario may run; a longer profile is rejected, so a forgotten scenario cannot drive traffic indefinitely. Default is 3600000 (1 hour).
Type: long Default: 3600000
ConfigurationProperties.loadGenerationMaxDurationMillis(long millis)
-Dmockserver.loadGenerationMaxDurationMillis=... MOCKSERVER_LOAD_GENERATION_MAX_DURATION_MILLIS=...
Max Steps — hard cap on the number of request steps a single scenario may define. Default is 50.
Type: int Default: 50
ConfigurationProperties.loadGenerationMaxSteps(int maxSteps)
-Dmockserver.loadGenerationMaxSteps=... MOCKSERVER_LOAD_GENERATION_MAX_STEPS=...
Max Rate — hard cap on the arrival rate (iterations per second) a RATE stage may request; a faster stage is rejected at validation. Default is 5000.
Type: double Default: 5000
ConfigurationProperties.loadGenerationMaxRate(double maxRate)
-Dmockserver.loadGenerationMaxRate=... MOCKSERVER_LOAD_GENERATION_MAX_RATE=...
Max Stages — hard cap on the number of stages a single load profile may define. Default is 20.
Type: int Default: 20
ConfigurationProperties.loadGenerationMaxStages(int maxStages)
-Dmockserver.loadGenerationMaxStages=... MOCKSERVER_LOAD_GENERATION_MAX_STAGES=...
Max Concurrent Scenarios — hard cap on how many load scenarios may be active (PENDING or RUNNING) at once; a start trigger that would exceed it is rejected. Loading/registering scenarios is not limited — only how many may run together. Default is 10.
Type: int Default: 10
ConfigurationProperties.loadGenerationMaxConcurrentScenarios(int maxConcurrentScenarios)
-Dmockserver.loadGenerationMaxConcurrentScenarios=... MOCKSERVER_LOAD_GENERATION_MAX_CONCURRENT_SCENARIOS=...
Load Scenario Initialization JSON Path — path to a JSON file containing an array of load scenario definitions. At startup each is loaded (registered) into the registry in the LOADED state — staged and ready to be triggered by name, but not running. Empty by default (no preloading). Mirrors initializationJsonPath for expectations.
Type: string Default: "" (empty)
ConfigurationProperties.loadScenarioInitializationJsonPath(String path)
-Dmockserver.loadScenarioInitializationJsonPath=... MOCKSERVER_LOAD_SCENARIO_INITIALIZATION_JSON_PATH=...
Example (enable load generation with a lower concurrency ceiling):
-Dmockserver.loadGenerationEnabled="true" -Dmockserver.loadGenerationMaxVirtualUsers="20" -Dmockserver.loadGenerationMaxRequestsPerSecond="200"
When enabled (alongside metricsEnabled), MockServer parses forwarded LLM responses to extract token usage and estimated cost, incrementing Prometheus counters labeled by provider and model. The parse is the same one used for GenAI span export; enabling this property activates the forward-path response parse even when OTLP tracing is off.
Three new Prometheus counters are registered: mock_server_llm_input_tokens, mock_server_llm_output_tokens, and mock_server_llm_cost_usd, each labeled by provider and model. The cost counter uses estimated provider pricing; treat the total as an estimate, not an invoice.
LLM Metrics Enabled — enable LLM token and cost metrics collection. Default is false to avoid parsing forwarded response bodies unless asked.
Type: boolean Default: false
ConfigurationProperties.llmMetricsEnabled(boolean enabled)
-Dmockserver.llmMetricsEnabled=... MOCKSERVER_LLM_METRICS_ENABLED=...
LLM Cost Budget — set a cumulative LLM cost budget in USD. When the cumulative cost of all LLM completions (mocked and forwarded) exceeds this budget, further LLM forwarding on all paths (matched forward expectations, breakpoint continuations, unmatched proxy-pass, and proxyPassMappings reverse-proxy routes) is blocked with a 429 response. Non-LLM forwards are unaffected. The budget is fail-open: negative, unset, or malformed values never block traffic. Trip events are visible in the dashboard Circuit Breakers section and the mock_server_llm_cost_budget_tripped Prometheus counter. Reset on server reset.
Type: double Default: -1.0 (disabled)
ConfigurationProperties.llmCostBudgetUsd(double budgetUsd)
-Dmockserver.llmCostBudgetUsd=... MOCKSERVER_LLM_COST_BUDGET_USD=...
Example (enable metrics and set a $10 cost budget):
-Dmockserver.metricsEnabled="true" -Dmockserver.llmMetricsEnabled="true" -Dmockserver.llmCostBudgetUsd="10.0"
When enabled (alongside metricsEnabled), MockServer registers a Prometheus counter mock_server_expectation_matched with an expectation_id label and increments it each time an expectation is matched and a response is served. This lets you track which expectations are hot and which are never hit.
This is off by default because each active expectation adds one Prometheus label value, so cardinality grows with the number of registered expectations. In long-running deployments with many expectations, enable only when you need per-expectation visibility. In CI or short-lived test runs with a bounded, small number of expectations, cardinality is not a concern.
The counter appears in the scrape output as mock_server_expectation_matched_total{expectation_id="..."}.
Type: boolean Default: false
Java Code:
ConfigurationProperties.perExpectationMetricsEnabled(boolean enabled)
System Property:
-Dmockserver.perExpectationMetricsEnabled=...
Environment Variable:
MOCKSERVER_PER_EXPECTATION_METRICS_ENABLED=...
Example:
-Dmockserver.metricsEnabled="true" -Dmockserver.perExpectationMetricsEnabled="true"
The legacy -Dmockserver.perExpectationMetrics / MOCKSERVER_PER_EXPECTATION_METRICS form is still accepted for backward compatibility.
Threshold in milliseconds for flagging slow forwarded requests. When a forwarded request's total time exceeds this threshold, MockServer emits a WARN-level log entry identifying the slow request and increments the mock_server_slow_requests_total Prometheus counter (visible when metricsEnabled is on). This makes it easy to spot upstreams that are responding slowly without trawling the full event log.
This is off by default (threshold 0, no requests flagged). Set it to the latency above which a forwarded request should be considered slow for your environment.
Type: long Default: 0 (disabled)
Java Code:
ConfigurationProperties.slowRequestThresholdMillis(long milliseconds)
System Property:
-Dmockserver.slowRequestThresholdMillis=...
Environment Variable:
MOCKSERVER_SLOW_REQUEST_THRESHOLD_MILLIS=...
Example:
-Dmockserver.slowRequestThresholdMillis="2000"
When enabled (alongside metricsEnabled), MockServer registers an additional histogram mock_server_request_duration_by_method_seconds with a method label for the HTTP method (GET, POST, etc.), alongside the unlabelled mock_server_request_duration_seconds. This lets you break request-latency percentiles down per HTTP method.
This is off by default. Cardinality is bounded to the set of standard HTTP methods, so enabling it adds only a small, fixed number of label values.
Type: boolean Default: false
Java Code:
ConfigurationProperties.metricsRequestDurationRouteLabels(boolean enable)
System Property:
-Dmockserver.metricsRequestDurationRouteLabels=...
Environment Variable:
MOCKSERVER_METRICS_REQUEST_DURATION_ROUTE_LABELS=...
Example:
-Dmockserver.metricsEnabled="true" -Dmockserver.metricsRequestDurationRouteLabels="true"
When MockServer records traffic as a proxy, the recorded expectations contain the exact headers that were sent — including credentials such as Authorization (bearer / token values), Cookie, Set-Cookie, x-api-key and api-key. When this setting is enabled, MockServer masks those header values with ***REDACTED*** before the recorded expectations are returned. Because this applies on the recorded-expectation retrieval path, it covers retrieving recordings as JSON, generating client code from recordings, and persisting recordings to disk — so proxied secrets do not leak into shared recordings, generated code, or saved files.
This is off by default. Enabling it has a trade-off: a recorded expectation whose credential has been masked can no longer be replayed against an upstream that requires that credential. Enable it when you want to share or store recordings safely; leave it off when you need recordings to replay against a protected upstream unchanged.
Type: boolean Default: false
Java Code:
ConfigurationProperties.redactSecretsInRecordedExpectations(boolean enable)
System Property:
-Dmockserver.redactSecretsInRecordedExpectations=...
Environment Variable:
MOCKSERVER_REDACT_SECRETS_IN_RECORDED_EXPECTATIONS=...
Example:
-Dmockserver.redactSecretsInRecordedExpectations="true"
When MockServer records traffic as a proxy, the recorded expectations match the exact values that were captured. A recording pinned to a specific request id, session token or timestamp will not match the next request, making recordings brittle and over-specific. By default the recorded-expectation post-processor (enabled with deduplicateRecordedExpectations) only generalizes id-like path segments (e.g. /users/1 → /users/{id}).
When this setting is enabled in addition to deduplicateRecordedExpectations, the post-processor also generalizes volatile-looking query parameter, header and JSON body values into matchers: UUIDs, long numeric ids, ISO-8601 dates / date-times, epoch-millisecond timestamps, JWTs and long opaque tokens (base64 / hex) are replaced with a regex matcher (.+ for query/header values, a ${json-unit.regex} placeholder for JSON body leaves). Known-credential header names (Authorization, Cookie, x-api-key, correlation-id headers, …) are always generalized when present.
It is deliberately conservative: stable values — short strings, words, booleans, small numbers such as a page size or status code, common content-types — are kept verbatim, so a recording is generalized only where it would otherwise be too specific to replay.
This is off by default and has no effect unless deduplicateRecordedExpectations is also enabled. Enable it when you want recordings that replay against future traffic; leave it off when you need recordings to match the exact captured values.
Type: boolean Default: false
Java Code:
ConfigurationProperties.templatizeRecordedValues(boolean enable)
System Property:
-Dmockserver.templatizeRecordedValues=...
Environment Variable:
MOCKSERVER_TEMPLATIZE_RECORDED_VALUES=...
Example:
-Dmockserver.deduplicateRecordedExpectations="true" -Dmockserver.templatizeRecordedValues="true"
The live event log — the entries returned by retrieveLogMessages / retrieveRecordedRequests and the request / response panes shown in the dashboard — normally includes the exact headers seen for each request and response, including credentials such as Authorization (bearer / token values), Proxy-Authorization, Cookie, Set-Cookie, x-api-key and api-key. When this setting is enabled, MockServer masks those header values with ***REDACTED*** wherever the log is displayed or retrieved, so secrets do not leak into a shared dashboard or an exported log. JSON body fields you list in fixtureBodyRedactFields are masked in the log too.
Redaction is applied only to the copies shown / returned — request matching and verification still see the original, unmasked values, so turning this on does not change which expectations match or how verification behaves.
This is off by default so the event log is unchanged. It complements redactSecretsInRecordedExpectations (which masks secrets on the recorded-expectation export path); enable both when you want secrets masked everywhere they could be observed.
Type: boolean Default: false
Java Code:
ConfigurationProperties.redactSecretsInLog(boolean enable)
System Property:
-Dmockserver.redactSecretsInLog=...
Environment Variable:
MOCKSERVER_REDACT_SECRETS_IN_LOG=...
Example:
-Dmockserver.redactSecretsInLog="true"
Master kill switch for the dashboard's anonymous usage analytics. When set to false, the analytics module never loads — no PostHog chunk is fetched, no events are sent, and the consent banner is suppressed. Use this to disable analytics across an entire deployment regardless of any other configuration.
Analytics is also inactive unless dashboardAnalyticsEndpoint and dashboardAnalyticsKey are both set to non-empty values, so setting this switch alone has no effect unless an endpoint and key are also provided.
Type: boolean Default: true
System Property:
-Dmockserver.dashboardAnalyticsEnabled=...
Environment Variable:
MOCKSERVER_DASHBOARD_ANALYTICS_ENABLED=...
Example (disable globally):
-Dmockserver.dashboardAnalyticsEnabled="false"
The base URL of a self-hosted PostHog instance to which anonymous dashboard usage events are sent (the PostHog api_host value, for example https://posthog.example.com). When this property is blank or absent, analytics is disabled regardless of the other analytics settings. MockServer never uses the PostHog cloud endpoint by default — an operator must explicitly supply their own self-hosted endpoint.
Type: string Default: "" (analytics disabled)
System Property:
-Dmockserver.dashboardAnalyticsEndpoint=...
Environment Variable:
MOCKSERVER_DASHBOARD_ANALYTICS_ENDPOINT=...
Example:
-Dmockserver.dashboardAnalyticsEndpoint="https://posthog.example.com"
The PostHog write-only project API key for the self-hosted instance identified by dashboardAnalyticsEndpoint. When this property is blank or absent, analytics is disabled. The key is transmitted to the dashboard browser as part of the server configuration and is used only to authenticate with the PostHog ingest API — it cannot read or export any data.
Type: string Default: "" (analytics disabled)
System Property:
-Dmockserver.dashboardAnalyticsKey=...
Environment Variable:
MOCKSERVER_DASHBOARD_ANALYTICS_KEY=...
Example:
-Dmockserver.dashboardAnalyticsKey="phc_xxxxxxxxxxxxxxxxxxxx"
A label that identifies which MockServer artefact produced an analytics event. It is sent as the distribution property on every app_open event and is chosen from a closed allow-list; any value not on the list is normalised to unknown before sending.
The official MockServer artefacts set this automatically — you do not need to configure it yourself:
The plain downloadable JAR and embedded / library use leave this property empty and send no analytics at all. Most users will never need to set this property.
Type: string Default: "" (unset)
System Property:
-Dmockserver.dashboardAnalyticsDistribution=...
Environment Variable:
MOCKSERVER_DASHBOARD_ANALYTICS_DISTRIBUTION=...
Example:
-Dmockserver.dashboardAnalyticsDistribution="binary"
MockServer can export to an OpenTelemetry (OTLP) collector, in two independent parts that are each off by default and fail-soft (a startup error logs one line and never stops the server or affects a response). Both use the OTLP HTTP/protobuf exporter with the JDK HTTP client (no gRPC/OkHttp) and share the same endpoint.
1. Metrics export — push MockServer's explicitly-defined metrics (request counts, expectation-match counts, action counts including the LLM and chaos counters) to OTLP, as an alternative to the Prometheus endpoint. Implemented as observable gauges reading the current values, so the Prometheus and OTLP views stay consistent. It does not add tracing or automatic instrumentation.
Type: boolean Default: false
ConfigurationProperties.otelMetricsEnabled(boolean enabled)
-Dmockserver.otelMetricsEnabled=... MOCKSERVER_OTEL_METRICS_ENABLED=...
Export interval (seconds), default 60:
-Dmockserver.otelMetricsExportIntervalSeconds=... MOCKSERVER_OTEL_METRICS_EXPORT_INTERVAL_SECONDS=...
Aggregation temporality — how counter and histogram values are reported over OTLP: cumulative (the default, a running total) or delta (only the change since the last export). Choose delta for backends such as New Relic that prefer it — delta metrics do not require the backend to track a separate running total per pod/instance, which reduces the number of time series. Only affects OTLP export (the Prometheus endpoint is always cumulative); any unrecognised value falls back to cumulative.
-Dmockserver.otelMetricsTemporality="delta" MOCKSERVER_OTEL_METRICS_TEMPORALITY=delta
2. GenAI span export — emit one OpenTelemetry GenAI semantic-convention span per LLM completion MockServer serves or forwards/proxies, carrying provider (gen_ai.system), model, token usage and finish reason. When MockServer forwards traffic to an upstream LLM provider (matched-expectation forward or unmatched proxy-pass), it detects the provider from the target host and emits a GenAI span for the upstream response. These are spans MockServer codes deliberately — no auto-instrumentation is added.
Type: boolean Default: false
ConfigurationProperties.otelTracesEnabled(boolean enabled)
-Dmockserver.otelTracesEnabled=... MOCKSERVER_OTEL_TRACES_ENABLED=...
OTLP endpoint (shared) — the collector base URL (e.g. http://localhost:4318); the /v1/metrics and /v1/traces paths are appended per signal.
ConfigurationProperties.otelEndpoint(String baseUrl)
-Dmockserver.otelEndpoint=... MOCKSERVER_OTEL_ENDPOINT=...
When this property is not set (a blank or whitespace-only MOCKSERVER_OTEL_ENDPOINT env var is treated as unset), the OpenTelemetry-standard OTEL_EXPORTER_OTLP_ENDPOINT environment variable is honoured as a fallback — the MockServer-specific value always takes precedence. When neither this property nor the standard OTEL_EXPORTER_OTLP_ENDPOINT is set, the empty value causes the OTel SDK to fall back to its default (http://localhost:4318).
Example (both signals to a collector):
-Dmockserver.otelMetricsEnabled="true" -Dmockserver.otelTracesEnabled="true" -Dmockserver.otelEndpoint="http://otel-collector:4318"
3. W3C Trace Context propagation — extract the W3C traceparent and tracestate headers from incoming requests and optionally copy them to mock responses. This lets callers correlate request-response pairs within a distributed trace when MockServer sits in a service mesh or test harness. The handler is always present in the pipeline but is a no-op unless enabled.
Propagate trace context to responses — when enabled, the traceparent (and tracestate, if present) headers from the incoming request are added to the mock response.
Type: boolean Default: false
ConfigurationProperties.otelPropagateTraceContext(boolean enabled)
-Dmockserver.otelPropagateTraceContext=... MOCKSERVER_OTEL_PROPAGATE_TRACE_CONTEXT=...
Generate trace ID — when enabled, MockServer generates a new random W3C trace ID for incoming requests that do not carry a traceparent header. Useful for test harnesses that want every request to have a trace context.
Type: boolean Default: false
ConfigurationProperties.otelGenerateTraceId(boolean enabled)
-Dmockserver.otelGenerateTraceId=... MOCKSERVER_OTEL_GENERATE_TRACE_ID=...
Example (propagate trace context and generate IDs for untraced requests):
-Dmockserver.otelPropagateTraceContext="true" -Dmockserver.otelGenerateTraceId="true"
Instead of (or as well as) being scraped at /mockserver/metrics, MockServer can push the very same metrics to a Prometheus Remote-Write endpoint on an interval. This suits short-lived pods and agentless setups, and works with Prometheus (started with --web.enable-remote-write-receiver), Grafana Cloud / Mimir, New Relic, VictoriaMetrics and Thanos Receive. It is off by default and fail-soft — a push failure logs one line and never affects request handling. The pushed series are exactly what the scrape endpoint serves (the whole registry); remote write is always cumulative (the Prometheus model).
Enable — turn on the periodic push.
Type: boolean Default: false
ConfigurationProperties.prometheusRemoteWriteEnabled(boolean enabled)
-Dmockserver.prometheusRemoteWriteEnabled=... MOCKSERVER_PROMETHEUS_REMOTE_WRITE_ENABLED=...
Endpoint URL — the full remote-write URL to POST to (e.g. http://prometheus:9090/api/v1/write). Required when enabled; if left blank, a warning is logged and nothing is pushed.
ConfigurationProperties.prometheusRemoteWriteUrl(String url)
-Dmockserver.prometheusRemoteWriteUrl=... MOCKSERVER_PROMETHEUS_REMOTE_WRITE_URL=...
Protocol version — v1 (default, universally supported) or v2. v2 interns labels into a symbol table and carries per-series metadata; use it only if your receiver supports Remote-Write 2.0. Any unrecognised value falls back to v1.
-Dmockserver.prometheusRemoteWriteProtocolVersion="v2" MOCKSERVER_PROMETHEUS_REMOTE_WRITE_PROTOCOL_VERSION=v2
Push interval (seconds), default 60, minimum 1:
-Dmockserver.prometheusRemoteWriteIntervalSeconds=... MOCKSERVER_PROMETHEUS_REMOTE_WRITE_INTERVAL_SECONDS=...
Authentication — most hosted endpoints require it. A bearer token is used if set (it wins over basic auth); otherwise HTTP basic auth (username + password); then any custom headers are applied last (so a custom Authorization header can override). Credential values are never logged.
-Dmockserver.prometheusRemoteWriteBearerToken=... MOCKSERVER_PROMETHEUS_REMOTE_WRITE_BEARER_TOKEN=...
-Dmockserver.prometheusRemoteWriteBasicAuthUsername=... MOCKSERVER_PROMETHEUS_REMOTE_WRITE_BASIC_AUTH_USERNAME=...
-Dmockserver.prometheusRemoteWriteBasicAuthPassword=... MOCKSERVER_PROMETHEUS_REMOTE_WRITE_BASIC_AUTH_PASSWORD=...
Custom headers — extra HTTP headers as a comma-separated key=value list, for tenant/API-key headers such as New Relic's Api-Key or Grafana Mimir's X-Scope-OrgID:
-Dmockserver.prometheusRemoteWriteHeaders="Api-Key=NRAK-xxxx,X-Scope-OrgID=tenant-a" MOCKSERVER_PROMETHEUS_REMOTE_WRITE_HEADERS=...
Reading the configuration back with GET /mockserver/configuration masks the value of any credential-bearing header (Authorization, Api-Key, X-Auth-Token and similar) with ***REDACTED***; every other header is returned exactly as you set it, so the example above reads back as Api-Key=***REDACTED***,X-Scope-OrgID=tenant-a. Sending that masked list straight back with PUT /mockserver/configuration is safe — the masked header keeps the real value MockServer already holds, while any header you edited is applied normally.
When you edit a masked header list, leave each ***REDACTED*** exactly as it was returned — you may rename, add, remove and re-order the other headers freely. To replace a credential, type the new value on its own in place of the whole ***REDACTED***; do not type it next to the mask.
If MockServer cannot work out which real value a ***REDACTED*** stands for, it applies none of the header list, logs a warning saying so, and keeps the headers it already holds. It will neither send the text ***REDACTED*** to your metrics endpoint as a credential nor quietly drop the header and leave you with no credential at all. If a header list you sent does not appear to have taken effect, check the log for that warning. That happens when:
Example (push to a local Prometheus every 15s):
-Dmockserver.metricsEnabled="true" -Dmockserver.prometheusRemoteWriteEnabled="true" -Dmockserver.prometheusRemoteWriteUrl="http://localhost:9090/api/v1/write" -Dmockserver.prometheusRemoteWriteIntervalSeconds="15"
The maximum time in seconds a streaming response connection may be idle (no chunk received from the upstream server) before MockServer closes it and logs the captured portion as truncated. This replaces the fixed global socket timeout for streaming responses, which would otherwise terminate long-lived LLM completions. The timeout resets on every chunk received, so a slow-but-active stream is never cut off prematurely.
Set to 0 to disable the idle bound entirely: a stream is then never closed for inactivity. Use with care — this removes the only inactivity limit on a streaming connection, so a stalled upstream that stops sending chunks will hold the connection open indefinitely.
Type: int Default: 60 (seconds)
Java Code:
ConfigurationProperties.streamIdleTimeoutSeconds(int seconds)
System Property:
-Dmockserver.streamIdleTimeoutSeconds=...
Environment Variable:
MOCKSERVER_STREAM_IDLE_TIMEOUT_SECONDS=...
Property File:
mockserver.streamIdleTimeoutSeconds=...
Example:
-Dmockserver.streamIdleTimeoutSeconds="120"
Adds a fixed delay (in milliseconds) to all matched expectation responses. This delay is additive — it combines with any per-action delay configured on individual expectations. For example, if an expectation has a 100ms delay and the global delay is 200ms, the total delay is 300ms.
This is useful for simulating network latency across all mocked endpoints without having to configure delay on each expectation individually.
Type: long Default: null (no global delay)
Java Code:
ConfigurationProperties.globalResponseDelayMillis(Long millis)
System Property:
-Dmockserver.globalResponseDelayMillis=...
Environment Variable:
MOCKSERVER_GLOBAL_RESPONSE_DELAY_MILLIS=...
Property File:
mockserver.globalResponseDelayMillis=...
Example:
-Dmockserver.globalResponseDelayMillis="200"
On shutdown (via PUT /mockserver/stop or ClientAndServer.stop()), MockServer stops accepting new connections and then waits up to this many milliseconds for in-flight requests that are already being processed to complete before tearing down the Netty event loops. If the timeout elapses before all in-flight requests finish, a WARN log entry is written with the number of requests still in progress, and shutdown proceeds anyway. Set to 0 to disable draining and stop immediately (the pre-7.2 behaviour).
Type: long Default: 15000
Java Code:
ConfigurationProperties.stopDrainMillis(long millis)
System Property:
-Dmockserver.stopDrainMillis=...
Environment Variable:
MOCKSERVER_STOP_DRAIN_MILLIS=...
Example (disable drain — stop immediately):
-Dmockserver.stopDrainMillis="0"
Path to support HTTP GET requests for status response (also available on PUT /mockserver/status).
If this value is not modified then only PUT /mockserver/status but is a none blank value is provided for this value then GET requests to this path will return the 200 Ok status response showing the MockServer version and bound ports.
A GET request to this path will be matched before any expectation matching or proxying of requests.
Type: string Default: ""
Java Code:
ConfigurationProperties.livenessHttpGetPath(String livenessPath)
System Property:
-Dmockserver.livenessHttpGetPath=...
Environment Variable:
MOCKSERVER_LIVENESS_HTTP_GET_PATH=...
Property File:
mockserver.livenessHttpGetPath=...
Example:
-Dmockserver.livenessHttpGetPath="/liveness/probe"
Lets multiple teams or test-suites share a single MockServer instance without their expectations colliding, by partitioning expectations into named namespaces (tenants).
Give an expectation an optional namespace field. A request then chooses its namespace by sending this header. A request in namespace T matches expectations whose namespace is T plus all global (no-namespace) expectations — and never another team's. A request with no namespace header matches only global expectations, so isolation is the safe default.
You can also clear or retrieve just one tenant's expectations: PUT /mockserver/clear?type=expectations&namespace=T removes only namespace T's expectations (leaving others intact), and PUT /mockserver/retrieve?type=active_expectations&namespace=T returns only that tenant's expectations plus global ones. Both also accept the namespace as the header instead of the query parameter.
This feature is fully backward compatible: if you never set a namespace on any expectation, matching behaves exactly as before.
Type: string Default: "X-MockServer-Namespace"
Java Code:
ConfigurationProperties.matchNamespaceHeader(String matchNamespaceHeader)
System Property:
-Dmockserver.matchNamespaceHeader=...
Environment Variable:
MOCKSERVER_MATCH_NAMESPACE_HEADER=...
Property File:
mockserver.matchNamespaceHeader=...
Example:
-Dmockserver.matchNamespaceHeader="X-Tenant"
A path prefix to add to all paths generated from OpenAPI specifications. For example, if set to /api/v1 then a path /pets from the spec becomes /api/v1/pets.
Type: string Default: "" (empty string)
Java Code:
ConfigurationProperties.openAPIContextPathPrefix(String openAPIContextPathPrefix)
System Property:
-Dmockserver.openAPIContextPathPrefix=...
Environment Variable:
MOCKSERVER_OPENAPI_CONTEXT_PATH_PREFIX=...
Property File:
mockserver.openAPIContextPathPrefix=...
Example:
-Dmockserver.openAPIContextPathPrefix="/api/v1"
If enabled, MockServer validates that mock responses conform to the OpenAPI spec schema they were generated from. Validation is advisory only - responses are still returned to the client even if validation fails.
Type: boolean Default: false
Java Code:
ConfigurationProperties.openAPIResponseValidation(boolean enable)
System Property:
-Dmockserver.openAPIResponseValidation=...
Environment Variable:
MOCKSERVER_OPENAPI_RESPONSE_VALIDATION=...
Property File:
mockserver.openAPIResponseValidation=...
Example:
-Dmockserver.openAPIResponseValidation="true"
By default, OpenAPI response validation of mock responses is advisory only - violations are recorded as OPENAPI_RESPONSE_VALIDATION_FAILED log events but the response is still returned to the client. When this is enabled, a mock response that fails OpenAPI response validation is replaced with a 502 error describing the violations, matching the enforcement available on the validation-proxy path via validateProxyEnforce. This only has any effect when openAPIResponseValidation is also enabled.
Type: boolean Default: false
Java Code:
ConfigurationProperties.enforceResponseValidationForMocks(boolean enable)
System Property:
-Dmockserver.enforceResponseValidationForMocks=...
Environment Variable:
MOCKSERVER_ENFORCE_RESPONSE_VALIDATION_FOR_MOCKS=...
Property File:
mockserver.enforceResponseValidationForMocks=...
Example:
-Dmockserver.enforceResponseValidationForMocks="true"
By default a request matched by a mock expectation created from an OpenAPI spec is not re-validated against that spec. When this is enabled, an incoming request matched by an OpenAPI-backed expectation is validated against the spec before the mock response is returned. A request that violates the spec (for example a malformed or missing request body) is rejected with a 400 describing the violations and recorded as an OPENAPI_REQUEST_VALIDATION_FAILED log event, instead of returning the mock response. This only affects expectations created from an OpenAPI spec; expectations defined with an explicit request matcher are unaffected.
Type: boolean Default: false
Java Code:
ConfigurationProperties.validateRequestsAgainstOpenApiSpec(boolean enable)
System Property:
-Dmockserver.validateRequestsAgainstOpenApiSpec=...
Environment Variable:
MOCKSERVER_VALIDATE_REQUESTS_AGAINST_OPENAPI_SPEC=...
Property File:
mockserver.validateRequestsAgainstOpenApiSpec=...
Example:
-Dmockserver.validateRequestsAgainstOpenApiSpec="true"
When set to an OpenAPI spec URL, file path, or inline JSON/YAML payload, MockServer validates every forwarded/proxied request and its upstream response against the spec. Request violations are recorded as OPENAPI_REQUEST_VALIDATION_FAILED log events and response violations as OPENAPI_RESPONSE_VALIDATION_FAILED log events. By default, validation is report-only and does not block traffic. To block non-conformant traffic, also enable validateProxyEnforce.
Type: string Default: "" (disabled)
Java Code:
ConfigurationProperties.validateProxyOpenAPISpec(String specUrlOrPayload)
System Property:
-Dmockserver.validateProxyOpenAPISpec=...
Environment Variable:
MOCKSERVER_VALIDATE_PROXY_OPENAPI_SPEC=...
Property File:
mockserver.validateProxyOpenAPISpec=...
Example:
-Dmockserver.validateProxyOpenAPISpec="https://petstore.swagger.io/v2/swagger.json"
When enabled (and validateProxyOpenAPISpec is set), forwarded requests that violate the OpenAPI spec are rejected with a 400, and non-streaming upstream responses that violate the spec are replaced with a 502. Streaming responses cannot be replaced after their body has been written to the client, so they are validated in report-only mode (violations logged but not blocked) even when enforce is enabled. When disabled (the default), violations are logged but traffic flows unmodified.
Type: boolean Default: false
Java Code:
ConfigurationProperties.validateProxyEnforce(boolean enable)
System Property:
-Dmockserver.validateProxyEnforce=...
Environment Variable:
MOCKSERVER_VALIDATE_PROXY_ENFORCE=...
Property File:
mockserver.validateProxyEnforce=...
Example:
-Dmockserver.validateProxyEnforce="true"
When enabled, OpenAPI example responses that have no explicit example value are filled with realistic, format-aware fake data (e.g. plausible emails, dates, UUIDs) instead of static placeholders. The generated values are deterministic (same seed produces the same output).
Type: boolean Default: false
Java Code:
new Configuration().generateRealisticExampleValues(true)
System Property:
-Dmockserver.generateRealisticExampleValues=...
Environment Variable:
MOCKSERVER_GENERATE_REALISTIC_EXAMPLE_VALUES=...
Property File:
mockserver.generateRealisticExampleValues=...
Example:
-Dmockserver.generateRealisticExampleValues="true"
These properties configure server-wide defaults for AsyncAPI broker mocking. Per-request brokerConfig values in the PUT /mockserver/asyncapi request body override these defaults.
Default Kafka bootstrap servers used when a PUT /mockserver/asyncapi request body does not include brokerConfig.kafkaBootstrapServers. When unset (empty string), the broker must be specified per-request.
Type: string Default: "" (unset)
Java Code:
ConfigurationProperties.asyncKafkaBootstrapServers(String servers)
System Property:
-Dmockserver.asyncKafkaBootstrapServers=...
Environment Variable:
MOCKSERVER_ASYNC_KAFKA_BOOTSTRAP_SERVERS=...
Property File:
mockserver.asyncKafkaBootstrapServers=...
Example:
-Dmockserver.asyncKafkaBootstrapServers="localhost:9092"
Default MQTT broker URL used when a PUT /mockserver/asyncapi request body does not include brokerConfig.mqttBrokerUrl. When unset (empty string), the broker must be specified per-request.
Type: string Default: "" (unset)
Java Code:
ConfigurationProperties.asyncMqttBrokerUrl(String url)
System Property:
-Dmockserver.asyncMqttBrokerUrl=...
Environment Variable:
MOCKSERVER_ASYNC_MQTT_BROKER_URL=...
Property File:
mockserver.asyncMqttBrokerUrl=...
Example:
-Dmockserver.asyncMqttBrokerUrl="tcp://localhost:1883"
Default AMQP (RabbitMQ) connection URI used when a PUT /mockserver/asyncapi request body does not include brokerConfig.amqpUri. When unset (empty string), the broker must be specified per-request. The exchange and routing key for each channel are derived from the channel's bindings.amqp definition.
Type: string Default: "" (unset)
Java Code:
ConfigurationProperties.asyncAmqpUri(String uri)
System Property:
-Dmockserver.asyncAmqpUri=...
Environment Variable:
MOCKSERVER_ASYNC_AMQP_URI=...
Property File:
mockserver.asyncAmqpUri=...
Example:
-Dmockserver.asyncAmqpUri="amqp://guest:guest@localhost:5672/"
Maximum number of recorded messages retained per channel in async messaging subscribers. When the cap is reached, the oldest messages are evicted (FIFO). This prevents unbounded memory growth when consuming high-volume topics.
Type: int Default: 1000
Java Code:
ConfigurationProperties.asyncRecordedMessageMaxEntries(int maxEntries)
System Property:
-Dmockserver.asyncRecordedMessageMaxEntries=...
Environment Variable:
MOCKSERVER_ASYNC_RECORDED_MESSAGE_MAX_ENTRIES=...
Property File:
mockserver.asyncRecordedMessageMaxEntries=...
Example:
-Dmockserver.asyncRecordedMessageMaxEntries="5000"
These properties configure multi-node clustering. When enabled, MockServer instances sharing the same cluster name replicate expectation state via an embedded Infinispan data grid with JGroups transport. Requires the mockserver-state-infinispan module on the classpath and stateBackend=infinispan.
Selects the backend used to store expectation and request-log state. The default memory backend keeps all state in the local JVM, so each MockServer instance is independent. Set this to infinispan to replicate state across a cluster of MockServer instances using an embedded Infinispan data grid.
The infinispan backend requires the mockserver-state-infinispan module on the classpath and is normally combined with the clustering properties below.
Type: string Default: memory (valid values: memory, infinispan)
Java Code:
ConfigurationProperties.stateBackend(String stateBackend)
System Property:
-Dmockserver.stateBackend=...
Environment Variable:
MOCKSERVER_STATE_BACKEND=...
Property File:
mockserver.stateBackend=...
Example:
-Dmockserver.stateBackend="infinispan"
Enables multi-node clustering with JGroups transport. When false (default), MockServer runs in single-node LOCAL mode with no network transport.
Type: boolean Default: false
Java Code:
ConfigurationProperties.clusterEnabled(boolean enabled)
System Property:
-Dmockserver.clusterEnabled=true
Environment Variable:
MOCKSERVER_CLUSTER_ENABLED=true
Property File:
mockserver.clusterEnabled=true
The JGroups cluster name. All MockServer instances with the same cluster name will form a cluster and replicate state. Change this to isolate independent clusters on the same network.
Type: string Default: "mockserver-cluster"
Java Code:
ConfigurationProperties.clusterName(String name)
System Property:
-Dmockserver.clusterName="my-test-cluster"
Environment Variable:
MOCKSERVER_CLUSTER_NAME="my-test-cluster"
Property File:
mockserver.clusterName=my-test-cluster
Path to a custom JGroups XML transport configuration file. When unset, MockServer uses a built-in SHARED_LOOPBACK stack suitable for in-JVM testing only (no network I/O). For multi-host production clusters, provide a JGroups XML file with a real transport (TCP/UDP) and an appropriate discovery protocol (TCPPING, DNS_PING, S3_PING, etc.).
Type: string Default: "" (built-in SHARED_LOOPBACK stack)
Java Code:
ConfigurationProperties.clusterTransportConfig(String path)
System Property:
-Dmockserver.clusterTransportConfig="/etc/mockserver/jgroups-tcp.xml"
Environment Variable:
MOCKSERVER_CLUSTER_TRANSPORT_CONFIG="/etc/mockserver/jgroups-tcp.xml"
Property File:
mockserver.clusterTransportConfig=/etc/mockserver/jgroups-tcp.xml
Controls how limited-use expectations (those created with Times.exactly(n)) count their remaining uses across a cluster. When true (the default), the remaining count is shared across all nodes using an atomic compare-and-set on the replicated store, so an expectation set to respond N times responds exactly N times across the whole cluster. This costs a synchronous replicated write on the request-handling thread each time such an expectation matches. Set to false to skip the shared counter and use a faster node-local count instead — each node then serves up to its own N, so the fleet-wide total becomes approximate. Only affects clustered deployments with limited-use expectations; single-node and unlimited-use matching are unaffected.
Type: boolean Default: true
Java Code:
ConfigurationProperties.clusterSharedTimesEnabled(boolean enabled)
System Property:
-Dmockserver.clusterSharedTimesEnabled=false
Environment Variable:
MOCKSERVER_CLUSTER_SHARED_TIMES_ENABLED=false
Property File:
mockserver.clusterSharedTimesEnabled=false
Controls whether verify and retrieve of recorded requests aggregate across all cluster nodes. MockServer replicates expectations and scenario state across a cluster, but each node keeps its OWN record of the requests it received. Behind a load balancer that means a verify or a retrieve of recorded requests sees only the traffic that happened to reach the node handling that call — so a verification can pass even though the whole cluster served more (or fewer) matching requests than expected. When true, MockServer asks every other node (listed in clusterVerifyFanInPeers) for its local records, merges them, and evaluates the verification against the cluster-wide total. Default is false (each node reports only its own traffic — unchanged behaviour). If a peer cannot be reached the verify/retrieve fails rather than returning a partial result. Only relevant in a clustered deployment.
Type: boolean Default: false
Java Code:
ConfigurationProperties.clusterVerifyFanIn(boolean enabled)
System Property:
-Dmockserver.clusterVerifyFanIn=true
Environment Variable:
MOCKSERVER_CLUSTER_VERIFY_FAN_IN=true
Property File:
mockserver.clusterVerifyFanIn=true
The comma-separated list of the OTHER cluster nodes' base URLs (for example http://mockserver-1:1080,http://mockserver-2:1080) that clusterVerifyFanIn queries when aggregating verify/retrieve across the cluster. List every node except the one being configured. Has no effect unless clusterVerifyFanIn is enabled; when enabled with an empty list, fan-in is a no-op.
Type: string Default: "" (empty)
Java Code:
ConfigurationProperties.clusterVerifyFanInPeers(String peers)
System Property:
-Dmockserver.clusterVerifyFanInPeers="http://mockserver-1:1080,http://mockserver-2:1080"
Environment Variable:
MOCKSERVER_CLUSTER_VERIFY_FAN_IN_PEERS=http://mockserver-1:1080,http://mockserver-2:1080
Property File:
mockserver.clusterVerifyFanInPeers=http://mockserver-1:1080,http://mockserver-2:1080
The credential MockServer presents when it queries other cluster nodes during verify/retrieve fan-in. If your MockServer control plane requires authentication (a bearer token, JWT, or OIDC), the fan-in queries to other nodes would otherwise be rejected and the whole verify/retrieve would fail. Set this to the credential each node should send — it is used exactly as given for the Authorization header, so include the scheme, for example Bearer eyJ.... Set the same value on every node. Default is empty (no credential sent — unchanged behaviour); leave it empty if your control plane is not authenticated. Because it is sent on every cross-node query, treat it as a shared secret and prefer TLS between nodes. Has no effect unless clusterVerifyFanIn is enabled. Like every other credential property it is write-only: GET /mockserver/configuration does not return it.
Type: string Default: "" (empty)
Java Code:
ConfigurationProperties.clusterFanInPeerAuthToken(String token)
System Property:
-Dmockserver.clusterFanInPeerAuthToken="Bearer eyJ..."
Environment Variable:
MOCKSERVER_CLUSTER_FAN_IN_PEER_AUTH_TOKEN="Bearer eyJ..."
Property File:
mockserver.clusterFanInPeerAuthToken=Bearer eyJ...
These properties configure cloud-backed blob storage for durable persistence of expectations, cassettes, and fixture files. Each cloud backend requires its own optional module on the classpath. Set blobStoreType to s3, gcs, or azure and configure the backend-specific properties below.
Selects where MockServer stores blob data such as persisted expectations, recorded cassettes, and fixture files. The default filesystem backend writes blobs to the local disk (preserving the existing on-disk persistence behaviour). The memory backend keeps blobs in the JVM only, so they are lost when the process exits. The s3, gcs, and azure backends store blobs in the corresponding cloud object store and require the matching optional module on the classpath plus the backend-specific properties below.
Type: string Default: filesystem (valid values: filesystem, memory, s3, gcs, azure)
Java Code:
ConfigurationProperties.blobStoreType(String blobStoreType)
System Property:
-Dmockserver.blobStoreType=...
Environment Variable:
MOCKSERVER_BLOB_STORE_TYPE=...
Property File:
mockserver.blobStoreType=...
Example:
-Dmockserver.blobStoreType="s3"
The bucket name for S3 or GCS blob storage. Required when blobStoreType is s3 or gcs.
Type: string Default: "" (none)
System Property:
-Dmockserver.blobStoreBucket="my-mockserver-bucket"
Environment Variable:
MOCKSERVER_BLOB_STORE_BUCKET="my-mockserver-bucket"
The AWS region for S3 blob storage. If not set, defaults to us-east-1.
Type: string Default: "" (us-east-1)
System Property:
-Dmockserver.blobStoreRegion="eu-west-1"
Environment Variable:
MOCKSERVER_BLOB_STORE_REGION="eu-west-1"
Endpoint override URL for S3-compatible stores (e.g. MinIO, LocalStack) or GCS emulators (e.g. fake-gcs-server). When set, the cloud client connects to this URL instead of the real cloud service.
Type: string Default: "" (none -- use real cloud endpoint)
System Property:
-Dmockserver.blobStoreEndpoint="http://localhost:9000"
Environment Variable:
MOCKSERVER_BLOB_STORE_ENDPOINT="http://localhost:9000"
An optional prefix prepended to all blob keys in the cloud store. Useful for namespacing MockServer objects within a shared bucket or container (e.g. mockserver/).
The trailing / is optional: MockServer always joins the prefix and the key with exactly one /, so mockserver, mockserver/ and /mockserver/ all produce the same object name (for example mockserver/persistedExpectations.json). A leading / and any repeated // are removed: S3-compatible stores such as MinIO reject a // outright, and a leading / produces an awkward object name that most tools cannot browse to.
Type: string Default: "" (no prefix)
System Property:
-Dmockserver.blobStoreKeyPrefix="mockserver/"
Environment Variable:
MOCKSERVER_BLOB_STORE_KEY_PREFIX="mockserver/"
The Azure Blob Storage container name. Required when blobStoreType is azure.
Type: string Default: "" (none)
System Property:
-Dmockserver.blobStoreContainer="my-container"
Environment Variable:
MOCKSERVER_BLOB_STORE_CONTAINER="my-container"
The Azure Blob Storage connection string (includes account name, key, and endpoint). Required when blobStoreType is azure.
Type: string Default: "" (none)
System Property:
-Dmockserver.blobStoreConnectionString="DefaultEndpointsProtocol=https;AccountName=...;AccountKey=..."
Environment Variable:
MOCKSERVER_BLOB_STORE_CONNECTION_STRING="DefaultEndpointsProtocol=https;AccountName=...;AccountKey=..."
Explicit AWS access key ID for the S3 blob store. Optional — when empty, the default AWS credential chain is used (environment, profile, instance/IRSA role). Only relevant when blobStoreType is s3.
Type: string Default: "" (use default credential chain)
System Property:
-Dmockserver.blobStoreAccessKeyId="AKIA..."
Environment Variable:
MOCKSERVER_BLOB_STORE_ACCESS_KEY_ID="AKIA..."
Explicit AWS secret access key for the S3 blob store. Optional — when empty, the default AWS credential chain is used. Only relevant when blobStoreType is s3.
Type: string Default: "" (use default credential chain)
System Property:
-Dmockserver.blobStoreSecretAccessKey="..."
Environment Variable:
MOCKSERVER_BLOB_STORE_SECRET_ACCESS_KEY="..."
The Google Cloud project ID for the GCS blob store. Optional — when empty, the project is inferred from Application Default Credentials. Only relevant when blobStoreType is gcs.
Type: string Default: "" (infer from ADC)
System Property:
-Dmockserver.blobStoreProjectId="my-gcp-project"
Environment Variable:
MOCKSERVER_BLOB_STORE_PROJECT_ID="my-gcp-project"
How many seconds MockServer waits, while starting up, for previously persisted expectations to be read back from a cloud blob store before giving up and starting anyway.
This read happens before MockServer starts listening, so an unreachable or misconfigured blob-store endpoint would otherwise delay startup for the cloud SDK's own retry budget — around two minutes for AWS — long enough to fail a Kubernetes readiness probe or a test-container wait. When the wait expires MockServer logs a warning and starts with no restored expectations.
Set to 0 to skip the startup restore entirely. Only relevant when persistExpectations is enabled and blobStoreType is a cloud backend (s3, gcs or azure) — the filesystem backend reloads via initializationJsonPath instead.
This value is read once, while MockServer starts, so it must be set before startup. Like the other blobStore settings it is reported by GET /mockserver/configuration, but changing it with PUT /mockserver/configuration on a running instance has no effect — the restore it governs has already happened.
Type: int Default: 10
System Property:
-Dmockserver.blobStoreRestoreTimeoutSeconds="10"
Environment Variable:
MOCKSERVER_BLOB_STORE_RESTORE_TIMEOUT_SECONDS="10"
Property File:
mockserver.blobStoreRestoreTimeoutSeconds=10