Defer Transaction Side-Effects in Node.js

engineering grouparoo node.js typescript 
2021-01-21 - Originally posted at https://www.grouparoo.com/blog/defering-side-effects-in-node
↞ See all posts


A glowing laptop

At Grouparoo, we use Actionhero as our Node.js API server and Sequelize for our Object Relational Mapping (ORM) tool - making it easy to work with complex records from our database. Within our Actions and Tasks, we often want to treat the whole execution as a single database transaction - either all the modifications to the database will succeed or fail as a unit. This is really helpful when a single activity may create or modify many database rows.

Why do we need Transactions?

Take the following example from a prototypical blogging site. When a user is created (POST /api/v1/user), we also create their first post and send them a welcome email. All examples in this post are written in Typescript, but the concepts work the same for Javascript.

1import { action } from "actionhero"; 2import { User, Post } from "../models"; 3 4export class UserCreate extends Action { 5 constructor() { 6 super(); 7 this.name = "user:create"; 8 this.description = "create a user and their first post"; 9 this.inputs = { 10 firstName: { required: true }, 11 lastName: { required: true }, 12 password: { required: true }, 13 email: { required: true }, 14 }; 15 } 16 17 async run({ params }) { 18 const user = await User.create(params); 19 await user.updatePassword(params.password); 20 await user.sendWelcomeEmail(); 21 22 const post = await Post.create({ 23 userId: user.id, 24 title: "My First Post", 25 published: false, 26 }); 27 28 return { userId: user.id, postId: post.id }; 29 } 30}

In this example, we:

  1. Create the user record
  2. Update the user’s password
  3. Send the welcome email
  4. Create the first post for the new user
  5. Return the IDs of the new records created

This works as long as nothing fails mid-action. What if we couldn’t update the user’s password? The new user record would still be in our database, and we would need a try/catch to clean up the data. If not, when the user tries to sign up again, they would have trouble as there would already be a record in the database for their email address.

To solve this cleanup problem, you could use transactions. Using Sequelize’s Managed Transactions, the run method of the Action could be:

1async run({ params }) { 2 return sequelize.transaction(async (t) => { 3 const user = await User.create(params, {transaction: t}); 4 await user.updatePassword(params.password, {transaction: t} ); 5 await user.sendWelcomeEmail(); 6 7 const post = await Post.create({ 8 userId: user.id, 9 title: 'My First Post', 10 published: false, 11 }, {transaction: t}) 12 13 return { userId: user.id, postId: post.id }; 14 }) 15}

Managed Transactions in Sequelize are very helpful - you don’t need to worry about rolling back the transaction if something goes wrong! If there’s an error throw-n, it will rollback the whole transaction automatically.

While this is safer than the first attempt, there are still some problems:

  1. We have to remember to pass the transaction object to every Sequelize call
  2. We need to ensure that every method we call which could read or write to the database needs to use the transaction as well, and take it as an argument (like user.updatePassword()... that probably needs to write to the database, right?)
  3. Sending the welcome email is not transaction safe.

Sending the email as-written will happen even if we roll back the transaction because of an error when creating the new post… which isn’t great if the user record wasn’t committed! So what do we do?

Automatically Pass Transactions to all Queries: CLS-Hooked

The solution to our problem comes from a wonderful package called cls-hooked. Using the magic of AsyncHooks, this package can tell when certain code is within a callback chain or promise. In this way, you can say: "for all methods invoked within this async function, I want to keep this variable in scope". This is pretty wild! If you opt into using Sequelize with CLS-Hooked, every SQL statement will check to see if there is already a transaction in scope... You don't need to manually supply it as an argument!

From the cls-hooked readme:

CLS: "Continuation-Local Storage"

Continuation-local storage works like thread-local storage in threaded programming, but is based on chains of Node-style callbacks instead of threads.

There is a performance penalty for using cls-hooked, but in our testing, it isn’t meaningful when compared to await-ing SQL results from a remote database.

Using cls-hooked, our Action's run method now can look like this:

1// Elsewhere in the Project 2 3const cls = require('cls-hooked'); 4const namespace = cls.createNamespace('actionhero') 5const Sequelize = require('sequelize'); 6Sequelize.useCLS(namespace); 7new Sequelize(....); 8 9// Our Run Method 10 11async run({ params }) { 12 return sequelize.transaction(async (t) => { 13 const user = await User.create(params); 14 await user.updatePassword(params.password); 15 await user.sendWelcomeEmail(); 16 17 const post = await Post.create({ 18 userId: user.id, 19 title: 'My First Post', 20 published: false, 21 }) 22 23 return { userId: user.id, postId: post.id }; 24 }) 25}

