Common configurations

Copy-paste one of these blocks as a starting point. All values can be overridden by system properties or environment variables at runtime.

Local development

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

CI (shared, parallel test runs)

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

Production / shared team instance

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
 

Top 10 most-changed properties

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
 

Property Index

Filter the full list of configuration properties. Click a property name to jump to its detail — the accordion expands automatically.

Property Section
Log LevelLogging & Metrics
Disable Logging To System OutLogging & Metrics
Disable All LoggingLogging & Metrics
Compact Log FormatLogging & Metrics
Log Level Overrides (Per-Category)Logging & Metrics
Detailed Match FailuresLogging & Metrics
Detailed Verification FailuresLogging & Metrics
Launch UI When Log Level DEBUGLogging & Metrics
Enable MetricsLogging & Metrics
Custom Log Event ListenerLogging & Metrics
Dev ModeDeveloper Mode
Maximum Expectations To Hold In MemoryMemory Usage
Maximum Log Entries To Hold In MemoryMemory Usage
Log Event Ring Buffer SizeMemory Usage
Maximum Event Log Size In BytesMemory Usage
Maximum Logged Body Bytes Per EntryMemory Usage
Maximum WebSockets For Object Callback ExpectationsMemory Usage
Output JVM Memory UsageMemory Usage
Directory For Outputting JVM Memory UsageMemory Usage
Connection DelayPerformance
Use Native Transport (Epoll)Performance
Number of Event Loop ThreadsPerformance
Number of Action Handler ThreadsPerformance
Number of Client Event Loop ThreadsPerformance
Number of Client Web Socket Event Loop ThreadsPerformance
Request Matchers Fail FastPerformance
HTTP/3 (QUIC) PortSocket
HTTP/3 Max Idle TimeoutSocket
HTTP/3 Initial Max DataSocket
HTTP/3 Initial Max Stream Data (Bidirectional)Socket
HTTP/3 Initial Max Streams (Bidirectional)Socket
HTTP/3 QPACK Max Table CapacitySocket
HTTP/3 Alt-Svc Max AgeSocket
HTTP/3 Advertise Alt-SvcSocket
HTTP/3 CONNECT-UDP (MASQUE) EnabledSocket
HTTP/3 CONNECT-UDP (MASQUE) Allowed TargetsSocket
Maximum Socket TimeoutSocket
Maximum Socket Connection TimeoutSocket
Always Close Socket Connection After ResponseSocket
Local Bound IP For Accepting Socket ConnectionSocket
Match Exact CaseHTTP Request Parsing
Maximum HTTP Request Initial Line LengthHTTP Request Parsing
Maximum HTTP Request Header SizeHTTP Request Parsing
Maximum HTTP Request Chunk SizeHTTP Request Parsing
Maximum Inbound Request Body SizeHTTP Request Parsing
Maximum Upstream Response Body SizeHTTP Request Parsing
Regex Matching TimeoutHTTP Request Parsing
XPath Matching TimeoutHTTP Request Parsing
Custom JSON Body MatchersHTTP Request Parsing
JSON Schema Remote $ref ResolutionHTTP Request Parsing
Attach Mismatch Diagnostic To Unmatched ResponseHTTP Request Parsing
Closest Match Hint On Unmatched ResponseHTTP Request Parsing
Block Forwarding To Private Networks (SSRF Protection)HTTP Request Parsing
Allow Insecure TLS ProtocolsHTTP Request Parsing
Treat Semicolon As Query Parameter SeparatorHTTP Request Parsing
Startup WarmupHTTP Request Parsing
Assume All Requests Are HTTPHTTP Request Parsing
HTTP/2 EnabledHTTP Request Parsing
gRPC Bidi-Streaming EnabledHTTP Request Parsing
Enable CORS For MockServer REST APICORS
Enable CORS For All ResponsesCORS
CORS Allow Origin ValueCORS
CORS Allow Methods ValueCORS
CORS Allow Headers ValueCORS
CORS Allow Credentials ValueCORS
CORS Max Age ValueCORS
Default Response HeadersDefault Response Headers
Disable Classes In JavaScript TemplatesTemplate Restrictions
Restrict Content In JavaScript TemplatesTemplate Restrictions
JavaScript Template Execution TimeoutTemplate Restrictions
Template Faker SeedTemplate Restrictions
Disable Class Loading In Velocity TemplatesTemplate Restrictions
Restrict Content In Velocity TemplatesTemplate Restrictions
Restrict Content In Mustache TemplatesTemplate Restrictions
Expectation Initialization ClassInitializer & Persistence
Expectation Initialization JSON File PathInitializer & Persistence
Expectation Initialization OpenAPI File PathInitializer & Persistence
Watch Expectation Initialization FilesInitializer & Persistence
Fail On Initialization ErrorInitializer & Persistence
Persist Expectations As JSONInitializer & Persistence
Persisted Expectations File PathInitializer & Persistence
Persist Recorded Expectations As JSONInitializer & Persistence
Persisted Recorded Expectations File PathInitializer & Persistence
Persist Recorded Requests To Disk (NDJSON)Initializer & Persistence
Persisted Recorded Requests File PathInitializer & Persistence
Maximum Requests In Verification FailureInitializer & Persistence
Proxy Setup — Generate Unique Secure CAProxying
Proxy Setup LoggingProxying
Attempt To Proxy If No Matching ExpectationProxying
Forward Binary Requests Without Waiting For ResponseProxying
Reuse Upstream Connections (Connection Pooling)Proxying
Maximum Idle Pooled Connections Per UpstreamProxying
Idle Pooled Connection TimeoutProxying
Keep Pooled Connections Warm Under Sustained LoadProxying
Maximum Warm Pooled Connections Per UpstreamProxying
Forward Upstream TCP KeepaliveProxying
Forward Upstream TCP Keepalive Idle SecondsProxying
Forward Upstream TCP Keepalive Interval SecondsProxying
Forward Upstream TCP Keepalive Probe CountProxying
Forward Upstream Requests Using HTTP/2Proxying
Upgrade Forwarded Requests To HTTP/2Proxying
Retry Forwarded Requests On Transient FailureProxying
Retry Back-OffProxying
Upstream Circuit BreakerProxying
Circuit Breaker Failure ThresholdProxying
Circuit Breaker Open WindowProxying
HTTP Proxy For Forwarded RequestsProxying
HTTPS Proxy For Forwarded RequestsProxying
SOCKS Proxy For Forwarded RequestsProxying
Proxy Authentication Username For Forwarded RequestsProxying
Proxy Authentication Password For Forwarded RequestsProxying
Realm For Proxy Authentication to MockServerProxying
Required Username For Proxy Authentication to MockServerProxying
Required Password For Proxy Authentication to MockServerProxying
ProxyPass MappingsProxying
Hosts That Bypass ProxyProxying
Auto-Adjust Host Header When ForwardingProxying
Default Host Header for Forwarded RequestsProxying
Proxy Remote HostProxying
Proxy Remote PortProxying
Require Authentication On Mocked EndpointsData Plane Authentication
Data Plane Basic Authentication UsernameData Plane Authentication
Data Plane Basic Authentication PasswordData Plane Authentication
Data Plane Basic Authentication RealmData Plane Authentication
Data Plane Bearer Authentication TokenData Plane Authentication
Data Plane API Key Header NameData Plane Authentication
Data Plane API Key ValueData Plane Authentication
Streaming Responses EnabledStreaming Proxy
Maximum Streaming Response Body CaptureStreaming Proxy
Maximum LLM Conversation Body SizeStreaming Proxy
Runtime LLM Backend (optional)Streaming Proxy
LLM Fixture (VCR) Recording & ReplayStreaming Proxy
Drift DetectionStreaming Proxy
Control-Plane Audit LogStreaming Proxy
Control-Plane OIDC AuthenticationStreaming Proxy
Control-Plane AuthorizationStreaming Proxy
Interactive BreakpointsStreaming Proxy
Chaos Auto-Halt Circuit-BreakerStreaming Proxy
Rate Limit Max Named QuotasStreaming Proxy
Connection-Lifecycle Faults & Preemption SimulationStreaming Proxy
SLO VerdictsStreaming Proxy
Load GenerationStreaming Proxy
LLM Token & Cost MetricsStreaming Proxy
Per-Expectation Match CountersStreaming Proxy
Slow Request ThresholdStreaming Proxy
Metrics Request Duration Route LabelsStreaming Proxy
Redact Secrets In Recorded ExpectationsStreaming Proxy
Templatize Recorded ValuesStreaming Proxy
Redact Secrets In Event Log & DashboardStreaming Proxy
Dashboard Analytics EnabledDashboard Analytics
Dashboard Analytics EndpointDashboard Analytics
Dashboard Analytics KeyDashboard Analytics
Dashboard Analytics DistributionDashboard Analytics
OpenTelemetry (Metrics, GenAI Spans & Trace Context)Dashboard Analytics
Prometheus Remote Write (Push Metrics)Dashboard Analytics
Streaming Response Idle TimeoutDashboard Analytics
Global Response DelayDashboard Analytics
Graceful Shutdown Connection DrainDashboard Analytics
Path for HTTP GET Liveness / Healthcheck ProbesLiveness
Request Header That Scopes Matching To A NamespaceMulti-Tenancy
OpenAPI Context Path PrefixOpenAPI
OpenAPI Response ValidationOpenAPI
Enforce Response Validation For MocksOpenAPI
Validate Requests Against OpenAPI SpecOpenAPI
Validation Proxy OpenAPI SpecOpenAPI
Validation Proxy EnforceOpenAPI
Generate Realistic Example ValuesOpenAPI
Default Kafka Bootstrap ServersAsync Messaging
Default MQTT Broker URLAsync Messaging
Default AMQP (RabbitMQ) URIAsync Messaging
Maximum Recorded Messages Per ChannelAsync Messaging
Enable MCP EndpointMCP
Enable WASM Body MatchingWASM
WASM Maximum Memory PagesWASM
Enable gRPC SupportgRPC
gRPC Descriptor DirectorygRPC
gRPC Proto Source DirectorygRPC
gRPC Protoc PathgRPC
Enable DNS MockingDNS
DNS PortDNS
Transparent Proxy EnabledService Mesh
Transparent Proxy TPROXY ModeService Mesh
Transparent Proxy eBPF Original Destination ResolutionService Mesh
Transparent Proxy eBPF Map PathService Mesh
State BackendClustering
Cluster EnabledClustering
Cluster NameClustering
Cluster Transport ConfigClustering
Cluster Shared Times EnabledClustering
Cluster Verify Fan-InClustering
Cluster Verify Fan-In PeersClustering
Cluster Fan-In Peer Auth TokenClustering
Blob Store TypeCloud Blob Store
Blob Store Bucket (S3 / GCS)Cloud Blob Store
Blob Store Region (S3)Cloud Blob Store
Blob Store Endpoint OverrideCloud Blob Store
Blob Store Key PrefixCloud Blob Store
Blob Store Container (Azure)Cloud Blob Store
Blob Store Connection String (Azure)Cloud Blob Store
Blob Store Access Key ID (S3)Cloud Blob Store
Blob Store Secret Access Key (S3)Cloud Blob Store
Blob Store Project ID (GCS)Cloud Blob Store
Enabled Control Plane mTLS AuthenticationControl Plane Authentication
Control Plane mTLS Authentication CA ChainControl Plane Authentication
Control Plane mTLS Authentication Client Private KeyControl Plane Authentication
Control Plane mTLS Authentication Client CertificateControl Plane Authentication
Dynamically Create Inbound Certificate Authority X.509TLS
Directory To Save Dynamic CA X.509 and Private KeyTLS
Proactively Initialise TLS During Start UpTLS
TLS Protocol VersionsTLS
Prevent Dynamic Inbound X.509 UpdateTLS
Inbound X.509 Domain NameTLS
Inbound X.509 Subject Alternative Name DomainsTLS
Inbound X.509 Subject Alternative Name IPsTLS
Fixed Inbound Certificate Authority Private KeyTLS
Fixed Inbound Certificate Authority X.509 Certificate ChainTLS
Fixed Inbound Private KeyTLS
Fixed Inbound X.509 Certificate ChainTLS
Require Inbound mTLS Client AuthenticationTLS
Fixed Inbound mTLS Client Authentication X.509 Certificate ChainTLS
Outbound Trusted Certificates GroupTLS
Fixed Outbound X.509 Certificate Trust ChainTLS
Fixed Outbound Client Private KeyTLS
Fixed Outbound Client X.509 Certificate ChainTLS
Per-Host Outbound Client Certificate/Key (mTLS)TLS
MockServerClient Trust X.509 Certificate ChainTLS

Settings Properties

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:

  1. java code (highest precedence)
  2. @MockServerTest annotation (per-instance Configuration object)
  3. system property
  4. property file
  5. environment variable (lowest precedence)

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.

 

Programmatic Properties

There are two ways to set properties programmatically, as follows:

  • org.mockserver.configuration.ConfigurationProperties
    • is JVM global
    • exposes static methods
    • stores property values in system properties
  • org.mockserver.configuration.Configuration
    • is unique to each MockServer instance
    • can be passed to ClientAndServer, MockServer and MockServerClient classes
    • only supports instance methods
    • defaults to ConfigurationProperties for unset values
 

