Response size compression in Lagom: GZip Encoding

Knoldus Inc.
Knoldus - Technical Insights
2 min readApr 2, 2018

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.

[code language=”java”]
package com.example.filter;

import javax.inject.Inject;
import akka.stream.Materializer;
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;

@Inject
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()};
}

@Override
public EssentialFilter[] filters() {
return filters;
}
}
[/code]

Step 2: The configuration

In your application.conf, add the below parameters:

[code]#Fully qualified class name of our customized HttpFilter
play.http.filters = “com.example.GZipFilter”
#Maximum expected size of compressed response
play.filters.gzip.chunkedThreshold=300K[/code]

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

References:

  1. Configuring GZip encoding
  2. Cross-Origin Resource Sharing
knoldus-advt-sticker

--

--

Knoldus Inc.
Knoldus - Technical Insights

Group of smart Engineers with a Product mindset who partner with your business to drive competitive advantage | www.knoldus.com