Bird
Raised Fist0
NestJSframework~20 mins

Transactions in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Transaction Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when a NestJS service method uses a transaction but an error occurs?

Consider a NestJS service method that wraps multiple database operations inside a transaction using TypeORM's queryRunner. If one operation fails and throws an error, what is the expected behavior of the transaction?

NestJS
async function performOperations(queryRunner) {
  await queryRunner.startTransaction();
  try {
    await queryRunner.manager.save(entity1);
    await queryRunner.manager.save(entity2);
    throw new Error('Failure');
    await queryRunner.commitTransaction();
  } catch (error) {
    await queryRunner.rollbackTransaction();
    throw error;
  } finally {
    await queryRunner.release();
  }
}
AOnly entity1 is saved; entity2 is not saved due to the error.
BNeither entity1 nor entity2 is saved; the transaction rolls back all changes.
CBoth entity1 and entity2 are saved permanently despite the error.
DThe transaction commits partially, saving entity1 and rolling back entity2.
Attempts:
2 left
💡 Hint

Think about what a transaction does when an error occurs inside it.

📝 Syntax
intermediate
1:30remaining
Which option correctly starts and commits a transaction using TypeORM's QueryRunner in NestJS?

Choose the code snippet that correctly starts a transaction, performs an operation, and commits it using QueryRunner.

Aawait queryRunner.startTransaction(); await queryRunner.manager.save(entity); await queryRunner.commitTransaction(); await queryRunner.release();
Bawait queryRunner.manager.startTransaction(); await queryRunner.save(entity); await queryRunner.commit(); await queryRunner.release();
CqueryRunner.startTransaction(); queryRunner.manager.save(entity); queryRunner.commitTransaction(); queryRunner.release();
Dawait queryRunner.begin(); await queryRunner.manager.save(entity); await queryRunner.commit(); await queryRunner.release();
Attempts:
2 left
💡 Hint

Check the exact method names on QueryRunner for starting and committing transactions.

🔧 Debug
advanced
2:30remaining
Why does this NestJS transaction code cause a 'QueryRunner already released' error?

Review the following code snippet. It throws a 'QueryRunner already released' error when running multiple transactions sequentially. What is the cause?

NestJS
async function runTransaction(data) {
  const queryRunner = dataSource.createQueryRunner();
  await queryRunner.connect();
  await queryRunner.startTransaction();
  try {
    await queryRunner.manager.save(data);
    await queryRunner.commitTransaction();
  } catch (err) {
    await queryRunner.rollbackTransaction();
  } finally {
    await queryRunner.release();
  }
}

await runTransaction(entity1);
await runTransaction(entity2);
AThe queryRunner is released inside the function, so calling runTransaction twice creates conflicts.
BThe queryRunner is not connected before starting the transaction, causing the error.
CThe dataSource is not initialized, so queryRunner cannot be created.
DThe function does not await commitTransaction, so the release happens too early.
Attempts:
2 left
💡 Hint

Consider what happens to the queryRunner after release() is called.

❓ state_output
advanced
3:00remaining
What is the final state of the database after nested transactions with savepoints in NestJS?

Given the following pseudo-code using TypeORM's QueryRunner with savepoints, what data remains saved after execution?

NestJS
await queryRunner.startTransaction();
try {
  await queryRunner.manager.save(entityA);
  await queryRunner.query('SAVEPOINT sp1');
  await queryRunner.manager.save(entityB);
  throw new Error('Error after sp1');
  await queryRunner.query('RELEASE SAVEPOINT sp1');
  await queryRunner.commitTransaction();
} catch (e) {
  await queryRunner.query('ROLLBACK TO SAVEPOINT sp1');
  await queryRunner.commitTransaction();
}
ABoth entityA and entityB are saved permanently.
BOnly entityB is saved; entityA is rolled back.
CNeither entityA nor entityB is saved; the entire transaction is rolled back.
DOnly entityA is saved; entityB is rolled back to the savepoint.
Attempts:
2 left
💡 Hint

Think about what rolling back to a savepoint does inside a transaction.

🧠 Conceptual
expert
2:00remaining
Why should you avoid long-running transactions in NestJS applications?

In NestJS applications using database transactions, why is it important to keep transactions short and avoid long-running ones?

ALong transactions are automatically converted to read-only, preventing data changes.
BLong transactions automatically commit after a timeout, risking partial data saves.
CLong transactions can lock database rows or tables, reducing concurrency and causing performance issues.
DLong transactions consume less memory but increase CPU usage drastically.
Attempts:
2 left
💡 Hint

Consider how databases handle locks during transactions.

Practice

(1/5)
1. What is the main purpose of using transactions in a NestJS application with a database?
easy
A. To automatically generate database schemas
B. To ensure multiple database operations succeed or fail together
C. To speed up database queries by caching results
D. To log all database queries for debugging