Property File

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

# 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
 

JSON Configuration File

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"],
  "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. This output can be saved as a JSON configuration file and reloaded at startup.

 

Configuration Properties

 

Logging & Metrics Configuration:

Quick Reference

Property Purpose Default
logLevelGlobal minimum log levelINFO
disableSystemOutSuppress stdout outputfalse
disableLoggingDisable all logging and event processingfalse
compactLogFormatOne-line summaries instead of full JSON in stdoutfalse
logLevelOverridesPer-type/category log level overrides{}
detailedMatchFailuresInclude per-field match failure reasonstrue
detailedVerificationFailuresInclude per-field diff in verification failurestrue
launchUIForLogLevelDebugAuto-open UI when log level is DEBUGfalse
metricsEnabledPrometheus metrics endpointfalse
slowRequestThresholdMillisFlag forwarded requests slower than this threshold0 (disabled)
metricsRequestDurationRouteLabelsAdd per-HTTP-method labels to the request duration histogramfalse

The the minimum level of logs to record in the event log and to output to system out (if system out log output is not disabled). The lower the log level the more log entries will be captured, particularly at TRACE level logging.

Type: string Default: INFO

Allowed values: TRACE, DEBUG, INFO, WARN, ERROR, OFF (also accepts java.util.logging equivalents: FINEST, FINE, WARNING, SEVERE)

Java Code:

ConfigurationProperties.logLevel(String level)

System Property:

-Dmockserver.logLevel=...

Environment Variable:

MOCKSERVER_LOG_LEVEL=...

Property File:

mockserver.logLevel=...

Example:

-Dmockserver.logLevel="DEBUG"

Disable logging to the system output

Type: boolean Default: false

Java Code:

ConfigurationProperties.disableSystemOut(boolean disableSystemOut)

System Property:

-Dmockserver.disableSystemOut=...

Environment Variable:

MOCKSERVER_DISABLE_SYSTEM_OUT=...

Property File:

mockserver.disableSystemOut=...

Example:

-Dmockserver.disableSystemOut="true"

Disable all logging and processing of log events

Type: boolean Default: false

Java Code:

ConfigurationProperties.disableLogging(boolean disableLogging)

System Property:

-Dmockserver.disableLogging=...

Environment Variable:

MOCKSERVER_DISABLE_LOGGING=...

Property File:

mockserver.disableLogging=...

Example:

-Dmockserver.disableLogging="true"

When enabled, log messages written to stdout/SLF4J use a compact single-line format showing summary information (method, path, status code, expectation ID) instead of full JSON-serialized request and response details. This significantly reduces log noise, especially in CI/CD environments or when running many tests.

The dashboard UI, verification, and log retrieval APIs are not affected — they continue to show full details.

Type: boolean Default: false

Java Code:

ConfigurationProperties.compactLogFormat(boolean enable)

System Property:

-Dmockserver.compactLogFormat=...

Environment Variable:

MOCKSERVER_COMPACT_LOG_FORMAT=...

Property File:

mockserver.compactLogFormat=...

Example output comparison:

Verbose (default):

INFO - 50850 returning response:

  {
    "statusCode" : 200,
    "body" : "{\"accessToken\":{...}}"
  }

 for request:

  {
    "method" : "POST",
    "path" : "/oauth2/token",
    "headers" : { ... }
  }

 from expectation:

  a735b798-8aec-4c15-b264-c6d3c93fda1d

Compact:

INFO - 50850 returning response: 200 for request: POST /oauth2/token from expectation: a735b798-8aec-4c15-b264-c6d3c93fda1d

Example:

-Dmockserver.compactLogFormat="true"

Tip: combine with logLevelOverrides for maximum control. For example, enable compact format and suppress startup/shutdown noise:

-Dmockserver.compactLogFormat="true" -Dmockserver.logLevelOverrides='{"SERVER":"WARN"}'

Override the log level for specific categories of log events or individual log message types. This allows fine-grained control over log verbosity without changing the global log level.

Keys can be category group names or individual log message type names. When both are specified, the individual type override takes precedence over the category group override, which takes precedence over the global logLevel.

This setting affects stdout/SLF4J output and the dashboard UI. The internal event log (used for verification) is not affected.

Note: Overrides can only suppress log events that are already captured at the global logLevel. For example, with logLevel=WARN, setting {"EXPECTATION_MATCHED":"INFO"} will not cause INFO-level match events to appear, because they are not generated when the global level is WARN. To see more verbose events for a specific category, first set the global logLevel low enough (e.g., INFO or DEBUG), then use overrides to suppress the noisy categories.

Type: map (JSON object) Default: {} (empty, global logLevel applies to all categories)

Category Groups:

MATCHINGEXPECTATION_MATCHED, EXPECTATION_NOT_MATCHED, NO_MATCH_RESPONSE
REQUEST_LIFECYCLERECEIVED_REQUEST, FORWARDED_REQUEST, EXPECTATION_RESPONSE, TEMPLATE_GENERATED
EXPECTATION_MANAGEMENTCREATED_EXPECTATION, UPDATED_EXPECTATION, REMOVED_EXPECTATION, CLEARED
VERIFICATIONVERIFICATION, VERIFICATION_FAILED, VERIFICATION_PASSED, RETRIEVED
SERVERSERVER_CONFIGURATION, AUTHENTICATION_FAILED, OPENAPI_RESPONSE_VALIDATION_FAILED
GENERALTRACE, DEBUG, INFO, WARN, ERROR, EXCEPTION

Java Code:

ConfigurationProperties.logLevelOverrides(Map<String, String> overrides)

System Property:

-Dmockserver.logLevelOverrides=...

Environment Variable:

MOCKSERVER_LOG_LEVEL_OVERRIDES=...

Property File:

mockserver.logLevelOverrides=...

REST API:

PUT /mockserver/configuration {"logLevelOverrides": {"MATCHING": "WARN", "EXPECTATION_MATCHED": "INFO"}}

Example - suppress per-expectation match failure noise while keeping match successes:

-Dmockserver.logLevelOverrides='{"MATCHING":"WARN","EXPECTATION_MATCHED":"INFO"}'

Example - suppress all matching and expectation management logs:

MOCKSERVER_LOG_LEVEL_OVERRIDES='{"MATCHING":"WARN","EXPECTATION_MANAGEMENT":"WARN"}'

If true (the default) the log event recording that a request matcher did not match will include a detailed reason why each non matching field did not match. See Troubleshooting Matching for how to use this when debugging.

Type: boolean Default: true

Java Code:

ConfigurationProperties.detailedMatchFailures(boolean enable)

System Property:

-Dmockserver.detailedMatchFailures=...

Environment Variable:

MOCKSERVER_DETAILED_MATCH_FAILURES=...

Property File:

mockserver.detailedMatchFailures=...

Example:

-Dmockserver.detailedMatchFailures="false"

If true (the default) verification failure messages will include a detailed diff showing how each recorded request differed from the expected request. This makes it easier to identify why a verification failed by highlighting per-field mismatches between the expected and actual requests.

Disable this if verification failure messages are too verbose or if you prefer concise failure output.

Type: boolean Default: true

Java Code:

ConfigurationProperties.detailedVerificationFailures(boolean enable)

System Property:

-Dmockserver.detailedVerificationFailures=...

Environment Variable:

MOCKSERVER_DETAILED_VERIFICATION_FAILURES=...

Property File:

mockserver.detailedVerificationFailures=...

Example:

-Dmockserver.detailedVerificationFailures="false"

If true (default false) the ClientAndServer constructor or static factory methods will open the UI in the default browser when the log level is set to DEBUG.

Type: boolean Default: false

Java Code:

ConfigurationProperties.launchUIForLogLevelDebug(boolean enable)

System Property:

-Dmockserver.launchUIForLogLevelDebug=...

Environment Variable:

MOCKSERVER_LAUNCH_UI_FOR_LOG_LEVEL_DEBUG=...

Property File:

mockserver.launchUIForLogLevelDebug=...

Example:

-Dmockserver.launchUIForLogLevelDebug="false"

Enable the recording of metrics for different activities within MockServer, these are exposed via /mockserver/metrics in prometheus format

Type: boolean Default: false

Java Code:

ConfigurationProperties.metricsEnabled(boolean enable)

System Property:

-Dmockserver.metricsEnabled=...

Environment Variable:

MOCKSERVER_METRICS_ENABLED=...

Property File:

mockserver.metricsEnabled=...

Example:

-Dmockserver.metricsEnabled="true"

Threshold in milliseconds for flagging slow forwarded requests. When a forwarded request's total round-trip time exceeds this value, MockServer emits a WARN-level log entry and increments the mock_server_slow_requests_total Prometheus counter (when metrics are enabled). This is useful for detecting intermittently slow upstream services without scanning every recorded request manually.

Set to 0 to disable slow-request detection. See Network Latency Debugging for usage examples.

Type: long Default: 0 (disabled)

Java Code:

ConfigurationProperties.slowRequestThresholdMillis(long milliseconds)

System Property:

-Dmockserver.slowRequestThresholdMillis=...

Environment Variable:

MOCKSERVER_SLOW_REQUEST_THRESHOLD_MILLIS=...

Property File:

mockserver.slowRequestThresholdMillis=...

Example:

-Dmockserver.slowRequestThresholdMillis="500"

When enabled, MockServer registers an additional Prometheus histogram mock_server_request_duration_by_method_seconds with a method label for the HTTP method (GET, POST, PUT, etc.). This lets you compute per-method latency percentiles in your monitoring system. Cardinality is bounded to the set of standard HTTP methods.

Requires metricsEnabled to be true. See Network Latency Debugging for Prometheus query examples.

Type: boolean Default: false

Java Code:

ConfigurationProperties.metricsRequestDurationRouteLabels(boolean enable)

System Property:

-Dmockserver.metricsRequestDurationRouteLabels=...

Environment Variable:

MOCKSERVER_METRICS_REQUEST_DURATION_ROUTE_LABELS=...

Property File:

mockserver.metricsRequestDurationRouteLabels=...

Example:

-Dmockserver.metricsRequestDurationRouteLabels="true"

Register a custom callback that receives every log event generated by MockServer. This is useful for integrating MockServer logging with external systems (e.g. forwarding events to a monitoring tool, custom test reporting, or capturing specific events programmatically during tests).

This feature is programmatic only — there is no system property or environment variable equivalent because the listener is a Java callback.

Java Code:

Configuration.logEventListener(Consumer<LogEntry> listener)
ClientAndServer.setLogEventListener(Consumer<LogEntry> listener)

Example:

ClientAndServer mockServer = ClientAndServer.startClientAndServer(1080);
mockServer.setLogEventListener(logEntry -> {
    System.out.println("Event: " + logEntry.getType() + " - " + logEntry.getTimestamp());
});
 

Developer Mode:

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):

  • maxLogEntries is set to 1,000 (instead of the heap-based default up to 100,000)
  • maxExpectations is set to 1,000 (instead of the heap-based default up to 15,000)

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
 

Memory Usage Configuration:

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="."
   

Memory Tuning Guide

MockServer stores expectations and log entries in memory using ring buffers. The two most important settings that affect memory usage are maxExpectations and maxLogEntries. Each HTTP request processed by MockServer generates 2-3 log entries (the request itself, the expectation match result, and the response).

Both settings have automatic defaults based on available JVM heap space. The table below provides recommended values if you want to override the defaults for different heap sizes:

JVM Heap Size maxExpectations maxLogEntries Approx HTTP Requests Retained
256 MB 1,000 5,000 ~1,500 - 2,500
512 MB 2,000 15,000 ~5,000 - 7,500
1 GB 5,000 40,000 ~13,000 - 20,000

These are conservative estimates assuming typical request/response sizes of 1-5 KB. Large request or response bodies will consume more memory per entry.

Tips for reducing memory usage:

  • Reduce maxLogEntries to limit the number of stored request/response log entries
  • Reduce maxExpectations if expectations contain large response bodies
  • Increase JVM heap size (-Xmx) to give the garbage collector more headroom
  • Use outputMemoryUsageCsv to monitor actual heap usage and tune values accordingly

Docker example with memory-constrained settings:

docker run -d --rm -p 1080:1080 \
  --env MOCKSERVER_MAX_EXPECTATIONS=1000 \
  --env MOCKSERVER_MAX_LOG_ENTRIES=5000 \
  mockserver/mockserver

Introduces a delay (in milliseconds) before protocol detection on new TCP connections. This can be used to simulate slow connection establishment, such as when testing client timeout handling or connection pooling behaviour under latency.

Type: long Default: 0

Java Code:

ConfigurationProperties.connectionDelayMillis(long millis)
Configuration.connectionDelay(Delay delay)

System Property:

-Dmockserver.connectionDelayMillis=...

Environment Variable:

MOCKSERVER_CONNECTION_DELAY_MILLIS=...

Property File:

mockserver.connectionDelayMillis=...

Example:

