Throttling in Akka and Spray

When you want to limit the amount of messages an actor gets, you can use the throttler in akka-contrib. This will let you limit the max transactions per second(tps). It will queue up the surplus.

Here I’ll describe another way. I’ll reject all the surplus messages. This has the advantage that the requester knows it’s sending too much and can act on that.

Both methods have their advantages. And both have limits, since they still require resources to queue or reject the messages.

In Akka we can create an Actor that sends messages through to the target actor, or rejects them when it exceeds the specified tps.

This will return an Accepted or ExceededMaxTps message to the sender.

In Spray we can make a directive that returns with http code 400 when you exceed the maximum.

This can then easily be used in our route.

And to see it in action, I quickly ran curl two times.

The whole code can be found here.



Building a REST client with Spray

In a previous blog I wrote how to make an API. See here.

Now we’ll make a client to use that API. This can be done with spray-client.

First we add dependencies for spray-client and spray-json:

This is what the main class looks like:

You can get the whole code from github.

Alternating between Spray-servlet and Spray-can

On a server you may want to deploy your application as a war. How to build a war with spray-servlet
Locally it’s easiest to run without an application server.

We include both the spray-servlet and spray-can dependencies:

We make a trait with all the common functionality. We extend both SprayApiServlet and SprayApiCan from it.

You can see the whole example here.

Building a war with spray-servlet

We will use spray-servlet to build a war file of our API. So we can run it in a java app server.
I assume we already have a working REST API.

We will need a web.xml, under src/main/webapp/WEB-INF/:

We need an sbt plugin to build wars. Add this to project/plugins.sbt:

We’ll add dependencies to build.sbt, and also extra tasks:

We’ll need to extend spray.servlet.WebBoot:

And add a reference to this class in application.conf:

on is a good example application

Now we can run sbt package to build a war.
And in sbt, use container:start to start a tomcat server with our application. And container:stop to stop it.

A good way to restart the server every time we change code is: