Sometime our response from our API can be huge in the sense that it delay loading time along with it degrades user experience.So, GZIP compression comes to the rescue. We want to compress the response data bytes and GZIP compression does that by 90%.
If you had 10 MB data size then GZIP compresses data size to 1-2MB. All of this is easy with Spring Boot.
GZIP is a file format use to compress HTTP content before it is served to a client. There are different advantage of using GZIP.
- Improved Page loading time
- Decreased Bandwidth consumption
- Great User experience
Enable GZIP Compression in Spring Boot
Spring Boot is amazing as most of the thing comes out of the box. We just need to write a couple of lines and it is configured. Let’s take an example by creating a project from Spring Initialzr. I am using the project from Many-To-Many Spring JPA. You are free to make your own. It will simply be a demonstration of Gzip compression.
After you’ve launched the application, right-click and select inspect from the drop-down menu in the browser tab. Now use your browser to call your GET endpoint, go to the Network tab, and look for something like this in the Response header.
There is no GZIP content encoding in the response and it is because Spring Boot disables the GZIP compression by default. Now let’s add couple of lines in application.properties file.
# Enable response compression
# Different mime types that should be compressed
Now run the application again, check the response headers. It should look something like this.
You can see now content-encoding is set to gzip which means gzip compression is enabled and your response is compressed.
You might be thinking, well i do not want to compress all my response which is of smaller size. Spring Boot makes it easy by defining the size of minimum response after which you want to enable the gzip compression for response.
# Minimum response size for response to be compressed
Explanation for GZIP commands
server.compression.enabled property enables or disables the compression. By default it is disabled.
server.compression.mime-types: Configures mime types that we want to compress. It supports many different formats and can be configured on multiple formats.
server.compression.min-response-size: Setting minimum response size for compression to start. This is the minimum size of response before GZIP starts compressing. Any response size below this value will be served to the client as it is.
We learned how to enable GZIP compression in a Spring Boot application in this post. Spring Boot makes compression simple by giving capabilities right out of the box. Please let me know if you enjoyed the post by leaving a comment.