Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Cancelling HTTP Requests: AbortController vs RxJS Observables

This project demonstrates the difference between cancelling only the HTTP connection (AbortController) and cancelling the whole sequence including server-side work (RxJS Observables + teardown).


Table of contents

  1. How Observables work
  2. Stopping events in sequence: AbortController vs RxJS
  3. What happens in this project
  4. Summary

How Observables work

What is an Observable?

An Observable is a lazy stream of values over time. It does nothing until someone subscribes to it. When you subscribe, the producer runs and can emit values, errors, or complete.

flowchart LR
  subgraph Producer
    P[Producer runs when subscribed]
  end
  subgraph Observable
    O[Stream of values]
  end
  subgraph Subscriber
    S[Receives values / NestJS response]
  end
  P --> O --> S
Loading
flowchart LR
  A[Subscribe] --> B[Producer starts]
  B --> C[Emit values over time]
  C --> D[Complete or Error]
  D --> E[Teardown runs if unsubscribed]
Loading

Subscription and teardown

When you subscribe, you get a Subscription. The Observable's producer can return a teardown function:

new Observable(observer => {
  const id = setInterval(() => observer.next(1), 1000);
  return () => clearInterval(id);  // ← teardown: runs when subscription is disposed
});
sequenceDiagram
  participant Subscriber
  participant Observable
  participant Producer

  Subscriber->>Observable: subscribe()
  Observable->>Producer: run producer
  Producer->>Observable: next(value) / complete()
  Observable->>Subscriber: emit value

  Note over Subscriber,Observable: When subscriber unsubscribes:
  Subscriber->>Observable: unsubscribe()
  Observable->>Producer: run teardown()
  Producer->>Producer: clearInterval / set cancelled = true / close resources
Loading
  • Subscribe → producer runs (e.g. start HTTP request, start heavy work).
  • Unsubscribe (or complete/error) → teardown runs (e.g. clear timers, abort work, close resources).

So: cancelling a subscription = running teardown = stopping the underlying work, if the producer was written to do so.

Observable lifecycle (cold)

stateDiagram-v2
  [*] --> Created: new Observable(...)
  Created --> Subscribed: subscribe()
  Subscribed --> Running: producer runs
  Running --> Emitting: next(value)
  Emitting --> Running: more values
  Running --> Completed: complete() or error()
  Running --> Disposed: unsubscribe()
  Disposed --> [*]: teardown runs
  Completed --> [*]: teardown runs
Loading
  • Cold: work starts only when there is a subscriber (e.g. our heavy CPU).
  • When the subscriber unsubscribes, the Observable is disposed and the teardown runs. That is how we stop the sequence on the server when the client disconnects.

Why this matters for HTTP

flowchart TB
  subgraph Client["Browser (Client)"]
    AC[AbortController.abort()]
    AC --> CloseConn[Connection closed]
    AC --> FetchReject[fetch rejects with AbortError]
  end

  subgraph ServerDefault["Server (default: Promise / loop)"]
    Handler[Handler keeps running]
    Handler --> CPU[CPU work continues]
  end

  subgraph ServerObservable["Server (with Observable + teardown)"]
    Close[Socket 'close' event]
    Close --> Unsub[Interceptor unsubscribes]
    Unsub --> Teardown[Teardown runs]
    Teardown --> Stop[Server work stops]
  end

  CloseConn -.->|connection closed| Close
Loading
  • Browser: you cancel the request with AbortController.abort() → the TCP/HTTP connection closes.
  • Server: by default, the handler keeps running (e.g. a Promise or a long loop). The connection is closed, but the process keeps doing work.
  • With Observables: if the server represents the response as an Observable and unsubscribes when the connection closes, the Observable's teardown runs and the server can stop the work (timers, loops, I/O). So "cancel request" becomes "cancel the whole sequence," not only the connection.

Stopping events in sequence: AbortController vs RxJS

AbortController only (client + connection)

What it does:

  • You pass an AbortSignal to fetch(). When you call controller.abort():
    • The browser stops waiting for the response and rejects the fetch Promise with AbortError.
    • The TCP/HTTP connection is closed (client side).

What it does not do:

  • It does not tell the server to stop. The server has no built-in idea that the client "cancelled." From the server's point of view, the connection was closed (client gone or network issue). The handler (e.g. a Promise or a long loop) keeps running until it finishes or the process exits.

Sequence diagram:

sequenceDiagram
  participant User
  participant Browser
  participant Network
  participant Server

  User->>Browser: Click Cancel / controller.abort()
  Browser->>Network: Close connection
  Browser->>Browser: fetch rejects with AbortError
  Browser->>User: Request canceled message

  Note over Server: Handler (Promise/loop) keeps running
  Server->>Server: Heavy work continues...
  Server->>Server: ...until completion
Loading

So with AbortController only, you stop the client-side sequence (request + waiting), but the server-side sequence (heavy work) keeps running.


RxJS + server teardown (client + connection + server work)

What we add:

  • Server:
    • The handler returns an Observable that does the heavy work.
    • The Observable's teardown is implemented so that it stops that work (e.g. set a cancelled flag, clear intervals, close resources).
    • An interceptor listens for "connection closed" (e.g. request.socket 'close' event) and unsubscribes from that Observable.

When the client closes the connection (e.g. after AbortController.abort()):

  1. The socket 'close' event fires on the server.
  2. The interceptor unsubscribes from the handler Observable.
  3. The Observable's teardown runs.
  4. The teardown stops the server-side work (e.g. stops the loop, clears timers).

Sequence diagram:

