Response size compression in Lagom: GZip Encoding

This is a small blog post, in which we will go through the steps to add response compression in our Java-based Lagom service. If you are not familiar with the concepts of Lagom, read through this blog to gain a brief idea of what Lagom is all about. Then, come back here and we will add quickly add compression to the service you’d have implemented.

Below are the two simple steps to add service response compression to your Lagom service.

Step 1: The Code

The first step is to write the code for our compression filter. We design a custom Filter that implements the HttpFilters interface provided by play framework as illustrated below. Let’s say we want to add GZip compression to our response before sending it to the consumer. The below snippet can be used as is in any Lagom service.

package com.example.filter;

import javax.inject.Inject;
import play.filters.gzip.GzipFilter;
import play.filters.gzip.GzipFilterConfig;
import play.http.HttpFilters;
import play.mvc.EssentialFilter;

public class GZipFilter implements HttpFilters {

    private EssentialFilter[] filters;

    public GZipFilter(Materializer materializer) {
        GzipFilterConfig gzipFilterConfig = new GzipFilterConfig();
        gzipFilterConfig = gzipFilterConfig.withShouldGzip((req, res) -> req.hasHeader("Accept-Encoding")
                ? req.getHeader("Accept-Encoding").toLowerCase().contains("gzip") : false);

        GzipFilter gzipFilter = new GzipFilter(gzipFilterConfig, materializer);
        filters = new EssentialFilter[]{gzipFilter.asJava()};

    public EssentialFilter[] filters() {
        return filters;

Step 2: The configuration

In your application.conf, add the below parameters:

#Fully qualified class name of our customized HttpFilter
play.http.filters = "com.example.GZipFilter"
#Maximum expected size of compressed response

And you’re done!

This is the simplest way to add compression to your service response with minimal configuration. To study in further detail, feel free to explore the documentation of Play GZipEncoding. If you have any questions, queries or suggestions for me, please drop a comment below and I’ll be happy to answer. And if you found this useful, do like & share this blog, we are all here to learn! Cheers. 🙂


  1. Configuring GZip encoding
  2. Cross-Origin Resource Sharing


This entry was posted in Java, Microservices, Play 2.4.X, Play Framework. Bookmark the permalink.

One Response to Response size compression in Lagom: GZip Encoding

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s