Ok! We have removed the need to pass transaction to all queries and sub-methods! All that remains now is the user.sendWelcomeEmail() side-effect. How can we delay this method until the end of the transaction?

CLS and Deferred Execution

Looking deeper into how cls-hooked works, we can see that it is possible to tell if you are currently in a namespace, and to set and get values from the namespace. Think of this like a session... but for the callback or promise your code is within! With this in mind, we can write our run method to be transaction-aware. This means that we can use a pattern that knows to run a function in-line if we aren’t within a transaction, but if we are, defer it until the end. We’ve wrapped utilities to do this within Grouparoo’s CLS module.

With the CLS module you can write code like this:

1// from the Grouparoo Test Suite: Within Transaction 2 3test("in a transaction, deferred jobs will be run afterwords", async () => { 4 const results = []; 5 const runner = async () => { 6 await CLS.afterCommit(() => results.push("side-effect-1")); 7 await CLS.afterCommit(() => results.push("side-effect-2")); 8 results.push("in-line"); 9 }; 10 11 await CLS.wrap(() => runner()); 12 expect(results).toEqual(["in-line", "side-effect-1", "side-effect-2"]); 13});

You can see here that once you CLS.wrap() an async function, you can defer the execution of anything wrapped with CLS.afterCommit() until the transaction is complete. The order of the afterCommit side-effects is deterministic, and in-line happens first.

You can also take the same code and choose not apply CLS.wrap() to it to see that it still works, but the order of the side-effects has changed:

1// from the Grouparoo Test Suite: Without Transaction 2 3test("without a transaction, deferred jobs will be run in-line", async () => { 4 const results = []; 5 const runner = async () => { 6 await CLS.afterCommit(() => results.push("side-effect-1")); 7 await CLS.afterCommit(() => results.push("side-effect-2")); 8 results.push("in-line"); 9 }; 10 11 await runner(); 12 expect(results).toEqual(["side-effect-1", "side-effect-2", "in-line"]); 13});

CLSAction and CLSTask

Now that it is possible to take arbitrary functions and delay their execution until the transaction is complete, we can use these techniques to make a new type of Action and Task that has this functionality built in. We call these CLSAction and CLSTask. These new classes extend the regular Actionhero Action and Task classes, but provide a new runWithinTransaction method to replace run, which helpfully already uses CLS.wrap(). This makes it very easy for us to opt-into an Action in which automatically runs within a Sequelize transaction, and can defer it's own side-effects!

Putting everything together, our new transaction-safe Action looks like this:

1// *** Define the CLSAction Class *** 2 3import { Action } from "actionhero"; 4import { CLS } from "../modules/cls"; 5 6export abstract class CLSAction extends Action { 7 constructor() { 8 super(); 9 } 10 11 async run(data) { 12 return CLS.wrap(async () => await this.runWithinTransaction(data)); 13 } 14 15 abstract runWithinTransaction(data): Promise<any>; 16}
1// *** Use the CLSAction Class *** 2 3import { CLSAction } from "../classes"; 4import { User, Post } from "../models"; 5 6export class UserCreate extends CLSAction { 7 constructor() { 8 super(); 9 this.name = "user:create"; 10 this.description = "create a user and their first post"; 11 this.inputs = { 12 firstName: { required: true }, 13 lastName: { required: true }, 14 password: { required: true }, 15 email: { required: true }, 16 }; 17 } 18 19 async runWithinTransaction({ params }) { 20 const user = await User.create(params); 21 await user.updatePassword(params.password); 22 await CLS.afterCommit(user.sendWelcomeEmail); 23 24 const post = await Post.create({ 25 userId: user.id, 26 title: "My First Post", 27 published: false, 28 }); 29 30 return { userId: user.id, postId: post.id }; 31 } 32}

If the transaction fails, the email won’t be sent, and all the models will rolled back. There won't be any mess to clean up 🧹!

Summary

The cls-hooked module is a very powerful tool. If applied globally, it unlocks the ability to produce side-effects throughout your application worry-free. Perhaps your models need to enqueue a Task every time they are created... now you can if you cls.wrap() it! You can be sure that task won’t be enqueued unless the model was really saved and committed. This unlocks powerful tools that you can use with confidence.

Hi, I'm Evan

I write about Technology, Software, and Startups. I use my Product Management, Software Engineering, and Leadership skills to build teams that create world-class digital products.

Get in touch