Solution

  1. Step 1: Understand what transactions do

    Transactions group multiple database actions so they either all succeed or all fail, preventing partial updates.
  2. Step 2: Identify the purpose in NestJS context

    In NestJS, transactions keep data consistent by ensuring grouped operations are atomic.
  3. Final Answer:

    To ensure multiple database operations succeed or fail together -> Option B
  4. Quick Check:

    Transactions = atomic operations [OK]
Hint: Transactions keep grouped DB actions all-or-nothing [OK]
Common Mistakes:
  • Thinking transactions speed up queries
  • Confusing transactions with schema generation
  • Assuming transactions are for logging only
2. Which of the following is the correct way to start a transaction using TypeORM's DataSource in NestJS?
easy
A. dataSource.transaction(async (manager) => { /* operations */ })
B. dataSource.startTransaction(() => { /* operations */ })
C. dataSource.begin(async () => { /* operations */ })
D. dataSource.runTransaction(() => { /* operations */ })

Solution

  1. Step 1: Recall TypeORM transaction method

    TypeORM uses dataSource.transaction with an async callback to run transactional code.
  2. Step 2: Check method names

    Only dataSource.transaction(async (manager) => { /* operations */ }) uses the correct method name and async callback pattern.
  3. Final Answer:

    dataSource.transaction(async (manager) => { /* operations */ }) -> Option A
  4. Quick Check:

    Correct method is transaction with async callback [OK]
Hint: Use dataSource.transaction with async callback [OK]
Common Mistakes:
  • Using non-existent methods like startTransaction
  • Omitting async keyword in callback
  • Using wrong method names like begin or runTransaction
3. Given the following code snippet in a NestJS service using TypeORM, what will be the output if the second operation fails?
await dataSource.transaction(async (manager) => {
  await manager.save(user1);
  await manager.save(user2); // throws error
});
console.log('Transaction complete');
medium
A. Neither user1 nor user2 are saved, and an error is thrown before logging
B. Only user1 is saved, then 'Transaction complete' is logged
C. Both user1 and user2 are saved, then 'Transaction complete' is logged
D. 'Transaction complete' is logged before any save operations

Solution

  1. Step 1: Understand transaction rollback behavior

    If any operation inside the transaction fails, all changes are rolled back, so no data is saved.
  2. Step 2: Analyze the code flow

    The second save throws an error, so the transaction aborts and neither user1 nor user2 are saved. The error prevents reaching the console.log.
  3. Final Answer:

    Neither user1 nor user2 are saved, and an error is thrown before logging -> Option A
  4. Quick Check:

    Transaction rollback on error = no saves, error thrown [OK]
Hint: Error inside transaction rolls back all changes [OK]
Common Mistakes:
  • Assuming partial saves happen before error
  • Thinking console.log runs despite error
  • Believing transaction commits despite failure
4. Identify the error in this NestJS transaction code snippet:
await dataSource.transaction(async (manager) => {
  manager.save(user1);
  await manager.save(user2);
});
medium
A. dataSource.transaction requires a synchronous callback
B. Transaction callback should not be async
C. Missing await before manager.save(user1)
D. manager.save cannot be used inside transactions

Solution

  1. Step 1: Check async calls inside transaction

    All asynchronous operations inside the transaction callback must be awaited to ensure proper execution order.
  2. Step 2: Identify missing await

    The first save call lacks await, so it may not complete before the second save starts, causing unexpected behavior.
  3. Final Answer:

    Missing await before manager.save(user1) -> Option C
  4. Quick Check:

    Await all async DB calls inside transaction [OK]
Hint: Always await async DB calls inside transaction [OK]
Common Mistakes:
  • Omitting await on async calls
  • Thinking transaction callback can't be async
  • Believing manager.save is disallowed in transactions
5. You want to update two related entities atomically in NestJS using TypeORM transactions. Which approach correctly ensures both updates succeed or fail together?
async updateEntities(entityA, entityB) {
  await this.dataSource.transaction(async (manager) => {
    await manager.save(entityA);
    await manager.save(entityB);
  });
}
What is the best practice to handle errors and maintain data consistency?
hard
A. Manually call rollback() inside the transaction callback on error
B. Save entities without transactions and rely on database constraints
C. Use separate transactions for each save to isolate failures
D. Wrap the transaction call in try-catch and handle rollback automatically

Solution

  1. Step 1: Understand transaction error handling in TypeORM

    TypeORM automatically rolls back if an error is thrown inside the transaction callback.
  2. Step 2: Use try-catch outside transaction to handle errors

    Wrapping the transaction call in try-catch lets you catch errors and respond without manual rollback calls.
  3. Final Answer:

    Wrap the transaction call in try-catch and handle rollback automatically -> Option D
  4. Quick Check:

    Try-catch outside transaction handles errors; rollback is automatic [OK]
Hint: Use try-catch around transaction; rollback is automatic [OK]
Common Mistakes:
  • Trying to manually rollback inside transaction callback
  • Using separate transactions for related updates
  • Ignoring transactions and relying only on DB constraints
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard