Bird
Raised Fist0
Node.jsframework~8 mins

AbortController for cancellation in Node.js - Performance & Optimization

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Performance: AbortController for cancellation
MEDIUM IMPACT
This affects how efficiently asynchronous operations can be stopped to save resources and improve responsiveness.
Canceling a long-running fetch request when no longer needed
Node.js
const controller = new AbortController();
const signal = controller.signal;
const response = await fetch(url, { signal });
// Later if needed
controller.abort();
Fetch request is aborted immediately when no longer needed, freeing resources.
📈 Performance GainPrevents unnecessary network and CPU usage, improving responsiveness
Canceling a long-running fetch request when no longer needed
Node.js
const response = await fetch(url);
// No cancellation, fetch runs to completion even if no longer needed
Fetch request continues even if user navigates away or cancels, wasting network and CPU resources.
📉 Performance CostBlocks resources until fetch completes, increasing CPU and network usage unnecessarily
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
No cancellationN/AN/AN/A[!] Poor
Using AbortControllerN/AN/AN/A[OK] Good
Rendering Pipeline
AbortController signals cancellation to async tasks, preventing further processing and resource use.
JavaScript Execution
Network Request Handling
⚠️ BottleneckContinued execution of unnecessary async tasks wastes CPU and network bandwidth
Core Web Vital Affected
INP
This affects how efficiently asynchronous operations can be stopped to save resources and improve responsiveness.
Optimization Tips
1Use AbortController to cancel async tasks when no longer needed to save CPU and network resources.
2Cancelling tasks early improves input responsiveness (INP) by freeing up the event loop.
3Without cancellation, async tasks waste resources and can degrade user experience.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using AbortController in Node.js async operations?
AIt reduces the size of the JavaScript bundle.
BIt speeds up the initial loading of the page.
CIt stops unnecessary async tasks early, saving CPU and network resources.
DIt improves CSS rendering speed.
DevTools: Performance
How to check: Record a session with and without AbortController; look for long-running fetch or async tasks in the flame chart.
What to look for: Shorter task durations and fewer wasted CPU cycles indicate good cancellation usage.

Practice

(1/5)
1. What is the main purpose of AbortController in Node.js?
easy
A. To manage file system permissions
B. To create new HTTP servers
C. To cancel ongoing asynchronous operations like fetch requests
D. To handle database connections

Solution

  1. Step 1: Understand AbortController's role

    AbortController is designed to stop or cancel asynchronous tasks such as fetch requests.
  2. Step 2: Compare with other options

    Creating servers, managing permissions, or handling databases are unrelated to AbortController's purpose.
  3. Final Answer:

    To cancel ongoing asynchronous operations like fetch requests -> Option C
  4. Quick Check:

    AbortController cancels async tasks = C [OK]
Hint: AbortController is about stopping async tasks quickly [OK]
Common Mistakes:
  • Confusing AbortController with server or database management
  • Thinking it manages permissions
  • Assuming it creates servers
2. Which of the following is the correct way to create an AbortController and get its signal?
easy
A. const signal = new AbortController.signal();
B. const controller = new AbortController; const signal = controller.abort();
C. const controller = AbortController(); const signal = controller.abort;
D. const controller = new AbortController(); const signal = controller.signal;

Solution

  1. Step 1: Check correct instantiation syntax

    AbortController must be created with 'new AbortController()' and its signal accessed via 'controller.signal'.
  2. Step 2: Identify errors in other options

    const signal = new AbortController.signal(); wrongly calls signal as a constructor. const controller = AbortController(); const signal = controller.abort; misses 'new' and uses 'abort' instead of 'signal'. const controller = new AbortController; const signal = controller.abort(); misses parentheses on 'new AbortController()' and calls 'abort()' instead of accessing 'signal'.
  3. Final Answer:

    const controller = new AbortController(); const signal = controller.signal; -> Option D
  4. Quick Check:

    Use 'new' and access 'signal' property = B [OK]
Hint: Always use 'new AbortController()' and get 'signal' property [OK]
Common Mistakes:
  • Forgetting 'new' keyword
  • Calling 'abort' instead of accessing 'signal'
  • Treating 'signal' as a constructor
3. What will be the output of this code snippet?
const controller = new AbortController();
const signal = controller.signal;

setTimeout(() => controller.abort(), 100);

signal.addEventListener('abort', () => console.log('Aborted!'));
medium
A. Logs 'Aborted!' after 100 milliseconds
B. Logs 'Aborted!' immediately
C. Throws an error immediately
D. No output, because abort is never called

Solution

  1. Step 1: Understand the abort timing

    The controller.abort() is called after 100 milliseconds using setTimeout.
  2. Step 2: Check event listener behavior

    The signal listens for 'abort' event and logs 'Aborted!' when triggered.
  3. Final Answer:

    Logs 'Aborted!' after 100 milliseconds -> Option A
  4. Quick Check:

    Abort triggers event after delay = D [OK]
Hint: Abort triggers event after delay, not immediately [OK]
Common Mistakes:
  • Assuming abort happens immediately
  • Expecting no output because of async delay
  • Thinking it throws error instead of event
4. Identify the error in this code snippet that uses AbortController:
const controller = new AbortController();
const signal = controller.signal;

fetch('https://example.com', { signal });
controller.abort();

signal.addEventListener('abort', () => console.log('Fetch aborted'));
medium
A. Not passing the signal to fetch options
B. Calling abort() before adding the abort event listener
C. Using signal.addEventListener instead of controller.addEventListener
D. Missing async/await for fetch

Solution

  1. Step 1: Check event listener timing

    The abort event listener is added after calling controller.abort(), so it misses the event.
  2. Step 2: Verify other parts

    The signal is correctly passed to fetch, and signal is the right object to listen on. Async/await is optional here.
  3. Final Answer:

    Calling abort() before adding the abort event listener -> Option B
  4. Quick Check:

    Add event listener before abort() call = A [OK]
Hint: Add abort listener before calling abort() [OK]
Common Mistakes:
  • Adding listener after abort() call
  • Listening on controller instead of signal
  • Forgetting to pass signal to fetch
5. You want to cancel a fetch request if it takes longer than 200ms. Which code correctly implements this using AbortController?
hard
A. const controller = new AbortController(); setTimeout(() => controller.abort(), 200); fetch('https://api.com/data', { signal: controller.signal }) .catch(err => { if (err.name === 'AbortError') console.log('Request timed out'); });
B. const controller = new AbortController(); fetch('https://api.com/data', { signal: controller.signal }); setTimeout(() => controller.abort(), 200); console.log('Request timed out');
C. const controller = new AbortController(); fetch('https://api.com/data'); setTimeout(() => controller.abort(), 200); .catch(err => console.log('Request timed out'));
D. const controller = new AbortController(); setTimeout(() => controller.abort(), 200); fetch('https://api.com/data', { signal: controller.abort() }) .catch(err => console.log('Request timed out'));

Solution

  1. Step 1: Setup AbortController and timeout

    Create controller, set timeout to call abort after 200ms.
  2. Step 2: Pass signal to fetch and handle abort error

    Pass controller.signal to fetch options and catch AbortError to log timeout message.
  3. Step 3: Identify errors in other options

    const controller = new AbortController(); fetch('https://api.com/data', { signal: controller.signal }); setTimeout(() => controller.abort(), 200); console.log('Request timed out'); logs timeout immediately, not on abort. const controller = new AbortController(); fetch('https://api.com/data'); setTimeout(() => controller.abort(), 200); .catch(err => console.log('Request timed out')); misses passing signal. const controller = new AbortController(); setTimeout(() => controller.abort(), 200); fetch('https://api.com/data', { signal: controller.abort() }) .catch(err => console.log('Request timed out')); incorrectly calls abort() instead of passing signal.
  4. Final Answer:

    const controller = new AbortController(); setTimeout(() => controller.abort(), 200); fetch('https://api.com/data', { signal: controller.signal }) .catch(err => { if (err.name === 'AbortError') console.log('Request timed out'); }); -> Option A
  5. Quick Check:

    Pass signal, abort after delay, catch AbortError = A [OK]
Hint: Pass controller.signal to fetch and abort after timeout [OK]
Common Mistakes:
  • Calling abort() instead of passing signal
  • Logging timeout before abort happens
  • Not passing signal to fetch