-Dmockserver.connectionDelayMillis="500"
 

Troubleshooting: MockServer Becomes Slow or Unresponsive

If MockServer appears to freeze, hang, or become progressively slower under sustained load, the most likely cause is memory pressure from log entry accumulation. This section explains why it happens and how to fix it.

Why Does MockServer Slow Down?

Every HTTP request that MockServer processes generates 2-3 log entries that are stored in memory regardless of the configured log level. These entries record the received request, expectation match result, and response — they are always stored to support request verification. Each log entry consumes approximately 4-10 KB of heap for small request/response bodies, scaling proportionally for larger bodies. Under sustained high-throughput load, log entry allocation drives significant GC pressure:

Request Rate Response Body Size Log Data Generated Per Minute
1 req/s 1 KB ~1 MB
10 req/s 1 KB ~12 MB
10 req/s 100 KB ~120 MB
1 req/s 1 MB+ ~120 MB

Log entries are stored in a bounded circular queue (maxLogEntries), so total memory usage does not grow indefinitely. However, the constant allocation and eviction of log entries creates GC pressure. When the JVM heap fills up, the garbage collector runs more frequently and for longer, causing pauses that make MockServer appear to freeze. In extreme cases, the JVM may spend almost all of its time in garbage collection, effectively halting request processing.

Large response bodies amplify this problem significantly. A single expectation returning a 10 MB response at 1 request per second generates over 600 MB of log data per minute — far more than a default heap can handle. Even with ring buffer eviction, the JVM must allocate and then garbage-collect these large objects continuously.

Note: Expectations with large response bodies also consume heap proportionally (e.g., a 50 KB response body results in ~55-75 KB per stored expectation). If you have many expectations with large bodies, reduce maxExpectations as well.

How To Fix It

Apply one or more of the following, depending on your use case:

Fix When To Use Trade-off
Increase JVM heap size Always recommended for large responses or high request rates Uses more container/host memory
Reduce maxLogEntries The single most effective fix — fewer entries means less memory and less GC pressure Fewer requests available for verification
Reduce maxExpectations When expectations contain large response bodies Fewer expectations can be stored simultaneously
Switch to ZGC (-XX:+UseZGC) Heap ≥ 4 GB and matcher latency matters — typically gives single-digit-millisecond GC pauses where G1 commonly sits in the 50–200 ms range under sustained allocation Fixed memory overhead (less attractive below ~4 GB); set -Xms and -Xmx to the same value (e.g. -Xms4g -Xmx4g) so the heap is pre-committed

