Full answer
Pitfalls and fixes
- N+1 queries
- teachers.findAll() then teacher.getStudents() for each teacher runs 1 + N queries. Fix with eager loading (include in Sequelize, include in Prisma) which uses a join or one extra IN query, or with a DataLoader in GraphQL.
- Over-fetching
- By default models select every column, including large text or JSON fields. Select what you need (attributes in Sequelize, select in Prisma). Return DTOs, not models.
- Row by row writes
- A loop with create() makes N round trips. Use bulkCreate, createMany or a single INSERT with many rows. For updates, use one UPDATE with a WHERE clause instead of loading, changing and saving each row.
- Missing transactions
- A business operation with several writes (create order, reduce stock) must run in a transaction. Sequelize managed transactions (sequelize.transaction(async (t) => ...)) commit when the callback resolves and roll back when it throws. Pass the transaction to every query inside.
- Keep transactions short. Do not call slow external services inside one.
- Lost updates and races
- Read, change, save can overwrite another writer. Use atomic updates (increment), optimistic locking (version column) or SELECT ... FOR UPDATE.
- Pagination and counts
- Offset pagination on big tables and count queries on every request are slow. Use keyset pagination where possible.
- Migrations and schema drift
- Do not use sync({ force: true }) or auto sync in production. Use versioned migrations.
How to check: enable query logging in development, count queries per request in tests (fail a test if a route runs more than expected), use EXPLAIN on slow queries, and add indexes for foreign keys and filter columns.
const { Sequelize, DataTypes } = require('sequelize');
(async () => {
let log = [];
const sequelize = new Sequelize({
dialect: 'postgres', host: process.env.PGHOST, port: Number(process.env.PGPORT), username: process.env.PGUSER, database: process.env.PGDATABASE,
logging: (sql) => log.push(sql.replace(/^Executing \(default\): /, '')),
});
const Teacher = sequelize.define('Teacher', { name: DataTypes.STRING }, { tableName: 'orm2_teachers', timestamps: false });
const Student = sequelize.define('Student', { name: DataTypes.STRING, notes: DataTypes.TEXT }, { tableName: 'orm2_students', timestamps: false });
Teacher.hasMany(Student);
Student.belongsTo(Teacher);
await sequelize.sync({ force: true });
const teachers = await Teacher.bulkCreate([{ name: 'T1' }, { name: 'T2' }, { name: 'T3' }]);
await Student.bulkCreate(teachers.flatMap((t, i) => [{ name: `S${i}a`, TeacherId: t.id }, { name: `S${i}b`, TeacherId: t.id }]));
const count = () => log.filter((q) => /^(SELECT|INSERT|UPDATE)/.test(q)).length;
// 1. N+1
log = [];
for (const t of await Teacher.findAll()) await t.getStudents();
console.log('1. lazy loading in a loop :', count(), 'queries for 3 teachers');
log = [];
await Teacher.findAll({ include: Student });
console.log(' eager loading with include :', count(), 'query');
// 2. Over-fetching
log = [];
await Student.findAll({ attributes: ['id', 'name'] });
console.log('2. selected columns :', log[0].match(/SELECT (.*) FROM/)[1]);
// 3. Row by row writes versus a bulk insert
log = [];
for (let i = 0; i < 5; i++) await Student.create({ name: 'loop' + i });
const loopQueries = count();
log = [];
await Student.bulkCreate(Array.from({ length: 5 }, (_, i) => ({ name: 'bulk' + i })));
console.log('3. five creates in a loop :', loopQueries, 'queries | bulkCreate:', count(), 'query');
// 4. A managed transaction rolls back everything when the callback throws
const before = await Student.count();
try {
await sequelize.transaction(async (transaction) => {
await Student.create({ name: 'in-transaction' }, { transaction });
throw new Error('stock check failed');
});
} catch (err) { console.log('4. transaction failed :', err.message); }
console.log(' rows before and after :', before, await Student.count());
await sequelize.query('DROP TABLE orm2_students; DROP TABLE orm2_teachers;');
await sequelize.close();
})();Sequelize runs against a local PostgreSQL server, and the script counts the queries that each approach sends. Install first with npm install sequelize pg (run here with sequelize 6.37.8, pg 8.23.1). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): 1. lazy loading in a loop : 4 queries for 3 teachers eager loading with include : 1 query 2. selected columns : "id", "name" 3. five creates in a loop : 5 queries | bulkCreate: 1 query 4. transaction failed : stock check failed rows before and after : 16 16
Key points
- Eager loading replaces N+1 queries.
- Select only the columns you need.
- Use bulk operations for many writes.
- Wrap multi-step changes in a transaction and pass it to every query.
- Log and count queries in tests.
Common mistakes
- Calling a relation getter inside a loop.
- Looping over create() for imports.
- Doing the steps of one business action without a transaction.
- Using sync({ force: true }) outside tests.
- Returning whole models, including private columns, from the API.
Follow-ups
- How would you find N+1 queries in a running service?
- What is optimistic locking?
- When is SELECT FOR UPDATE the right tool?
Tips
- Open with the N+1 arithmetic.
- Name eager loading, bulk writes and transactions.
- Say 'count the queries in tests'.