Gzip compression is a technique used to reduce the size of HTTP responses by compressing them before sending them over the network. Learn to enable HTTP response gzip compression in a Spring Boot application.
By default, the Gzip compression is disabled in Spring Boot.
1. Enable and Configure Gzip Compression in Spring Boot
The following response compression-related Spring Boot properties are applicable to Jetty, Tomcat, and Undertow. Define these properties in the application.properties file.
A similar configuration can be written in YAML as follows:
excluded-user-agents: MSIE 6.0,UCBrowser
- server.compression.enabled enables or disables the compression.
- server.compression.min-response-size – configures the minimum number of bytes in response for compression to be performed. The default size is
- server.compression.mime-types – enables compression only if their content type is one of the given mime-types.
- server.compression.excluded-user-agents – specifies a comma-separated list of user-agent patterns for which Gzip compression should be excluded.
2. Wildcards in Mime-types are not Supported
The compression in Spring Boot relies on support provided by underlying embedded servers. Unfortunately, these servers do not provide any consistent wildcard support in mime-type.
Jetty performs strict string comparisons when determining whether to compress a response based on MIME type. Wildcards such as
* are not supported directly for matching multiple MIME types. [Link]
However, Jetty provides an alternative mechanism for configuring a whitelist or blacklist of MIME types explicitly. This allows you to specify which MIME types should or should not be compressed.
For example, you might configure a whitelist to explicitly list the MIME types that should be compressed:
While Tatomc doesn’t support wildcards in the traditional sense, you can configure MIME types in a way that covers a range of similar types. [Link]
So configuring ‘application/vnd.company‘ would work for both ‘application/vnd.company.v3+json‘ and ‘application/vnd.company.v2+xml‘.
3. Testing the Gzip Compression
Once the compression is enabled and configured, the Spring Boot application will automatically compress responses that match the configured MIME types and are larger than the specified minimum response size.
We can use tools like cURL, Postman, or browser developer tools to inspect the HTTP headers of the responses to confirm that Gzip compression is applied.
curl -X GET http://localhost:8080/api/some-endpoint -H "Accept: application/json" -I
Look for the
Content-Encoding: gzip header in the response, indicating that Gzip compression was applied.
Enabling Gzip compression is a simple and effective way to optimize the performance of your Spring Boot REST API, especially when dealing with large JSON responses or other text-based content.
Drop me your questions related to Gzip compression in Spring Boot.
Happy Learning !!