Note on GC selection: Java 17 makes ZGC production-ready in every JDK distribution MockServer supports. For deployments with deep ring buffers (high maxLogEntries) or large heaps, -XX:+UseZGC can reduce p99 matcher latency by holding stop-the-world pauses to the single-digit-millisecond range (typically 1–5 ms in Java 17's non-generational ZGC). For small-fixture deployments (a sidecar in a test pipeline), the default GC is fine — ZGC's fixed overhead isn't worth it below ~4 GB heap. In containerised deployments using ZGC, size the container memory limit at ~1.5× your -Xmx value to leave headroom for JVM overhead (code cache, metaspace, thread stacks) and Netty's direct buffer pool. Note that ZGC multi-maps the same physical pages for its coloured-pointer scheme; under some cgroup RSS-accounting modes those pages are counted multiple times against the container limit, so the process can be OOM-killed even though the actual physical footprint fits (e.g. -Xmx4g--memory=6g). Shenandoah is not recommended — it is not available in Oracle JDK 17 and not universally available across all JDK distributions, so ZGC is the simpler choice.

Note on logLevel and disableLogging: Setting logLevel to WARN reduces diagnostic TRACE/DEBUG log entries but does not prevent request/response recording — the memory-intensive log entries (received requests, matched expectations, and responses) are always stored regardless of log level, as they are required for verification. Similarly, disableLogging only suppresses system-out output and does not reduce memory usage. To reduce memory, lower maxLogEntries or increase heap size.

Note on logLevel and matching throughput: while stored log entries are independent of log level (above), the transient per-request allocation on the matching hot path is not. At INFO, every request that scans expectations builds and logs a diagnostic “matched”/“did not match because…” message per matcher; below INFO that work — the per-matcher log entry and the human-readable “because” string assembly — is skipped entirely. For a deployment with many expectations under sustained load this is the single largest matching-path allocation, so running at WARN noticeably cuts allocation churn and GC pressure (it does not change which requests match, only whether the diagnostic narrative is produced). This is purely a throughput/GC lever; it is independent of the steady-state memory footprint controlled by maxLogEntries.

Recommended Configurations

High-throughput with small responses (e.g., API mocking at >10 req/s with <10 KB bodies):

docker run -d --rm -p 1080:1080 \
  -e MOCKSERVER_MAX_LOG_ENTRIES=5000 \
  mockserver/mockserver

Large response bodies (e.g., responses >100 KB):

docker run -d --rm -p 1080:1080 \
  -e JAVA_TOOL_OPTIONS="-Xmx1g" \
  -e MOCKSERVER_MAX_LOG_ENTRIES=1000 \
  -e MOCKSERVER_MAX_EXPECTATIONS=100 \
  mockserver/mockserver

Maximum throughput, minimal memory (verification limited to most recent requests):

docker run -d --rm -p 1080:1080 \
  -e JAVA_TOOL_OPTIONS="-Xmx512m" \
  -e MOCKSERVER_MAX_LOG_ENTRIES=100 \
  -e MOCKSERVER_LOG_LEVEL=WARN \
  mockserver/mockserver

MOCKSERVER_LOG_LEVEL=WARN drops the per-matcher diagnostic logging on the matching hot path (see the note above), which is the largest matching-path allocation when many expectations are registered. If your matchers rely heavily on regular expressions and your patterns and inputs are trusted, also add -e MOCKSERVER_REGEX_MATCHING_TIMEOUT_MILLIS=0 to evaluate regexes inline and skip the per-regex thread hand-off (this removes the catastrophic-backtracking guard — see Regex Matching Timeout).

Configuring JVM Heap Size

The MockServer Docker image caps the JVM heap at 75% of the container's memory limit (-XX:MaxRAMPercentage=75.0), so the in-memory ring buffers size off a bounded heap. Always run the container with an explicit memory limit (for example --memory=1g, or resources.limits.memory in Kubernetes) — without one the JVM sizes its heap off the host's total memory, and the default ring sizes (maxLogEntries and maxExpectations, which derive from available heap) scale up with it, so MockServer can be OOM-killed under load. This cap only applies when you have not set an explicit heap; to change it, set an explicit -Xmx via the JAVA_TOOL_OPTIONS environment variable (a different -XX:MaxRAMPercentage passed via JAVA_TOOL_OPTIONS will not take effect, because the image's entrypoint applies its own value last):

docker run -d --rm -p 1080:1080 \
  -e JAVA_TOOL_OPTIONS="-Xmx512m" \
  mockserver/mockserver

When running with docker compose:

services:
  mockServer:
    image: mockserver/mockserver
    ports:
      - "1080:1080"
    environment:
      JAVA_TOOL_OPTIONS: "-Xmx512m"
      MOCKSERVER_MAX_LOG_ENTRIES: "5000"

When running as a standalone JAR:

java -Xmx512m -jar mockserver-netty.jar -serverPort 1080

Monitoring Memory Usage

To diagnose memory issues, enable CSV memory tracking:

docker run -d --rm -p 1080:1080 \
  -e MOCKSERVER_OUTPUT_MEMORY_USAGE_CSV=true \
  -e MOCKSERVER_MEMORY_USAGE_CSV_DIRECTORY=/config \
  -v $(pwd):/config \
  mockserver/mockserver

This creates a memoryUsage_<date>.csv file that records heap usage, log entry count, and expectation count over time. If you see heap usage consistently near the maximum, increase -Xmx or reduce maxLogEntries.

 

Proxying LLM / Large-Body Traffic Without OOM

TL;DR: enable disk capture so every exchange is durable, and set a byte budget so the in-memory log stays bounded. Memory never grows unbounded; disk holds the complete session history.

When MockServer proxies LLM traffic — tool schemas, growing conversation context, SSE chunk accumulation — individual request/response bodies can be hundreds of kilobytes each. The in-memory event log is normally bounded only by entry count (maxLogEntries), not by body size, so even a few thousand LLM exchanges can exhaust the heap.

Two complementary settings address this:

Setting What it does When to use
maxEventLogSizeInBytes Caps the total request+response body bytes held in memory. Once exceeded, the oldest entries are evicted (oldest-first), in addition to the entry-count bound. Always, when proxying traffic with large bodies. Set it well under the JVM heap — for a 2 GB heap, 256 MB (268435456) is a good starting point.
persistRecordedRequestsToDisk Appends every proxied exchange — full request and response — as a single NDJSON line to a file, flushed immediately. The file is the durable record: entries evicted from the in-memory window are never lost from disk. Always paired with maxEventLogSizeInBytes. The disk write happens before any in-memory truncation, so the archive is always full-fidelity.

Recommended combo for LLM / large-body capture:

java -Xmx2g \
  -Dmockserver.maxLogEntries=5000 \
  -Dmockserver.maxEventLogSizeInBytes=268435456 \
  -Dmockserver.persistRecordedRequestsToDisk=true \
  -Dmockserver.persistedRecordedRequestsPath=recordedRequests.ndjson \
  -jar mockserver-netty.jar -serverPort 1080

With this configuration:

  • Every proxied exchange is written to recordedRequests.ndjson in full as it completes
  • The in-memory log retains at most the most recent 256 MB of body bytes (plus up to 5,000 entries by count) — the dashboard shows this recent window
  • Older entries evicted from memory are still on disk — nothing is lost

The mockserver-ui/scripts/launch-with-llm-capture.sh script uses exactly this combination by default (2 GB heap, 256 MB byte budget, NDJSON disk capture). Run it with a tool name to start MockServer as an HTTPS proxy capturing that tool's LLM traffic:

./mockserver-ui/scripts/launch-with-llm-capture.sh opencode

Optional secondary valve — maxLoggedBodyBytes: when set to a positive value, bodies are truncated in memory beyond that many bytes (the in-memory copy gets a x-mockserver-body-truncated: <originalLength> header). The disk write is not affected. Use this only when you want the dashboard to show abbreviated bodies — leave it at 0 (the default) when the byte-budget eviction (maxEventLogSizeInBytes) is sufficient.

Security — data at rest: the recordedRequests.ndjson archive contains the full recorded request and response bodies on disk, which for proxied LLM and API traffic can include credentials (Authorization headers, API keys) and other sensitive data. The archive honours redactSecretsInLog — enable it to mask known secret headers and configured body fields in the file just as they are masked in the dashboard. Treat the file as sensitive regardless: store it on a protected volume and delete it when you are done. The capture launcher truncates it at the start of each session (unless you pass --keep-log).

 

Scalability Configuration:

When enabled (the default), MockServer uses the native Linux epoll transport for higher throughput and lower latency. This is also required for transparent-proxy SO_ORIGINAL_DST resolution, which needs epoll socket channels to read the original destination address from iptables REDIRECT rules.

On non-Linux platforms (macOS, Windows) this setting has no effect — MockServer transparently falls back to the Java NIO transport regardless. Set to false to force the NIO transport on all platforms, including Linux.

This property is read at start-up only.

Type: boolean Default: true

Java Code:

ConfigurationProperties.useNativeTransport(boolean enable)

System Property:

-Dmockserver.useNativeTransport=...

Environment Variable:

MOCKSERVER_USE_NATIVE_TRANSPORT=...

Property File:

mockserver.useNativeTransport=...

Example:

-Dmockserver.useNativeTransport=true

Number of threads for main event loop

These threads are used for fast non-blocking activities such as:

  • reading and de-serialise all requests
  • serialising and writing control plane responses
  • adding, updating or removing expectations
  • verifying requests or request sequences
  • retrieving logs

Expectation actions are handled in a separate thread pool to ensure slow object or class callbacks and response / forward delays do not impact the main event loop.

Type: int Default: 5

Java Code:

ConfigurationProperties.nioEventLoopThreadCount(int count)

System Property:

-Dmockserver.nioEventLoopThreadCount=...

Environment Variable:

MOCKSERVER_NIO_EVENT_LOOP_THREAD_COUNT=...

Property File:

mockserver.nioEventLoopThreadCount=...

Example:

-Dmockserver.nioEventLoopThreadCount="5"

Number of threads for the action handler thread pool

These threads are used for handling actions such as:

  • serialising and writing expectation or proxied responses
  • handling response delays in a non-blocking way (i.e. using a scheduler)
  • executing class callbacks
  • handling method / closure callbacks (using web sockets)

Type: int Default: maximum of 5 or available processors count

Java Code:

ConfigurationProperties.actionHandlerThreadCount(int count)

System Property:

-Dmockserver.actionHandlerThreadCount=...

Environment Variable:

MOCKSERVER_ACTION_HANDLER_THREAD_COUNT=...

Property File:

mockserver.actionHandlerThreadCount=...

Example:

-Dmockserver.actionHandlerThreadCount="5"

Number of threads for client event loop when calling downstream

These threads are used for fast non-blocking activities such as, reading and de-serialise all requests and responses

Type: int Default: 5

Java Code:

ConfigurationProperties.clientNioEventLoopThreadCount(int count)

System Property:

-Dmockserver.clientNioEventLoopThreadCount=...

Environment Variable:

MOCKSERVER_CLIENT_NIO_EVENT_LOOP_THREAD_COUNT=...

Property File:

mockserver.clientNioEventLoopThreadCount=...

Example:

-Dmockserver.clientNioEventLoopThreadCount="5"

Number of threads for each expectation with a method / closure callback (i.e. web socket client) in the org.mockserver.client.MockServerClient

This setting only effects the Java client and how requests each method / closure callbacks it can handle, the default is 5 which should be suitable except in extreme cases.

Type: int Default: 5

Java Code:

ConfigurationProperties.webSocketClientEventLoopThreadCount(int count)

System Property:

-Dmockserver.webSocketClientEventLoopThreadCount=...

Environment Variable:

MOCKSERVER_WEB_SOCKET_CLIENT_EVENT_LOOP_THREAD_COUNT=...

Property File:

mockserver.webSocketClientEventLoopThreadCount=...

Example:

-Dmockserver.webSocketClientEventLoopThreadCount="5"

Maximum time allowed in milliseconds for any future to wait, for example when waiting for a response over a web socket callback.

Type: long Default: 90000

Java Code:

ConfigurationProperties.maxFutureTimeout(long milliseconds)

System Property:

-Dmockserver.maxFutureTimeout=...

Environment Variable:

MOCKSERVER_MAX_FUTURE_TIMEOUT=...

Property File:

mockserver.maxFutureTimeout=...

Example:

-Dmockserver.maxFutureTimeout="90000"

If true (the default) request matchers will fail on the first non-matching field, if false request matchers will compare all fields.

Set to false when debugging matching issues to see all mismatching fields in a single log entry. See Troubleshooting Matching for a step-by-step guide.

Type: boolean Default: true

Java Code:

ConfigurationProperties.matchersFailFast(boolean enable)

System Property:

-Dmockserver.matchersFailFast=...

Environment Variable:

MOCKSERVER_MATCHERS_FAIL_FAST=...

Property File:

mockserver.matchersFailFast=...

Example:

-Dmockserver.matchersFailFast="false"

The the minimum level of logs to record in the event log and to output to system out (if system out log output is not disabled). The lower the log level the more log entries will be captured, particularly at TRACE level logging.

Type: string Default: INFO

Java Code:

ConfigurationProperties.logLevel(String level)

System Property:

-Dmockserver.logLevel=...

Environment Variable:

MOCKSERVER_LOG_LEVEL=...

Property File:

mockserver.logLevel=...

The log level, which can be TRACE, DEBUG, INFO, WARN, ERROR, OFF, FINEST, FINE, INFO, WARNING, SEVERE

Example:

-Dmockserver.logLevel="DEBUG"

Disable logging to the system output

Type: boolean Default: false

Java Code:

ConfigurationProperties.disableSystemOut(boolean disableSystemOut)

System Property:

-Dmockserver.disableSystemOut=...

Environment Variable:

MOCKSERVER_DISABLE_SYSTEM_OUT=...

Property File:

mockserver.disableSystemOut=...

Example:

-Dmockserver.disableSystemOut="true"

Disable logging output to system out. Request/response log entries are still recorded in memory for verification.

Type: boolean Default: false

Java Code:

ConfigurationProperties.disableLogging(boolean disableLogging)

System Property:

-Dmockserver.disableLogging=...

Environment Variable:

MOCKSERVER_DISABLE_LOGGING=...

Property File:

mockserver.disableLogging=...

Example:

-Dmockserver.disableLogging="true"

Maximum request body size in bytes that conversation-aware LLM matchers will parse. LLM conversation matchers (whenLatestMessageContains, whenContainsToolResultFor, etc.) parse the inbound request body as JSON to extract the message history. For deep conversation histories or large tool results, this parse step is proportional to body size.

Requests whose body exceeds this cap skip conversation-aware matching and are treated as a no-match for conversation predicates (the scenario state machine is unaffected). Increase this value only when your LLM conversations regularly include very large tool results or long message histories. Reduce it in memory-constrained environments to bound the maximum allocation per matching attempt.

Type: int Default: 1048576 (1 MiB) Range: 16384 (16 KiB) — 67108864 (64 MiB)

Java Code:

ConfigurationProperties.maxLlmConversationBodySize(int size)
Configuration.maxLlmConversationBodySize(Integer size)

System Property:

-Dmockserver.maxLlmConversationBodySize=...

Environment Variable:

MOCKSERVER_MAX_LLM_CONVERSATION_BODY_SIZE=...

Property File:

mockserver.maxLlmConversationBodySize=...

Example:

-Dmockserver.maxLlmConversationBodySize="4194304"
 

Socket Configuration:

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"
 

Http Request Parsing Configuration:

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 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"
 

CORS Configuration:

Enable CORS for MockServer REST API so that the API can be used for javascript running in browsers, such as selenium

Type: boolean Default: false

Java Code:

ConfigurationProperties.enableCORSForAPI(boolean enableCORSForAPI)

System Property:

-Dmockserver.enableCORSForAPI=...

Environment Variable:

MOCKSERVER_ENABLE_CORS_FOR_API=...

Property File:

mockserver.enableCORSForAPI=...

Example:

-Dmockserver.enableCORSForAPI="true"

Enable CORS for all responses from MockServer, including the REST API and expectation responses

Type: boolean Default: false

Java Code:

ConfigurationProperties.enableCORSForAllResponses(boolean enableCORSForAllResponses)

System Property:

-Dmockserver.enableCORSForAllResponses=...

Environment Variable:

MOCKSERVER_ENABLE_CORS_FOR_ALL_RESPONSES=...

Property File:

mockserver.enableCORSForAllResponses=...

Example:

-Dmockserver.enableCORSForAllResponses="true"

The value used for CORS in the access-control-allow-origin header.

Note: To ensure access-control-allow-credentials works correctly, when corsAllowCredentials is true the CORS header access-control-allow-origin will set its value using the origin header on requests instead of corsAllowOrigin property.

Type: string Default: ""

Java Code:

ConfigurationProperties.corsAllowOrigin(String corsAllowOrigin)

System Property:

-Dmockserver.corsAllowOrigin=...

Environment Variable:

MOCKSERVER_CORS_ALLOW_ORIGIN=...

Property File:

mockserver.corsAllowOrigin=...

Example:

-Dmockserver.corsAllowOrigin="*"

The value used for CORS in the access-control-allow-methods header.

Type: string Default: ""

Java Code:

ConfigurationProperties.corsAllowMethods(String corsAllowMethods)

System Property:

-Dmockserver.corsAllowMethods=...

Environment Variable:

MOCKSERVER_CORS_ALLOW_METHODS=...

Property File:

mockserver.corsAllowMethods=...

Example:

-Dmockserver.corsAllowMethods="CONNECT, DELETE, GET, HEAD, OPTIONS, POST, PUT, PATCH, TRACE"

Default value used for CORS in the access-control-allow-headers and access-control-expose-headers headers.

In addition to this default value any headers specified in the request header access-control-request-headers also get added to access-control-allow-headers and access-control-expose-headers headers in a CORS response.

Type: string Default: ""

Java Code:

ConfigurationProperties.corsAllowHeaders(String corsAllowHeaders)

System Property:

-Dmockserver.corsAllowHeaders=...

Environment Variable:

MOCKSERVER_CORS_ALLOW_HEADERS=...

Property File:

mockserver.corsAllowHeaders=...

Example:

-Dmockserver.corsAllowHeaders="Allow, Content-Encoding, Content-Length, Content-Type, ETag, Expires, Last-Modified, Location, Server, Vary, Authorization"

The value used for CORS in the access-control-allow-credentials header.

Note: To ensure access-control-allow-credentials works correctly, when corsAllowCredentials is true the CORS header access-control-allow-origin will set its value using the origin header on requests instead of corsAllowOrigin property.

Type: boolean Default: false

Java Code:

ConfigurationProperties.corsAllowCredentials(boolean allow)

System Property:

-Dmockserver.corsAllowCredentials=...

Environment Variable:

MOCKSERVER_CORS_ALLOW_CREDENTIALS=...

Property File:

mockserver.corsAllowCredentials=...

Example:

-Dmockserver.corsAllowCredentials="true"

The value used for CORS in the access-control-max-age header.

Type: int Default: 0

Java Code:

ConfigurationProperties.corsMaxAgeInSeconds(int maxAgeInSeconds)

System Property:

-Dmockserver.corsMaxAgeInSeconds=...

Environment Variable:

MOCKSERVER_CORS_MAX_AGE_IN_SECONDS=...

Property File:

mockserver.corsMaxAgeInSeconds=...

Example:

-Dmockserver.corsMaxAgeInSeconds=300
 

Default Response Headers Configuration:

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"
 

Template Restriction Configuration:

Set comma separate list of classes not allowed to be used by javascript templates

Type: string Default: ""

Java Code:

ConfigurationProperties.javascriptDisallowedClasses(String javascriptDisallowedClasses)

System Property:

-Dmockserver.javascriptDisallowedClasses=...

Environment Variable:

MOCKSERVER_JAVASCRIPT_DISALLOWED_CLASSES=...

Property File:

mockserver.javascriptDisallowedClasses=...

Example:

-Dmockserver.javascriptDisallowedClasses="java.lang.Runtime,java.lang.Class"

Set comma separate list of text not allowed to be contained in javascript templates

Type: string Default: ""

Java Code:

ConfigurationProperties.javascriptDisallowedText(String javascriptDisallowedText)

System Property:

-Dmockserver.javascriptDisallowedText=...

Environment Variable:

MOCKSERVER_JAVASCRIPT_DISALLOWED_TEXT=...

Property File:

mockserver.javascriptDisallowedText=...

Example:

-Dmockserver.javascriptDisallowedText="getRuntime().exec"

Maximum time in milliseconds a JavaScript response template is allowed to run before it is cancelled. A runaway or malicious template (for example one containing an infinite loop) would otherwise pin the worker thread handling that request indefinitely; this cap aborts the evaluation with a clear timeout error instead, so the request fails fast and the thread is freed.

The default of 5000 (5 seconds) is far longer than any legitimate template needs — a normal template evaluates in well under a second — so it will not affect real templates. Increase it only if you run unusually heavy templates, or set it to 0 (or a negative value) to disable the timeout entirely and restore the previous unbounded behaviour.

Type: long Default: 5000

Java Code:

ConfigurationProperties.javascriptTemplateExecutionTimeout(long millis)

System Property:

-Dmockserver.javascriptTemplateExecutionTimeout=...

Environment Variable:

MOCKSERVER_JAVASCRIPT_TEMPLATE_EXECUTION_TIMEOUT=...

Property File:

mockserver.javascriptTemplateExecutionTimeout=...

Example:

-Dmockserver.javascriptTemplateExecutionTimeout="2000"

If true class loading is not allowed in velocity templates

Type: boolean Default: false

Java Code:

ConfigurationProperties.velocityDisallowClassLoading(boolean velocityDisallowClassLoading)

System Property:

-Dmockserver.velocityDisallowClassLoading=...

Environment Variable:

MOCKSERVER_VELOCITY_DISALLOW_CLASS_LOADING=...

Property File:

mockserver.velocityDisallowClassLoading=...

Example:

-Dmockserver.velocityDisallowClassLoading="true"

Set comma separate list of text not allowed to be contained in velocity templates

Type: string Default: ""

Java Code:

ConfigurationProperties.velocityDisallowedText(String velocityDisallowedText)

System Property:

-Dmockserver.velocityDisallowedText=...

Environment Variable:

MOCKSERVER_VELOCITY_DISALLOWED_TEXT=...

Property File:

mockserver.velocityDisallowedText=...

Example:

-Dmockserver.velocityDisallowedText="request.class"

Set comma separate list of text not allowed to be contained in mustache templates

Type: string Default: ""

Java Code:

ConfigurationProperties.mustacheDisallowedText(String mustacheDisallowedText)

System Property:

-Dmockserver.mustacheDisallowedText=...

Environment Variable:

MOCKSERVER_MUSTACHE_DISALLOWED_TEXT=...

Property File:

mockserver.mustacheDisallowedText=...

Example:

-Dmockserver.mustacheDisallowedText="request.method"

Seed for the template faker sample-data helper (Velocity $faker, Mustache {{faker.*}}, JavaScript faker). By default faker is unseeded, so faker-driven templates produce different, random values on every render.

Set a non-zero value to seed faker deterministically so faker-driven templates generate reproducible fixtures across runs — useful when you want your generated test data to be stable from one run to the next. The seed produces a deterministic sequence of values for a given order of renders; determinism is strongest when fixtures are generated sequentially.

The default of 0 leaves faker unseeded, so existing templates are unaffected.

Type: long Default: 0

Java Code:

ConfigurationProperties.templateFakerSeed(long seed)

System Property:

-Dmockserver.templateFakerSeed=...

Environment Variable:

MOCKSERVER_TEMPLATE_FAKER_SEED=...

Property File:

mockserver.templateFakerSeed=...

Example:

-Dmockserver.templateFakerSeed="42"
 

Initialization & Persistence Configuration:

The class (and package) used to initialize expectations in MockServer at startup, if set MockServer will load and call this class to initialise expectations when is starts.

Type: string Default: null

Java Code:

ConfigurationProperties.initializationClass(String initializationClass)

System Property:

-Dmockserver.initializationClass=...

Environment Variable:

MOCKSERVER_INITIALIZATION_CLASS=...

Property File:

mockserver.initializationClass=...

Spring @MockServerTest:

@MockServerTest("mockserver.initializationClass=org.mockserver.server.initialize.ExpectationInitializerExample")

Example:

-Dmockserver.initializationClass="org.mockserver.server.initialize.ExpectationInitializerExample"

The path to the json file used to initialize expectations in MockServer at startup, if set MockServer will load this file and initialise expectations for each item in the file when is starts.

The expected format of the file is a JSON array of expectations, as per the REST API format

Type: string Default: null

Java Code:

ConfigurationProperties.initializationJsonPath(String initializationJsonPath)

System Property:

-Dmockserver.initializationJsonPath=...

Environment Variable:

MOCKSERVER_INITIALIZATION_JSON_PATH=...

Property File:

mockserver.initializationJsonPath=...

Example:

-Dmockserver.initializationJsonPath="org/mockserver/server/initialize/initializerJson.json"

The path to the OpenAPI spec file used to initialize expectations in MockServer at startup, if set MockServer will load this file and create expectations for each operation when it starts.

The file can be a YAML (.yaml, .yml) or JSON (.json) OpenAPI v3 specification. MockServer will generate an expectation for each operation defined in the spec, with example responses derived from the schema.

To watch multiple files use file globs as documented here: glob patterns

Type: string Default: null

Java Code:

ConfigurationProperties.initializationOpenAPIPath(String initializationOpenAPIPath)

System Property:

-Dmockserver.initializationOpenAPIPath=...

Environment Variable:

MOCKSERVER_INITIALIZATION_OPENAPI_PATH=...

Property File:

mockserver.initializationOpenAPIPath=...

Example:

-Dmockserver.initializationOpenAPIPath="/config/petstore.yaml"

If enabled the initialization JSON file and OpenAPI file will be watched for changes, any changes found will result in expectations being created, removed or updated by matching against their key.

If duplicate keys exist only the last duplicate key in the file will be processed and all duplicates except the last duplicate will be removed.

The order of expectations in the file is the order in which they are created if they are new, however, re-ordering existing expectations does not change the order they are matched against incoming requests.

Type: boolean Default: false

Java Code:

ConfigurationProperties.watchInitializationJson(boolean enable)

System Property:

-Dmockserver.watchInitializationJson=...

Environment Variable:

MOCKSERVER_WATCH_INITIALIZATION_JSON=...

Property File:

mockserver.watchInitializationJson=...

Example:

-Dmockserver.watchInitializationJson="false"

If enabled a failure to load any expectation initializer (a malformed initialization JSON or OpenAPI file, or a broken initialization class) will fail server startup with an exception, instead of logging a warning and continuing with zero expectations from that source.

By default (false) a broken initializer is logged once at WARN and MockServer still starts — which can silently leave you with missing mocks in CI or Kubernetes. Enable this when a half-initialized server is worse than a crash, so the failure is loud and visible.

For slow (but valid) initializers, use the readiness probe at GET /mockserver/ready instead, which returns 503 until initialization completes and 200 thereafter.

Type: boolean Default: false

Java Code:

ConfigurationProperties.failOnInitializationError(boolean enable)

System Property:

-Dmockserver.failOnInitializationError=...

Environment Variable:

MOCKSERVER_FAIL_ON_INITIALIZATION_ERROR=...

Property File:

mockserver.failOnInitializationError=...

Example:

-Dmockserver.failOnInitializationError="true"

Enable the persisting of expectations as json, which is updated whenever the expectation state is updated (i.e. add, clear, expires, etc)

Type: boolean Default: false

Java Code:

ConfigurationProperties.persistExpectations(boolean persistExpectations)

System Property:

-Dmockserver.persistExpectations=...

Environment Variable:

MOCKSERVER_PERSIST_EXPECTATIONS=...

Property File:

mockserver.persistExpectations=...

Example:

-Dmockserver.persistExpectations="true"

The file path used to save persisted expectations as json, which is updated whenever the expectation state is updated (i.e. add, clear, expires, etc)

Type: string Default: persistedExpectations.json

Java Code:

ConfigurationProperties.persistedExpectationsPath(String persistedExpectationsPath)

System Property:

-Dmockserver.persistedExpectationsPath=...

Environment Variable:

MOCKSERVER_PERSISTED_EXPECTATIONS_PATH=...

Property File:

mockserver.persistedExpectationsPath=...

Example:

-Dmockserver.persistedExpectationsPath="org/mockserver/server/initialize/initializerJson.json"

Enable the persisting of recorded expectations (proxy traffic) as json, which is updated whenever a new request is forwarded through the proxy.

The persisted file can be loaded on restart using initializationJsonPath to replay recorded traffic as mock expectations.

Type: boolean Default: false

Java Code:

ConfigurationProperties.persistRecordedExpectations(boolean enable)

System Property:

-Dmockserver.persistRecordedExpectations=...

Environment Variable:

MOCKSERVER_PERSIST_RECORDED_EXPECTATIONS=...

Property File:

mockserver.persistRecordedExpectations=...

Example:

-Dmockserver.persistRecordedExpectations="true"

The file path used to save persisted recorded expectations as json, which is updated whenever a new request is forwarded through the proxy.

Type: string Default: persistedRecordedExpectations.json

Java Code:

ConfigurationProperties.persistedRecordedExpectationsPath(String persistedRecordedExpectationsPath)

System Property:

-Dmockserver.persistedRecordedExpectationsPath=...

Environment Variable:

MOCKSERVER_PERSISTED_RECORDED_EXPECTATIONS_PATH=...

Property File:

mockserver.persistedRecordedExpectationsPath=...

Example:

-Dmockserver.persistedRecordedExpectationsPath="recordedExpectations.json"

When enabled, every proxied exchange (FORWARDED_REQUEST log event) is appended to an NDJSON file as it completes — one compact JSON object per line (request + response), flushed immediately after each line. The file is opened in append mode, so it survives process restarts and captures the complete session history even as the in-memory event log window evicts old entries under a byte budget.

This is the recommended pairing with maxEventLogSizeInBytes for proxying LLM traffic or any workload with large bodies: disk holds everything durably; memory stays bounded. See Proxying LLM / Large-Body Traffic Without OOM for the full worked example.

Note: disk capture writes the full body before any in-memory truncation (maxLoggedBodyBytes) is applied, so the archive is always complete even when the dashboard shows truncated bodies.

Type: boolean Default: false

Java Code:

ConfigurationProperties.persistRecordedRequestsToDisk(boolean enable)
Configuration.persistRecordedRequestsToDisk(Boolean enable)

System Property:

-Dmockserver.persistRecordedRequestsToDisk=...

Environment Variable:

MOCKSERVER_PERSIST_RECORDED_REQUESTS_TO_DISK=...

Property File:

mockserver.persistRecordedRequestsToDisk=...

Example:

-Dmockserver.persistRecordedRequestsToDisk="true"

The file path for the NDJSON archive written when persistRecordedRequestsToDisk is enabled. The file is opened in append mode on startup, so a fresh session extends the same file. Truncate it manually between sessions, or use --keep-log / omit to start fresh (the launch-with-llm-capture.sh script truncates it automatically unless --keep-log is passed).

Type: string Default: recordedRequests.ndjson

Java Code:

ConfigurationProperties.persistedRecordedRequestsPath(String path)
Configuration.persistedRecordedRequestsPath(String path)

System Property:

-Dmockserver.persistedRecordedRequestsPath=...

Environment Variable:

MOCKSERVER_PERSISTED_RECORDED_REQUESTS_PATH=...

Property File:

mockserver.persistedRecordedRequestsPath=...

Example:

-Dmockserver.persistedRecordedRequestsPath="recordedRequests.ndjson"
 

Verification Configuration:

The maximum number of requests to return in verification failure result, if more expectations are found the failure result does not list them separately

Type: int Default: 10

Java Code:

ConfigurationProperties.maximumNumberOfRequestToReturnInVerificationFailure(Integer maximumNumberOfRequestToReturnInVerificationFailure)

System Property:

-Dmockserver.maximumNumberOfRequestToReturnInVerificationFailure=...

Environment Variable:

MOCKSERVER_MAXIMUM_NUMBER_OF_REQUESTS_TO_RETURN_IN_VERIFICATION_FAILURE=...

Property File:

mockserver.maximumNumberOfRequestToReturnInVerificationFailure=...

Example:

-Dmockserver.maximumNumberOfRequestToReturnInVerificationFailure="20"
 

Proxying Configuration:

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:

  • pathPrefix (required) — the incoming path prefix to match, e.g. /api/
  • targetUri (required) — the upstream server URI including path, e.g. https://backend:8443/services/
  • preserveHost (optional, default false) — if true, the original Host header is preserved instead of being adjusted to match the target

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"
 

Data Plane Authentication Configuration:

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"
 

Streaming Proxy Configuration:

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):

  1. Provider environment conventions — if OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY, or OLLAMA_HOST is already set (the same variables each provider SDK reads), MockServer auto-detects a backend. No MockServer configuration needed.
  2. A single default backend via the properties below.
  3. Named backends via a JSON file (mockserver.llmBackendsConfig) for multiple or advanced setups.

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.

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 400 when tracking is disabled, 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"
 

Dashboard Analytics Configuration:

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:

  • Standard Docker image: docker-standard
  • GraalJS Docker image: docker-graaljs
  • Clustered Docker image: docker-clustered
  • Helm chart deployment: helm
  • Official binary launcher bundles: binary

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 versionv1 (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=...

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"
 

Liveness Configuration:

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"
 

Multi-Tenancy (Namespacing) Configuration:

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"
 

OpenAPI Configuration:

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"
 

Async Messaging Configuration:

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"
 

MCP (Model Context Protocol) Configuration:

Enable or disable the MCP (Model Context Protocol) endpoint at /mockserver/mcp.

When enabled, MockServer exposes a JSON-RPC 2.0 endpoint implementing the MCP Streamable HTTP transport, allowing AI coding assistants to interact with MockServer programmatically — creating expectations, verifying requests, retrieving traffic, and debugging mismatches.

The MCP endpoint enforces the same control plane authentication (mTLS and/or JWT) as the REST API.

Type: boolean Default: true

Java Code:

ConfigurationProperties.mcpEnabled(boolean enable)

System Property:

-Dmockserver.mcpEnabled=...

Environment Variable:

MOCKSERVER_MCP_ENABLED=...

Property File:

mockserver.mcpEnabled=...

Example:

-Dmockserver.mcpEnabled="false"
 

WASM Configuration:

Enable or disable WASM body matching. When enabled, users can upload WebAssembly modules as custom body matchers. WASM modules run inside a pure-Java interpreter (chicory) and are sandboxed from the host. See WASM Custom Rules for details.

Type: boolean Default: false

Java Code:

ConfigurationProperties.wasmEnabled(boolean enable)

System Property:

-Dmockserver.wasmEnabled=...

Environment Variable:

MOCKSERVER_WASM_ENABLED=...

Property File:

mockserver.wasmEnabled=...

Example:

-Dmockserver.wasmEnabled="true"

Maximum number of WASM linear memory pages allowed per module. Each page is 64 KiB, so the default of 256 pages allows up to 16 MiB of linear memory per WASM module. Increase this if your WASM modules need to process large request bodies.

Type: int Default: 256

Java Code:

ConfigurationProperties.wasmMaxMemoryPages(int pages)

System Property:

-Dmockserver.wasmMaxMemoryPages=...

Environment Variable:

MOCKSERVER_WASM_MAX_MEMORY_PAGES=...

Property File:

mockserver.wasmMaxMemoryPages=...

Example:

-Dmockserver.wasmMaxMemoryPages="512"
 

gRPC Configuration:

Enable or disable gRPC protocol support. When enabled and proto descriptors are loaded (via grpcDescriptorDirectory, grpcProtoDirectory, or the PUT /mockserver/grpc/descriptors REST API), MockServer intercepts gRPC requests on HTTP/2 connections, converts protobuf to JSON, and routes them through the standard expectation matching engine. Without loaded descriptors, gRPC interception is not active even when this property is true.

Type: boolean Default: true

Java Code:

ConfigurationProperties.grpcEnabled(boolean enable)

System Property:

-Dmockserver.grpcEnabled=...

Environment Variable:

MOCKSERVER_GRPC_ENABLED=...

Property File:

mockserver.grpcEnabled=...

Example:

-Dmockserver.grpcEnabled="false"

Directory containing pre-compiled proto descriptor set files (.dsc or .desc). MockServer loads all descriptor files from this directory at startup and registers their services for gRPC mocking.

Generate descriptor files using protoc --descriptor_set_out=service.dsc --include_imports service.proto.

Type: string Default: null

Java Code:

ConfigurationProperties.grpcDescriptorDirectory(String directory)

System Property:

-Dmockserver.grpcDescriptorDirectory=...

Environment Variable:

MOCKSERVER_GRPC_DESCRIPTOR_DIRECTORY=...

Property File:

mockserver.grpcDescriptorDirectory=...

Example:

-Dmockserver.grpcDescriptorDirectory="/path/to/descriptors"

Directory containing .proto source files. MockServer compiles these files at startup using protoc and registers their services for gRPC mocking. Requires protoc to be available on the system PATH (or configured via grpcProtocPath).

Type: string Default: null

Java Code:

ConfigurationProperties.grpcProtoDirectory(String directory)

System Property:

-Dmockserver.grpcProtoDirectory=...

Environment Variable:

MOCKSERVER_GRPC_PROTO_DIRECTORY=...

Property File:

mockserver.grpcProtoDirectory=...

Example:

-Dmockserver.grpcProtoDirectory="/path/to/protos"

Path to the protoc compiler binary. Only needed when using grpcProtoDirectory to compile .proto files at startup. If protoc is on the system PATH, the default value works without configuration.

Type: string Default: "protoc"

Java Code:

ConfigurationProperties.grpcProtocPath(String path)

System Property:

-Dmockserver.grpcProtocPath=...

Environment Variable:

MOCKSERVER_GRPC_PROTOC_PATH=...

Property File:

mockserver.grpcProtocPath=...

Example:

-Dmockserver.grpcProtocPath="/usr/local/bin/protoc"
 

DNS Configuration:

Enable or disable the DNS mock server. When enabled, MockServer starts a UDP DNS server that matches incoming DNS queries against expectations. DNS expectations use DnsRequestDefinition for matching and DnsResponse for responses. Supported record types: A, AAAA, CNAME, MX, SRV, TXT, PTR.

Type: boolean Default: false

Java Code:

ConfigurationProperties.dnsEnabled(boolean enable)

System Property:

-Dmockserver.dnsEnabled=...

Environment Variable:

MOCKSERVER_DNS_ENABLED=...

Property File:

mockserver.dnsEnabled=...

Example:

-Dmockserver.dnsEnabled="true"

The UDP port for the DNS mock server. Set to 0 to let the operating system assign an ephemeral port. Use MockServer.getDnsPort() to retrieve the actual bound port at runtime.

Type: integer Default: 0

Java Code:

ConfigurationProperties.dnsPort(int port)

System Property:

-Dmockserver.dnsPort=...

Environment Variable:

MOCKSERVER_DNS_PORT=...

Property File:

mockserver.dnsPort=...

Example:

-Dmockserver.dnsPort="5353"
 

Service Mesh / Sidecar Configuration:

These properties configure MockServer for running as a Kubernetes sidecar with transparent proxy interception. See Transparent Proxy / Sidecar Mode for a full usage guide.

Enable transparent HTTP proxy mode where all connections are treated as proxy requests using the Host header as the forwarding target. This enables iptables REDIRECT-based interception without requiring clients to send explicit HTTP CONNECT requests or configure proxy settings.

When enabled, MockServer reads the Host header from each incoming request to determine the forwarding target. If an expectation matches, MockServer returns the mock response; otherwise it forwards to the original target.

Type: boolean Default: false

Java Code:

ConfigurationProperties.transparentProxyEnabled(boolean enable)

System Property:

-Dmockserver.transparentProxyEnabled=...

Environment Variable:

MOCKSERVER_TRANSPARENT_PROXY_ENABLED=...

Property File:

mockserver.transparentProxyEnabled=...

Example:

-Dmockserver.transparentProxyEnabled="true"

Resolve the original destination of intercepted connections using the Linux TPROXY mechanism instead of REDIRECT. When enabled, the original destination is read from the socket's local address (preserved by the TPROXY iptables target), allowing MockServer to forward to the real destination address rather than relying on the Host header.

Requires Linux, the epoll transport, the CAP_NET_ADMIN capability, and TPROXY iptables rules instead of REDIRECT.

Type: boolean Default: false

Java Code:

ConfigurationProperties.transparentProxyTproxy(boolean enable)

System Property:

-Dmockserver.transparentProxyTproxy=...

Environment Variable:

MOCKSERVER_TRANSPARENT_PROXY_TPROXY=...

Property File:

mockserver.transparentProxyTproxy=...

Example:

-Dmockserver.transparentProxyTproxy="true"

Resolve the original destination of intercepted connections by reading from a pinned eBPF (BPF) hash map, populated by an external cgroup/connect4 BPF program and keyed by socket cookie. This is an alternative to TPROXY for recovering the real destination address.

Requires Linux, the CAP_BPF capability, a BTF-enabled kernel, and the external BPF program that populates the map (see transparentProxyEbpfMapPath).

Type: boolean Default: false

Java Code:

ConfigurationProperties.transparentProxyEbpf(boolean enable)

System Property:

-Dmockserver.transparentProxyEbpf=...

Environment Variable:

MOCKSERVER_TRANSPARENT_PROXY_EBPF=...

Property File:

mockserver.transparentProxyEbpf=...

Example:

-Dmockserver.transparentProxyEbpf="true"

Path to the pinned BPF map used by the eBPF original destination resolver. The map must be a BPF hash map with a u64 key (socket cookie) and a 6-byte value (4-byte IPv4 address + 2-byte port in network byte order).

Only used when transparentProxyEbpf is enabled.

Type: string Default: /sys/fs/bpf/mockserver_orig_dst

Java Code:

ConfigurationProperties.transparentProxyEbpfMapPath(String path)

System Property:

-Dmockserver.transparentProxyEbpfMapPath=...

Environment Variable:

MOCKSERVER_TRANSPARENT_PROXY_EBPF_MAP_PATH=...

Property File:

mockserver.transparentProxyEbpfMapPath=...

Example:

-Dmockserver.transparentProxyEbpfMapPath="/sys/fs/bpf/mockserver_orig_dst"
 

Clustering Configuration:

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.

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...
 

Cloud Blob Store Configuration:

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/).

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"
 

Control Plane Authentication Configuration:

Enable mTLS authentication for control plane interactions (i.e. create expectations, clear, reset, verify, retrieve, stop, etc)

If enabled then all control plane requests need to be received over a mTLS connection where the client's X509 certificates will be validated using the controlPlaneTLSMutualAuthenticationCAChain

It is possible to enable both controlPlaneJWTAuthenticationRequired and controlPlaneTLSMutualAuthenticationRequired but the mTLS will be checked first.

Type: boolean Default: false

Java Code:

ConfigurationProperties.controlPlaneTLSMutualAuthenticationRequired(boolean controlPlaneTLSMutualAuthenticationRequired)

System Property:

-Dmockserver.controlPlaneTLSMutualAuthenticationRequired=...

Environment Variable:

MOCKSERVER_CONTROL_PLANE_TLS_MUTUAL_AUTHENTICATION_REQUIRED=...

Property File:

mockserver.controlPlaneTLSMutualAuthenticationRequired=...

Example:

-Dmockserver.controlPlaneTLSMutualAuthenticationRequired="true"

File system path or classpath location of the CA (i.e. trust) chain to use to validate client X509 certificates if controlPlaneTLSMutualAuthenticationRequired is enabled

Type: string Default: null

Java Code:

ConfigurationProperties.controlPlaneTLSMutualAuthenticationCAChain(String controlPlaneTLSMutualAuthenticationCAChain)

System Property:

-Dmockserver.controlPlaneTLSMutualAuthenticationCAChain=...

Environment Variable:

MOCKSERVER_CONTROL_PLANE_TLS_MUTUAL_AUTHENTICATION_CERTIFICATE_CHAIN=...

Property File:

mockserver.controlPlaneTLSMutualAuthenticationCAChain=...

Example:

-Dmockserver.controlPlaneTLSMutualAuthenticationCAChain="/some/existing/path"

File system path or classpath location of the private key used by MockServerClient when controlPlaneTLSMutualAuthenticationRequired is enabled to ensure control plane request are correctly authorised

For control plane requests to be authorised the private key controlPlanePrivateKeyPath and certificate controlPlaneX509CertificatePath must:

Type: string Default: null

Java Code:

ConfigurationProperties.controlPlanePrivateKeyPath(String controlPlanePrivateKeyPath)

System Property:

-Dmockserver.controlPlanePrivateKeyPath=...

Environment Variable:

MOCKSERVER_CONTROL_PLANE_TLS_PRIVATE_KEY_PATH=...

Property File:

mockserver.controlPlanePrivateKeyPath=...

Example:

-Dmockserver.controlPlanePrivateKeyPath="/some/existing/path"

File system path or classpath location of the certificate used by MockServerClient when controlPlaneTLSMutualAuthenticationRequired is enabled to ensure control plane request are correctly authorised

For control plane requests to be authorised the private key controlPlanePrivateKeyPath and certificate controlPlaneX509CertificatePath must:

Type: string Default: null

Java Code:

ConfigurationProperties.controlPlaneX509CertificatePath(String controlPlaneX509CertificatePath)

System Property:

-Dmockserver.controlPlaneX509CertificatePath=...

Environment Variable:

MOCKSERVER_CONTROL_PLANE_TLS_X509_CERTIFICATE_PATH=...

Property File:

mockserver.controlPlaneX509CertificatePath=...

Example:

-Dmockserver.controlPlaneX509CertificatePath="/some/existing/path"

Enable JWT authentication for control plane interactions (i.e. create expectations, clear, reset, verify, retrieve, stop, etc)

If enabled then all control plane requests need and JWT via a authorization header which is validated using the controlPlaneJWTAuthenticationJWKSource

It is possible to enable both controlPlaneJWTAuthenticationRequired and controlPlaneTLSMutualAuthenticationRequired but the mTLS will be checked first.

Type: boolean Default: false

Java Code:

ConfigurationProperties.controlPlaneJWTAuthenticationRequired(boolean controlPlaneJWTAuthenticationRequired)

System Property:

-Dmockserver.controlPlaneJWTAuthenticationRequired=...

Environment Variable:

MOCKSERVER_CONTROL_PLANE_JWT_AUTHENTICATION_REQUIRED=...

Property File:

mockserver.controlPlaneJWTAuthenticationRequired=...

Example:

-Dmockserver.controlPlaneJWTAuthenticationRequired="true"

URL, file system path or classpath location of the JWK source when controlPlaneJWTAuthenticationRequired is enabled to validate JWT signatures

For control plane requests to be authorised:

  • they must include an authorization header, with a Bearer auth scheme, containing a JWT
  • the JWT should be validated by a key in the JWK source

For details of JWK see the JWK specification

Type: string Default: null

Java Code:

ConfigurationProperties.controlPlaneJWTAuthenticationJWKSource(String controlPlaneJWTAuthenticationJWKSource)

System Property:

-Dmockserver.controlPlaneJWTAuthenticationJWKSource=...

Environment Variable:

MOCKSERVER_CONTROL_PLANE_JWT_AUTHENTICATION_JWK_SOURCE=...

Property File:

mockserver.controlPlaneJWTAuthenticationJWKSource=...

Example:

-Dmockserver.controlPlaneJWTAuthenticationJWKSource="/some/existing/path"

Audience claim (i.e. aud) required when JWT authentication is enabled for control plane requests

Type: string Default: null

Java Code:

ConfigurationProperties.controlPlaneJWTAuthenticationExpectedAudience(String controlPlaneJWTAuthenticationExpectedAudience)

System Property:

-Dmockserver.controlPlaneJWTAuthenticationExpectedAudience=...

Environment Variable:

MOCKSERVER_CONTROL_PLANE_JWT_AUTHENTICATION_EXPECTED_AUDIENCE=...

Property File:

mockserver.controlPlaneJWTAuthenticationExpectedAudience=...

Example:

-Dmockserver.controlPlaneJWTAuthenticationExpectedAudience="mockserver-control-plane"

Matching claims expected when JWT authentication is enabled for control plane requests

Value should be string with comma separated key=value items, for example: scope=internal public,sub=some_subject

Type: string Default: null

Java Code:

ConfigurationProperties.controlPlaneJWTAuthenticationMatchingClaims(Map<String, String> controlPlaneJWTAuthenticationMatchingClaims)

System Property:

-Dmockserver.controlPlaneJWTAuthenticationMatchingClaims=...

Environment Variable:

MOCKSERVER_CONTROL_PLANE_JWT_AUTHENTICATION_MATCHING_CLAIMS=...

Property File:

mockserver.controlPlaneJWTAuthenticationMatchingClaims=...

Example:

-Dmockserver.controlPlaneJWTAuthenticationMatchingClaims="scope=internal,sub=user-123"

Required claims that should exist (i.e. with any value) when JWT authentication is enabled for control plane requests

Value should be string with comma separated values, for example: scope,sub

Type: string Default: null

Java Code:

ConfigurationProperties.controlPlaneJWTAuthenticationRequiredClaims(Set<String> controlPlaneJWTAuthenticationRequiredClaims)

System Property:

-Dmockserver.controlPlaneJWTAuthenticationRequiredClaims=...

Environment Variable:

MOCKSERVER_CONTROL_PLANE_JWT_AUTHENTICATION_REQUIRED_CLAIMS=...

Property File:

mockserver.controlPlaneJWTAuthenticationRequiredClaims=...

Example:

-Dmockserver.controlPlaneJWTAuthenticationRequiredClaims="scope,sub"

Enable verified OIDC authentication for control plane interactions (i.e. create expectations, clear, reset, verify, retrieve, stop, etc) using access tokens issued by an external OpenID Connect identity provider

If enabled then all control plane requests must include a Bearer access token via an authorization header. The token signature is verified against the provider's JWK set, and its issuer, audience, expiry and required scopes are checked. The verified subject (sub) is recorded as the principal in the control plane audit log.

For security, the OIDC handler enforces the following secure-by-default requirements (MockServer will refuse to start the OIDC handler, and fail every control plane request closed with a 401, if any are not met):

  • At least one of controlPlaneOidcIssuer or controlPlaneOidcAudience must be set — without either, any validly-signed token from the JWK set would be accepted regardless of who it was issued for.
  • A remote controlPlaneOidcJwksUri (or issuer used for discovery) must use https://. Plaintext http:// is allowed only for localhost/loopback (local testing).
  • Tokens must carry an exp (expiry) claim, and are verified only against asymmetric signing algorithms (RS*, PS*, ES*, EdDSA) — HMAC and unsigned (alg=none) tokens are always rejected.

When a control plane request fails OIDC authentication the client receives a generic Unauthorized for control plane response; the detailed reason (e.g. expected issuer/audience/scopes) is written only to the MockServer server log.

It is possible to enable controlPlaneOidcAuthenticationRequired alongside controlPlaneTLSMutualAuthenticationRequired and/or controlPlaneJWTAuthenticationRequired, in which case every enabled handler must pass.

Type: boolean Default: false

Java Code:

ConfigurationProperties.controlPlaneOidcAuthenticationRequired(boolean controlPlaneOidcAuthenticationRequired)

System Property:

-Dmockserver.controlPlaneOidcAuthenticationRequired=...

Environment Variable:

MOCKSERVER_CONTROL_PLANE_OIDC_AUTHENTICATION_REQUIRED=...

Property File:

mockserver.controlPlaneOidcAuthenticationRequired=...

Example:

-Dmockserver.controlPlaneOidcAuthenticationRequired="true"

Issuer (i.e. iss) required on control plane OIDC tokens. When controlPlaneOidcJwksUri is not set, the JWKS URI is discovered from this issuer's OIDC discovery document at {issuer}/.well-known/openid-configuration.

Type: string Default: null

Java Code:

ConfigurationProperties.controlPlaneOidcIssuer(String controlPlaneOidcIssuer)

System Property:

-Dmockserver.controlPlaneOidcIssuer=...

Environment Variable:

MOCKSERVER_CONTROL_PLANE_OIDC_ISSUER=...

Property File:

mockserver.controlPlaneOidcIssuer=...

Example:

-Dmockserver.controlPlaneOidcIssuer="https://idp.example.com"

JWKS URI used to verify control plane OIDC token signatures. If not set, it is discovered from the issuer's OIDC discovery document. A remote URI must use https:// (plaintext http:// is permitted only to localhost/loopback); a file or classpath path may also be used.

Type: string Default: null

Java Code:

ConfigurationProperties.controlPlaneOidcJwksUri(String controlPlaneOidcJwksUri)

System Property:

-Dmockserver.controlPlaneOidcJwksUri=...

Environment Variable:

MOCKSERVER_CONTROL_PLANE_OIDC_JWKS_URI=...

Property File:

mockserver.controlPlaneOidcJwksUri=...

Example:

-Dmockserver.controlPlaneOidcJwksUri="https://idp.example.com/.well-known/jwks.json"

Audience claim (i.e. aud) required on control plane OIDC tokens.

Type: string Default: null

Java Code:

ConfigurationProperties.controlPlaneOidcAudience(String controlPlaneOidcAudience)

System Property:

-Dmockserver.controlPlaneOidcAudience=...

Environment Variable:

MOCKSERVER_CONTROL_PLANE_OIDC_AUDIENCE=...

Property File:

mockserver.controlPlaneOidcAudience=...

Example:

-Dmockserver.controlPlaneOidcAudience="mockserver-control-plane"

Scopes that must all be present in a control plane OIDC token before it is accepted.

Value should be a string with comma separated values, for example: mockserver.read,mockserver.write

Type: string Default: null

Java Code:

ConfigurationProperties.controlPlaneOidcRequiredScopes(Set<String> controlPlaneOidcRequiredScopes)

System Property:

-Dmockserver.controlPlaneOidcRequiredScopes=...

Environment Variable:

MOCKSERVER_CONTROL_PLANE_OIDC_REQUIRED_SCOPES=...

Property File:

mockserver.controlPlaneOidcRequiredScopes=...

Example:

-Dmockserver.controlPlaneOidcRequiredScopes="mockserver.read,mockserver.write"

Name of the claim holding granted scopes on a control plane OIDC token. Default scope is read as a space-delimited string; array claims such as scp, roles or groups are also supported.

Type: string Default: scope

Java Code:

ConfigurationProperties.controlPlaneOidcScopeClaim(String controlPlaneOidcScopeClaim)

System Property:

-Dmockserver.controlPlaneOidcScopeClaim=...

Environment Variable:

MOCKSERVER_CONTROL_PLANE_OIDC_SCOPE_CLAIM=...

Property File:

mockserver.controlPlaneOidcScopeClaim=...

Example:

-Dmockserver.controlPlaneOidcScopeClaim="scp"

Enable coarse role-based authorization of control plane requests. Once a request is authenticated, the verified principal's scopes/groups are mapped (via Control Plane Scope Mapping) to one of three hierarchical roles — read, mutate or admin (admin satisfies mutate satisfies read). Reads (retrieve/verify/diff and all GETs) require read; every other operation (creating expectations, clear, reset, etc.) requires mutate. A principal without a sufficient role is rejected with 403 Forbidden and the denial is audited with outcome FORBIDDEN.

Authorization requires a verified principal with mapped scopes, so it should be used together with control plane OIDC authentication. It is off by default; when disabled, an authenticated request is never additionally authorized.

Type: boolean Default: false

Java Code:

ConfigurationProperties.controlPlaneAuthorizationEnabled(boolean enable)

System Property:

-Dmockserver.controlPlaneAuthorizationEnabled=...

Environment Variable:

MOCKSERVER_CONTROL_PLANE_AUTHORIZATION_ENABLED=...

Property File:

mockserver.controlPlaneAuthorizationEnabled=...

Example:

-Dmockserver.controlPlaneAuthorizationEnabled="true"

Mapping from a verified scope/group value to a coarse control plane role (read, mutate or admin), used when Control Plane Authorization Enabled is true.

Value should be a comma separated list of value=role pairs, for example: platform-admins=admin,qa-team=mutate,viewers=read. Unrecognised roles and malformed pairs are ignored.

Type: string Default: null

Java Code:

ConfigurationProperties.controlPlaneScopeMapping(Map<String, ControlPlaneRole> controlPlaneScopeMapping)

System Property:

-Dmockserver.controlPlaneScopeMapping=...

Environment Variable:

MOCKSERVER_CONTROL_PLANE_SCOPE_MAPPING=...

Property File:

mockserver.controlPlaneScopeMapping=...

Example:

-Dmockserver.controlPlaneScopeMapping="platform-admins=admin,qa-team=mutate,viewers=read"
 

TLS Configuration:

The following diagram shows where TLS/mTLS configuration settings are used:

MockServer HTTPS & TLS

 

Inbound TLS (for Received Requests)

Dynamic Inbound Certificate Authority X.509 & Private Key

Enable dynamic creation of Certificate Authority X.509 Certificate and Private Key

Enable this property to increase the security of trusting the MockServer Certificate Authority X.509 by ensuring a local dynamic value is used instead of the public value in the MockServer git repo.

These PEM files will be created and saved in the directory specified with configuration property directoryToSaveDynamicSSLCertificate.

A Certificate Authority X.509 Certificate and Private Key will only be created if the files used to save them are not already present. Therefore, if MockServer is re-started multiple times with the same value for directoryToSaveDynamicSSLCertificate. the Certificate Authority X.509 Certificate and Private Key will only be created once.

Type: boolean Default: false

Java Code:

ConfigurationProperties.dynamicallyCreateCertificateAuthorityCertificate(boolean enable)

System Property:

-Dmockserver.dynamicallyCreateCertificateAuthorityCertificate=...

Environment Variable:

MOCKSERVER_DYNAMICALLY_CREATE_CERTIFICATE_AUTHORITY_CERTIFICATE=...

Property File:

mockserver.dynamicallyCreateCertificateAuthorityCertificate=...

Example:

-Dmockserver.dynamicallyCreateCertificateAuthorityCertificate="true"

Directory used to save the dynamically generated Certificate Authority X.509 Certificate and Private Key.

This directory will only be used if MockServer is configured to create a dynamic Certificate Authority X.509 certificate and private key using dynamicallyCreateCertificateAuthorityCertificate.

By default the certificate and private key are written to the current working directory (.) of the MockServer process.

Type: string Default: . (current working directory)

Java Code:

ConfigurationProperties.directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate)

