Elastic Beanstalk
offers both a Web
tier and a Worker
tier. This allows developers to build reasonably complex applications without having to maintain moving pieces. Offloading heavy-duty workloads to the worker in order to keep the web tier responsive is as easy as putting a message on a queue.
One annoyance that I have with Beanstalk
is that there is no way to direct a message to a specific endpoint, hence leaving a single endpoint the responsibility of distributing the messages to all their handlers and potentially leading to brittle code. But it doesn’t have to be that way.
Implementation
SQS
messages have attributes, attributes can be set by the sender and are read by the receiver. The idea is to use a known attribute to attach routing metadata to the message.
Constants
Constants are the base of any decently built C#
application. I did not want to depart from to this rule and hence added some constants:
These constansts will be used to add routing metadata to the SQS
message.
We can then define our routes via some more constants:
Note: those two class
will have to be referenced by the sender and the Worker
.
Sending the message
The sender will most likely be the Web
tier but it could be any system being able to send a message to a SQS
queue.
Middleware
In the Worker
, the routing is implemented via a Middleware
:
Note: don’t forget to add HeaderRoutingMiddleware
to the IApplicationBuilder
.
Controller
The last piece of the puzzle is defining the expected route on the Controller
:
Simple routing
I used Simple Routing
in production over the last few months and am now confident that it does what it’s supposed to do. This is why I decided to release it under a MIT
license to allow others to benefit from my work.
Simple Routing
is available:
- On
NuGet
as the package BeanstalkWorker.SimpleRouting - A
GitHub
release - As source on
Github
- The implementation is so simple that you can just copy the classes into your own solution if that works better for you
Demo
The Simple Routing
solution contains a SampleWeb
app, you can either:
- Send “work” -
Send/Work
- Send “nothing” -
Send/Nothing
Send messages
Peek at the messages
Now let’s look at the messages in the SQS
queue:
- The
Work
message
- The
Nothing
message
Handle the messages
Launch the SampleWorker
app. When running in ElasticBeanstalk
the Sqsd daemon reads SQS
messages from the SQS
queue and POST
the content to your Worker
. But we’re running the Worker
on our machine and the Sqsd daemon
is not available. This is why I wrote Beanstalk Seeder
.
Beanstalk Seeder emulates the
SQS Daemon
surrounding anElastic Beanstalk
Worker Tier
so that you can replicate the interaction between aWeb Tier
and aWorker Tier
on your machine.
Handling the Work
message
Beanstalk Seeder
Worker
Handling the Nothing
message
Beanstalk Seeder
Worker
I wrote a detailed guide in the GitHub repository. Give it a try and let me know if it works for you.