sequenceDiagram
  participant User
  participant Browser
  participant Network
  participant Interceptor
  participant Observable
  participant HeavyWork

  User->>Browser: fetch(url, { signal })
  Browser->>Network: HTTP request
  Network->>Interceptor: Request arrives
  Interceptor->>Observable: subscribe(handler)
  Observable->>HeavyWork: start chunked work

  loop Every chunk
    HeavyWork->>HeavyWork: burn CPU chunk
  end

  User->>Browser: Click Cancel / controller.abort()
  Browser->>Network: Close connection
  Browser->>User: AbortError
  Network->>Interceptor: socket 'close' event
  Interceptor->>Observable: unsubscribe()
  Observable->>HeavyWork: teardown() → cancelled = true
  HeavyWork->>HeavyWork: stop at next chunk check
Loading

So with RxJS + teardown + "unsubscribe on close", you stop the whole sequence: client request, connection, and server-side work.


Comparison flowchart

flowchart TB
  subgraph AbortOnly["AbortController only"]
    A1[Client: abort] --> A2[Connection closed]
    A2 --> A3[Server: handler keeps running]
    A3 --> A4[CPU continues until done]
  end

  subgraph RxJSTeardown["RxJS + teardown"]
    R1[Client: abort] --> R2[Connection closed]
    R2 --> R3[Server: socket close]
    R3 --> R4[Interceptor: unsubscribe]
    R4 --> R5[Teardown runs]
    R5 --> R6[Server work stops]
  end
Loading

Side-by-side table

Aspect AbortController only RxJS + teardown
Client Request cancelled, fetch rejected Same
Connection Closed Closed
Server handler Keeps running (Promise/loop) Stopped when teardown runs
Server CPU / work Continues until handler ends Stops shortly after disconnect
Implementation signal on fetch Observable with teardown + "unsubscribe on close" interceptor

What happens in this project

Architecture overview

flowchart LR
  subgraph Frontend["Frontend (React + Vite)"]
    TabA[AbortController tab]
    TabR[RxJS tab]
    CPU[CPU monitor panel]
  end

  subgraph Backend["Backend (NestJS)"]
    HeavyA["GET /heavy/abort\n(Promise, no teardown)"]
    HeavyR["GET /heavy/rxjs\n(Observable + teardown)"]
    Stats["GET /stats/cpu"]
    Interceptor[UnsubscribeOnCloseInterceptor]
  end

  TabA --> HeavyA
  TabR --> HeavyR
  CPU --> Stats
  HeavyR -.-> Interceptor
  Interceptor -.->|socket close| HeavyR
Loading

Backend

flowchart TB
  subgraph AbortEndpoint["/heavy/abort"]
    A1[Returns Promise]
    A2[runHeavyAbortAsync]
    A2 --> A3[Chunked CPU work]
    A3 --> A4[Never checks 'cancelled']
    A4 --> A5[Runs until 15s or completion]
  end

  subgraph RxJSEndpoint["/heavy/rxjs"]
    R1[Returns Observable]
    R2[runHeavyRxjs]
    R2 --> R3[Chunked CPU work]
    R3 --> R4[Teardown sets cancelled = true]
    R4 --> R5[Loop checks cancelled each chunk]
    R5 --> R6[Stops when client disconnects]
  end

  Unsub[UnsubscribeOnCloseInterceptor] -->|unsubscribe on socket close| R4
Loading
  • GET /heavy/abort

    • Returns a Promise that runs heavy CPU work in chunks (so the event loop can still serve /stats/cpu).
    • Does not listen for client disconnect.
    • When you cancel on the client, the connection closes but the server keeps running the work until the Promise resolves.
  • GET /heavy/rxjs

    • Returns an Observable that runs the same heavy work in chunks.
    • The Observable's teardown sets a cancelled flag; the chunked loop checks it and stops.
    • UnsubscribeOnCloseInterceptor: when request.socket emits 'close', it unsubscribes from the handler Observable → teardown runs → server stops the work.

So:

  • AbortController only (used with /heavy/abort): you stop the request and the connection; the server does not stop the sequence.
  • RxJS (used with /heavy/rxjs): you stop the request, the connection, and the server-side sequence (CPU work stops when you cancel).

Frontend

  • AbortController tab: calls /heavy/abort, cancels with a "Cancel request" button (and on new input). You see the connection cancel and the "Request canceled" message, but the Backend CPU panel shows that the server keeps working.
  • RxJS tab: calls /heavy/rxjs, cancels the same way. After cancel, Backend CPU and Active heavy requests drop because the server actually stops the work.

Summary

flowchart LR
  subgraph Observable["Observable"]
    O1[Subscribe → work starts]
    O2[Unsubscribe → teardown runs]
    O2 --> O3[Stop server work]
  end

  subgraph Abort["AbortController"]
    A1[abort → connection closed]
    A1 --> A2[Server may keep running]
  end

  subgraph RxJSFull["RxJS + unsubscribe on close"]
    R1[Connection closed]
    R1 --> R2[Unsubscribe]
    R2 --> R3[Teardown → stop work]
  end
Loading
  • Observables: lazy streams; subscription starts work, unsubscribe runs teardown. If teardown is implemented to stop work (flags, clearInterval, close streams), then unsubscribing stops the sequence on the server.
  • AbortController: cancels the client-side request and closes the connection. The server is not obliged to stop; with a normal Promise or loop, the server keeps running.
  • RxJS + "unsubscribe on close": by unsubscribing from the handler Observable when the connection closes, we run its teardown and stop the server-side sequence (e.g. heavy CPU). So "cancel request" becomes "cancel the whole chain": client, connection, and server work.

This project uses both approaches so you can see the difference in behaviour (e.g. in the CPU panel) when you cancel a request.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors