When we write software, we always want to make it as flawless as possible. While we always strive for it hard enough, sometimes bugs still can appear in a production system. So this is why, when we write software, we have to prepare for the worst when things go wrong.
When software goes wrong, it will halt the code execution and returns an error message immediately. That is easy to implement, but what happens if it comes to a halt while it's in the middle of writing something in the database?
Let's say you’re creating a website with a payment system. Imagine user A wants to deposit some amount of his balance to user B. The server first decreases user A’s balance, but before the server can increase user B’s balance it crashes. This would be a disaster, how much of the users' balance would be gone missing, simply because of technical problems? This is why we have to learn to use Database Transactions.
A database transaction is a concept to merge several database queries such that we want to treat them as “a whole”. A transaction will either execute completely (committed) or not at all (rolled back). When a transaction has started, all execution will happen in the memory and not yet be written until it is fully committed. If we had used a database transaction in our problem above, the changes would only have happened in memory and not be committed, which makes users’ deposits untouched.
Most database libraries provide a way to use database transactions. That’s including Knex, which is used by Strapi through Bookshelf. Strapi is a headless content management system (CMS) built with React.js and Node.js. It is easy to learn. It supports PostgreSQL, SQLite, MySQL, and MariaDB. If you start to write code to implement custom routes in Strapi, this tutorial is for you. We’ll learn how to write queries for custom routes in Strapi with Database Transaction.
Before you can jump into this content, you need to have a basic understanding of the following.
Strapi uses Bookshelf.js library to send database queries in an ORM fashion. Bookshelf itself is powered by Knex.js, which is a SQL query builder. Knex.js supports popular SQL-based database engines like PostgreSQL, SQLite, MySQL, and MariaDB, which are also supported by Strapi. Knex.js also supports database transactions, which then makes Bookshelf also provides support for it. With a basic understanding of both libraries, we can add Database transaction support to Strapi queries.
Referencing from the Backend customization API documentation, we recall these query methods:
1 // find
2 strapi.query(entity).find(params, populate);
3 // findOne
4 strapi.query(entity).findOne(params, populate);
5 // create
6 strapi.query(entity).create(attributes);
7 // update
8 strapi.query(entity).update(params, attributes);
9 // delete
10 strapi.query(entity).delete(params);
Because database transactions are an undocumented feature within Strapi, we need to look at the query function declarations in the source code. Digging deeper in the source code, we'll learn that we can pass the [transacting](https://github.com/strapi/strapi/blob/v3.6.8/packages/strapi-connector-bookshelf/lib/queries.js#L67-L177)
parameter of Bookshelf as an extra parameter to the query functions so we can run the query inside a transaction. I summarize these query declarations here:
1 // find
2 strapi.query(entity).find(params, populate, { transacting })
3 // findOne
4 strapi.query(entity).findOne(params, populate, { transacting });
5 // create
6 strapi.query(entity).create(attributes, { transacting });
7 // update
8 strapi.query(entity).update(params, attributes, { transacting });
9 // delete
10 strapi.query(entity).delete(params, { transacting });
So now know that we can use { transacting }
as an extra parameter. But how do we use it? If we look at the Bookshelf documentation source, we can set this parameter with the callback parameter of Bookshelf.transactio``n()
which is just an alias to a Knex.js Transaction. And then on the Backend customization page, we know that we can get the Knex.js instance within Strapi with:
1 const knex = strapi.connections.default;
With a bit of reading from Knex.js Transaction documentation, we can start writing our query with transactions. The transaction callback will be something like this:
1 await strapi.connections.default.transaction(async(transacting) => {
2 // our queries with { transacting } set here...
3 });
Now lets we create a quick example project to demonstrate our problem before using database transactions in Strapi. Start by running this command in your favorite terminal:
1 npx create-strapi-app@3 strapi-api --quickstart
This will create a new Strapi project in the folder strapi-api
. Before we can start writing we should create some collections for demonstration. Run our project by running this command:
1 npm run develop
Open the admin dashboard, enter the new login credentials (only for the first time), go to Content-Types Builder, click on Create new collection type and create a new Receipt
collection type for recording transactions with attributes below.
You also need to add balance
to the existing User collection. We use this attribute to track users' balance.
Now, let's create a new controller to handle balance transfers. Open the Receipt controller and write this code. I have added comments for explanation.
.api/receipt/controllers/receipt.js
1 'use strict';
2 const { sanitizeEntity } = require('strapi-utils');
3
4 module.exports = {
5 async transferBalance(ctx) {
6 // Read from POST body
7 const { amount, from, to } = ctx.request.body;
8
9 return await strapi.connections.default.transaction(async (transacting) => {
10 // Find the user
11 const fromUser = await strapi.query('user', 'users-permissions').findOne({ id: from }, null, { transacting });
12 const toUser = await strapi.query('user', 'users-permissions').findOne({ id: to }, null, { transacting });
13
14 // Check if the user exists
15 if (!fromUser || !toUser) {
16 return ctx.badRequest(null, 'User not found');
17 }
18 // Check if the user has enough balance
19 if (fromUser.balance < amount) {
20 return ctx.badRequest(null, 'Insufficient balance');
21 }
22
23 // Update the user balance
24 fromUser.balance -= amount;
25 toUser.balance += amount;
26
27 // Record the transaction
28 const receipt = await strapi.query('receipt').create({
29 sender: fromUser.id,
30 recipient: toUser.id,
31 amount,
32 }, { transacting });
33
34 // Save the user
35 await strapi.query('user', 'users-permissions').update({ id: from }, fromUser, { transacting });
36 await strapi.query('user', 'users-permissions').update({ id: to }, toUser, { transacting });
37
38 // respond with the receipt (don't forget to sanitize our output!)
39 return sanitizeEntity(receipt, { model: strapi.models.receipt });
40 });
41 }
42 };
We also need to add a route to route config of Receipt. After that, we can call the controller function from API.
.api/receipt/config/routes.json
1 {
2 "routes": [
3 // ...
4 {
5 "method": "POST",
6 "path": "/receipts/transfer-balance",
7 "handler": "receipt.transferBalance",
8 "config": {
9 "policies": []
10 }
11 }
12 ]
13 }
Then we need to allow this endpoint to be accessed publicly so we can request it with Postman. In the sidebar, Go to Settings, Roles, Public, then at the Application section, look for transferbalance
and click Save. Remember this is not the right way to give access to this endpoint in real life, we just only do it for an easy demonstration!
Now let’s add two new users using Admin Dashboard. Go to Users in the sidebar then Add New Users. Let’s call them alpha
and bravo
and set each balance to 1000. If you haven’t added any users beforehand, the ids should be 1
and 2
.
Now open Postman and try to call our controller function, by sending the following POST
to .
If everything is done correctly, we would receive this response.
1 {
2 "id": 1,
3 "sender": {
4 "id": 1,
5 "username": "alpha",
6 "email": "alpha@example.com",
7 "provider": "local",
8 "confirmed": false,
9 "blocked": false,
10 "role": 1,
11 "balance": 900,
12 "created_at": "2021-11-15T08:25:05.013Z",
13 "updated_at": "2021-11-15T09:30:33.243Z"
14 },
15 "recipient": {
16 "id": 2,
17 "username": "bravo",
18 "email": "bravo@example.com",
19 "provider": "local",
20 "confirmed": false,
21 "blocked": false,
22 "role": 1,
23 "balance": 1100,
24 "created_at": "2021-11-15T08:25:55.309Z",
25 "updated_at": "2021-11-15T09:30:33.279Z"
26 },
27 "amount": 100,
28 "created_at": "2021-11-15T09:31:27.483Z",
29 "updated_at": "2021-11-15T09:31:27.494Z"
30 }
We can see that the transfer from alpha
to bravo
for the amount of 100
has been successfully done! You can also confirm both user balances and the new Receipt item in the Admin Dashboard.
Why bother using database transactions when there’s seems to be no difference at all compared to when we don’t use it?
That kind of assumption could be our biggest mistake in the long term.
Using database transactions creates a guarantee that there will be no query that’s executed only halfway no matter it’s caused by a software error or even a hardware power outage.
So for our demonstration, let’s rewrite our function without database transaction.
1 'use strict';
2 const { sanitizeEntity } = require("strapi-utils/lib");
3 module.exports = {
4 async transferBalance(ctx) {
5 // Read from POST body
6 const { amount, from, to } = ctx.request.body;
7 // Find the user
8 const fromUser = await strapi.query('user', 'users-permissions').findOne({ id: from }, null);
9 const toUser = await strapi.query('user', 'users-permissions').findOne({ id: to }, null);
10 // Check if the user has enough balance
11 if (fromUser.balance < amount) {
12 return ctx.badRequest(null, 'Insufficient balance');
13 }
14 // Save the user data
15 await strapi.query('user', 'users-permissions').update({ id: from }, { balance: fromUser.balance -= amount });
16 await strapi.query('user', 'users-permissions').update({ id: to }, { balance: toUser.balance += amount });
17 // Record the transaction
18 let receipt = await strapi.query('receipt').create({
19 sender: fromUser.id,
20 recipient: toUser.id,
21 amount,
22 });
23 // respond with the receipt (don't forget to sanitize our output!)
24 return sanitizeEntity(receipt, { model: strapi.models.receipt });
25 }
26 };
What would happen if we send data with to
to a non-existing user ID? The controller will throw on line 16, simply because toUser
is null (it does not exist). Because line 15 is already been executed, the sender balance transferred will simply go out of nowhere.
That is the danger of doing multiple queries without a transaction. Of course, our example above is straightforwardly not secure, it’s easy to spot mistakes there. But the real world is messy, in some point in the future our functions are often 100-ish lines long and we wouldn’t know that a vulnerability existed until it’s become too late.
Another important feature of database transactions is they’re safe from a race condition. To explain that, we need to take a stress test to our functions above.
Let’s try the insecure one (without database transaction) first. First things first, we need to reset both user balances to 1000
each (you can modify them in Admin Dashboard), then we run a thousand transfer requests in parallel. Let’s do this in a browser. Open your browser and the console tab in the browser development tools (Press f12
). Paste and run the below code.
1 // loop a thousand times and send fetch() simultaneously!
2 for (let i = 0; i < 1000; i++) {
3 fetch('http://localhost:1337/receipts/transfer-balance', {
4 body: '{"from": 1, "to":2, "amount":1}',
5 method: 'POST',
6 headers: {
7 'content-type': 'application/json'
8 }
9 })
10 }
Take a moment to understand what we are doing. We are transferring an amount of 1
, from account alpha
to bravo
, a thousand times. If the starting balance for both is 1000
, then we would expect the alpha
balance to end in 0
and bravo
end with 2000
.
If we use the controller without a database transaction, the result will looks something like this:
While the controller with a database transaction ends as we expected:
You might be asking, why it can be like that? Because database transactions are not just about error safety, it’s also about consistency. By using database transactions those queries are guaranteed to be isolated, not have any else query interrupting between the way. The database can make it possible by exclusively locking any row that’s been used in a transaction, forcing other modifications are waiting until it’s either committed or rolled back.
Consistency and Isolation are important aspects of the database world. If we need to mutate (changing iteratively) a row of data, we need to use a database transaction. Of course, it’s not just about money or balance, think like a voting system, a gift card, or even articles’ view count. It’s important to wrap any iteratively changing data in a database transaction.
Most of the time, using database transactions won’t introduce any noticeable performance impact. However, if you encounter that, Knex.js lets you choose how much “safety” you need for a specific transaction. These are known as Isolation Levels. There are four levels of isolations, a less restrictive level will give some performance boost in the trade of less stability. These isolation levels (ordered from the strongest one) are:
Depending on your use case, it may be best (or not) to leave with the default level. You can read on this Wikipedia page for further reading. To apply a specific level, you can read the isolation levels section of Knex.js documentation. I will summarize how to do that here in the code below:
1 try {
2 const isolationLevel = 'read committed';
3 const transacting = await knex.transaction({isolationLevel});
4 // ... database query here ...
5 await transacting.commit();
6 } catch (err) {
7 await transacting.rollback();
8 }
Be warned that SQLite doesn’t support setting isolation levels, so if you use SQLite for development only, don't override it.
1 const isProduction = strapi.config.environment === 'production';
2 const isolationLevel = isProduction ? 'read committed' : null;
3 const transacting = await knex.transaction({isolationLevel});
4 // ... database query below ...
This article demonstrated how to safely write queries using Database Transaction in Strapi. We also learn how important it can be in production servers.
You can download the source code from this code repository.
Let me know you have any suggestions and what you will be building with the knowledge.