System Property:

-Dmockserver.directoryToSaveDynamicSSLCertificate=...

Environment Variable:

MOCKSERVER_CERTIFICATE_DIRECTORY_TO_SAVE_DYNAMIC_SSL_CERTIFICATE=...

Property File:

mockserver.directoryToSaveDynamicSSLCertificate=...

Example:

-Dmockserver.directoryToSaveDynamicSSLCertificate="/some/existing/path"

Proactively initialise TLS during start to ensure that if dynamicallyCreateCertificateAuthorityCertificate is enabled the Certificate Authority X.509 Certificate and Private Key will be created during start up and not when the first TLS connection is received.

This setting will also ensure any configured private key and X.509 will be loaded during start up and not when the first TLS connection is received to give immediate feedback on any related TLS configuration errors.

Type: boolean Default: false

Java Code:

ConfigurationProperties.proactivelyInitialiseTLS(boolean enable)

System Property:

-Dmockserver.proactivelyInitialiseTLS=...

Environment Variable:

MOCKSERVER_PROACTIVELY_INITIALISE_TLS=...

Property File:

mockserver.proactivelyInitialiseTLS=...

Example:

-Dmockserver.proactivelyInitialiseTLS="true"

TLS Protocol Versions

Comma separated list of TLS protocol versions to enable for both inbound and outbound TLS connections.

