Chapter 27. Single-Process Pub/Sub

The example in the previous chapter was admittedly quite simple. Let’s build on that foundation (pun intended) to do something a bit more interesting. Suppose we have a workflow on our site like the following:

  1. Enter some information on page X, and submit.

  2. Submission starts a background job, and the user is redirected to a page to view the status of that job.

  3. That second page will subscribe to updates from the background job and display them to the user.

The core principle here is the ability to let one thread publish updates, and have another thread subscribe to receive those updates. This is known generally as pub/sub, and fortunately is very easy to achieve in Haskell via STM (the Software Transactional Memory library).

Like in the previous chapter, let me start off with the following caveat: this technique only works properly if you have a single web application process. If you have two different servers and a load balancer, you’ll either need sticky sessions or some other solution to make sure that the requests from a single user are going to the same machine. In those situations, you may want to consider using an external pub/sub solution, such as Redis.

With that caveat out of the way, let’s get started.

Foundation Data Type

We’ll need two different mutable references in our foundation. The first will keep track of the next “job ID” we’ll hand out. Each of these background jobs will be represented by a unique identifier that will ...

Get Developing Web Apps with Haskell and Yesod, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.