The default value is TLSv1,TLSv1.1,TLSv1.2 which includes TLSv1 and TLSv1.1 for backward compatibility. These older protocols are deprecated and considered insecure by most security standards.

To enable TLS 1.3, add TLSv1.3 to the list. To use only modern protocols, set the value to TLSv1.2,TLSv1.3.

Note: TLS 1.3 requires Java 11 or later. MockServer's default includes TLSv1 and TLSv1.1 for backward compatibility but you should restrict protocols to TLSv1.2 and TLSv1.3 in production-like environments.

Type: string Default: TLSv1,TLSv1.1,TLSv1.2

Java Code:

ConfigurationProperties.tlsProtocols("TLSv1.2,TLSv1.3")

System Property:

-Dmockserver.tlsProtocols=...

Environment Variable:

MOCKSERVER_TLS_PROTOCOLS=...

Property File:

mockserver.tlsProtocols=...

Example (enable TLS 1.2 and 1.3 only):

-Dmockserver.tlsProtocols="TLSv1.2,TLSv1.3"

Example (Docker environment variable):

MOCKSERVER_TLS_PROTOCOLS="TLSv1.2,TLSv1.3"

Dynamic Inbound Private Key & X.509

MockServer dynamically updates the Subject Alternative Name (SAN) values for its TLS certificate to add domain names and IP addresses from request Host headers and Host headers in expectations, this configuration setting disables this automatic update and only uses SAN value provided in TLS Subject Alternative Name Domains and TLS Subject Alternative Name IPs configuration properties.

When this property is enabled the generated X.509 Certificate and Private Key pair are saved to the directoryToSaveDynamicSSLCertificate as Certificate.pem and PKCS8PrivateKey.pem

Type: boolean Default: false

Java Code:

ConfigurationProperties.preventCertificateDynamicUpdate(boolean prevent)

System Property:

-Dmockserver.preventCertificateDynamicUpdate=...

Environment Variable:

MOCKSERVER_PREVENT_CERTIFICATE_DYNAMIC_UPDATE=...

Property File:

mockserver.preventCertificateDynamicUpdate=...

Example:

-Dmockserver.preventCertificateDynamicUpdate="true"

The domain name for auto-generate TLS certificates

Type: string Default: localhost

Java Code:

ConfigurationProperties.sslCertificateDomainName(String domainName)

System Property:

-Dmockserver.sslCertificateDomainName=...

Environment Variable:

MOCKSERVER_SSL_CERTIFICATE_DOMAIN_NAME=...

Property File:

mockserver.sslCertificateDomainName=...

Example:

-Dmockserver.sslCertificateDomainName="localhost"

The Subject Alternative Name (SAN) domain names for auto-generate TLS certificates as a comma separated list

Type: string Default: localhost

Java Code:

ConfigurationProperties.addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains)
or
ConfigurationProperties.clearSslSubjectAlternativeNameDomains()

System Property:

-Dmockserver.sslSubjectAlternativeNameDomains=...

Environment Variable:

MOCKSERVER_SSL_SUBJECT_ALTERNATIVE_NAME_DOMAINS=...

Property File:

mockserver.sslSubjectAlternativeNameDomains=...

Example:

-Dmockserver.sslSubjectAlternativeNameDomains="localhost,www.foo.bar"

The Subject Alternative Name (SAN) IP addresses for auto-generate TLS certificates as a comma separated list

Type: string Default: 127.0.0.1,0.0.0.0

Java Code:

ConfigurationProperties.addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps)
or
ConfigurationProperties.clearSslSubjectAlternativeNameIps()

System Property:

-Dmockserver.sslSubjectAlternativeNameIps=...

Environment Variable:

MOCKSERVER_SSL_SUBJECT_ALTERNATIVE_NAME_IPS=...

Property File:

mockserver.sslSubjectAlternativeNameIps=...

Example:

-Dmockserver.sslSubjectAlternativeNameIps="127.0.0.1,0.0.0.0"

Fixed (i.e. Custom) Inbound Certificate Authority X.509 & Private Key

Location of custom file for Certificate Authority for TLS, the private key must be a PKCS#8 or PKCS#1 PEM file and must match the TLS Certificate Authority X.509 Certificate.

To convert a PKCS#1 PEM file (i.e. default for Bouncy Castle) to a PKCS#8 PEM file the following command can be used: openssl pkcs8 -topk8 -inform PEM -in private_key_PKCS_1.pem -out private_key_PKCS_8.pem -nocrypt

Type: string Default: the built-in MockServer CA private key (org/mockserver/socket/PKCS8CertificateAuthorityPrivateKey.pem on the classpath)

Java Code:

ConfigurationProperties.certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey)

System Property:

-Dmockserver.certificateAuthorityPrivateKey=...

Environment Variable:

MOCKSERVER_CERTIFICATE_AUTHORITY_PRIVATE_KEY=...

Property File:

mockserver.certificateAuthorityPrivateKey=...

Example:

-Dmockserver.certificateAuthorityPrivateKey="/some/existing/path"

Location of custom file for Certificate Authority for TLS, the certificate must be a X.509 PEM file and must match the TLS Certificate Authority Private Key.

Type: string Default: the built-in MockServer CA certificate (org/mockserver/socket/CertificateAuthorityCertificate.pem on the classpath)

Java Code:

ConfigurationProperties.certificateAuthorityCertificate(String certificateAuthorityCertificate)

System Property:

-Dmockserver.certificateAuthorityCertificate=...

Environment Variable:

MOCKSERVER_CERTIFICATE_AUTHORITY_X509_CERTIFICATE=...

Property File:

mockserver.certificateAuthorityCertificate=...

Example:

-Dmockserver.certificateAuthorityCertificate="/some/existing/path"

Fixed (i.e. Custom) Inbound Private Key & X.509

File system path or classpath location of a fixed custom private key for TLS connections into MockServer.

The private key must be a PKCS#8 or PKCS#1 PEM file and must be the private key corresponding to the x509CertificatePath X.509 (public key) configuration.

The certificateAuthorityCertificate configuration must be the Certificate Authority for the corresponding X.509 certificate (i.e. able to valid its signature), see: x509CertificatePath.

To convert a PKCS#1 (i.e. default for Bouncy Castle) to a PKCS#8 the following command can be used: openssl pkcs8 -topk8 -inform PEM -in private_key_PKCS_1.pem -out private_key_PKCS_8.pem -nocrypt

This configuration will be ignored unless x509CertificatePath is also set.

Type: string Default: null

Java Code:

ConfigurationProperties.privateKeyPath(String privateKeyPath)

System Property:

-Dmockserver.privateKeyPath=...

Environment Variable:

MOCKSERVER_TLS_PRIVATE_KEY_PATH=...

Property File:

mockserver.privateKeyPath=...

Example:

-Dmockserver.privateKeyPath="/some/existing/path"

File system path or classpath location of a fixed custom X.509 Certificate for TLS connections into MockServer

The certificate must be a X.509 PEM file and must be the public key corresponding to the privateKeyPath private key configuration.

The certificateAuthorityCertificate configuration must be the Certificate Authority for this certificate (i.e. able to valid its signature).

This configuration will be ignored unless privateKeyPath is also set.

Type: string Default: null

Java Code:

ConfigurationProperties.x509CertificatePath(String x509CertificatePath)

System Property:

-Dmockserver.x509CertificatePath=...

Environment Variable:

MOCKSERVER_TLS_X509_CERTIFICATE_PATH=...

Property File:

mockserver.x509CertificatePath=...

Example:

-Dmockserver.x509CertificatePath="/some/existing/path"

Inbound mTLS Client Authentication (for Received Requests)

Require mTLS (also called client authentication and two-way TLS) for all TLS connections / HTTPS requests to MockServer

Type: boolean Default: false

Java Code:

ConfigurationProperties.tlsMutualAuthenticationRequired(boolean enable)

System Property:

-Dmockserver.tlsMutualAuthenticationRequired=...

Environment Variable:

MOCKSERVER_TLS_MUTUAL_AUTHENTICATION_REQUIRED=...

Property File:

mockserver.tlsMutualAuthenticationRequired=...

Example:

-Dmockserver.tlsMutualAuthenticationRequired="true"

File system path or classpath location of custom mTLS (TLS client authentication) X.509 Certificate Chain for Trusting (i.e. signature verification of) Client X.509 Certificates, the certificate chain must be a X.509 PEM file.

This certificate chain will be used if MockServer performs mTLS (client authentication) for inbound TLS connections because tlsMutualAuthenticationRequired is enabled

This configuration property is also used for MockServerClient to trust outbound TLS X.509 certificates i.e. TLS connections to MockServer

Type: string Default: null

Java Code:

ConfigurationProperties.tlsMutualAuthenticationCertificateChain(String certificateChain)

System Property:

-Dmockserver.tlsMutualAuthenticationCertificateChain=...

Environment Variable:

MOCKSERVER_TLS_MUTUAL_AUTHENTICATION_CERTIFICATE_CHAIN=...

Property File:

mockserver.tlsMutualAuthenticationCertificateChain=...

Example:

-Dmockserver.tlsMutualAuthenticationCertificateChain="/some/existing/path"


 

Outbound Client TLS/mTLS (for Forwarded or Proxied Requests)

Configure trusted set of certificates for forwarded or proxied requests (i.e. TLS connections out of MockServer).

MockServer will only be able to establish a TLS connection to endpoints that have a trusted X.509 certificate according to the trust manager type, as follows:

  • ANY - Insecure will trust all X.509 certificates and not perform host name verification.
  • JVM - Will trust all X.509 certificates trust by the JVM.
  • CUSTOM - Will trust all X.509 certificates specified in forwardProxyTLSCustomTrustX509Certificates configuration value.

Type: string Default: ANY

Java Code:

ConfigurationProperties.forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType)

System Property:

-Dmockserver.forwardProxyTLSX509CertificatesTrustManagerType=...

Environment Variable:

MOCKSERVER_FORWARD_PROXY_TLS_X509_CERTIFICATES_TRUST_MANAGER_TYPE=...

Property File:

mockserver.forwardProxyTLSX509CertificatesTrustManagerType=...

Example:

-Dmockserver.forwardProxyTLSX509CertificatesTrustManagerType="CUSTOM"

Fixed (i.e. Custom) Outbound CA X.509, Private Key & X.509

File system path or classpath location of custom file for trusted X.509 Certificate Authority roots for forwarded or proxied requests (i.e. TLS connections out of MockServer), the certificate chain must be a X.509 PEM file.

MockServer will only be able to establish a TLS connection to endpoints that have an X.509 certificate chain that is signed by one of the provided custom certificates, i.e. where a path can be established from the endpoints X.509 certificate to one or more of the custom X.509 certificates provided.

This configuration only take effect if forwardProxyTLSX509CertificatesTrustManagerType is configured as CUSTOM otherwise this value is ignored.

Type: string Default: null

Java Code:

ConfigurationProperties.forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates)

System Property:

-Dmockserver.forwardProxyTLSCustomTrustX509Certificates=...

Environment Variable:

MOCKSERVER_FORWARD_PROXY_TLS_CUSTOM_TRUST_X509_CERTIFICATES=...

Property File:

mockserver.forwardProxyTLSCustomTrustX509Certificates=...

Example:

-Dmockserver.forwardProxyTLSCustomTrustX509Certificates="/some/existing/path"

File system path or classpath location of custom Private Key for forwarded or proxied requests (i.e. TLS connections out of MockServer), the private key must be a PKCS#8 or PKCS#1 PEM file

To convert a PKCS#1 (i.e. default for Bouncy Castle) to a PKCS#8 the following command can be used: openssl pkcs8 -topk8 -inform PEM -in private_key_PKCS_1.pem -out private_key_PKCS_8.pem -nocrypt

This private key will be used if MockServer needs to perform mTLS (client authentication) for outbound TLS connections.

Type: string Default: null

Java Code:

ConfigurationProperties.forwardProxyPrivateKey(String privateKey)

System Property:

-Dmockserver.forwardProxyPrivateKey=...

Environment Variable:

MOCKSERVER_FORWARD_PROXY_TLS_PRIVATE_KEY=...

Property File:

mockserver.forwardProxyPrivateKey=...

Example:

-Dmockserver.forwardProxyPrivateKey="/some/existing/path"

File system path or classpath location of custom X.509 Certificate Chain for forwarded or proxied requests (i.e. TLS connections out of MockServer), the certificates must be a X.509 PEM file

This certificate chain will be used if MockServer needs to perform mTLS (client authentication) for outbound TLS connections.

Type: string Default: null

Java Code:

ConfigurationProperties.forwardProxyCertificateChain(String certificateChain)

System Property:

-Dmockserver.forwardProxyCertificateChain=...

Environment Variable:

MOCKSERVER_FORWARD_PROXY_TLS_X509_CERTIFICATE_CHAIN=...

Property File:

mockserver.forwardProxyCertificateChain=...

Example:

-Dmockserver.forwardProxyCertificateChain="/some/existing/path"

Present a different client certificate and key for outbound mTLS depending on which upstream host MockServer is connecting to. By default the fixed outbound client key/certificate above are used for every upstream; this property lets you override them per host.

The value is a comma-separated list of host=certificateChainPath;privateKeyPath entries. When MockServer opens a TLS connection to a matching upstream host (matched case-insensitively), it presents that host's certificate/key pair; any host that is not listed falls back to the fixed outbound client key/certificate (or, if those are not set, MockServer's own generated certificate). Each certificate chain is an X.509 PEM file and each private key a PKCS#8 or PKCS#1 PEM file.

Type: string Default: null

Java Code:

ConfigurationProperties.forwardProxyClientCertificatesByHost(String clientCertificatesByHost)

System Property:

-Dmockserver.forwardProxyClientCertificatesByHost=...

Environment Variable:

MOCKSERVER_FORWARD_PROXY_CLIENT_CERTIFICATES_BY_HOST=...

Property File:

mockserver.forwardProxyClientCertificatesByHost=...

Example:

-Dmockserver.forwardProxyClientCertificatesByHost="api.internal=/certs/api-chain.pem;/certs/api-key.pem,billing.internal=/certs/billing-chain.pem;/certs/billing-key.pem"
 

MockServer Client

File system path or classpath location of custom mTLS (TLS client authentication) X.509 Certificate Chain for Trusting (i.e. signature verification of) MockServer X.509 Certificates, the certificate chain must be a X.509 PEM file. This certificate chain will only be used if MockServerClient performs TLS to calls to MockServer.

This settings is particularly used when connecting to MockServer via a load-balancer or other TLS terminating network infrastructure with its own X.509 Certificate.

This configuration property is also used for MockServer to trust inbound mTLS client authentication X.509 certificates

Type: string Default: null

Java Code:

ConfigurationProperties.tlsMutualAuthenticationCertificateChain(String certificateChain)

System Property:

-Dmockserver.tlsMutualAuthenticationCertificateChain=...

Environment Variable:

MOCKSERVER_TLS_MUTUAL_AUTHENTICATION_CERTIFICATE_CHAIN=...

Property File:

mockserver.tlsMutualAuthenticationCertificateChain=...

Example:

-Dmockserver.tlsMutualAuthenticationCertificateChain="/some/existing/path"