Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 38 ยท Getting Started

How Ktor Handles a Request

Follow one HTTP request through a Ktor server: engine, pipeline phases, plugins, routing and the handler, and see why suspend functions scale without blocking threads.

You can write a Ktor application without knowing what happens between "bytes arrive on a socket" and "my handler runs". But when you debug a plugin that runs too early, or wonder why a blocking call slows the whole server, that knowledge is what saves you. This lesson follows one request from the network to your handler and back.

The journey of a request

flowchart LR
    A["Client"] --> B["Engine<br/>(Netty)"]
    B --> C["ApplicationCall"]
    C --> D["Application pipeline"]
    D --> E["Plugins<br/>(logging, auth, ...)"]
    E --> F["Routing"]
    F --> G["Your handler"]
    G --> H["Response pipeline"]
    H --> A

The engine turns bytes into an ApplicationCall; the call travels through plugins and routing to your handler; the response travels back through the response pipeline.

  1. The engine accepts the connection, parses the HTTP request and creates an ApplicationCall that holds the request and response.
  2. The call enters the application call pipeline, an ordered list of phases.
  3. Each plugin you installed attaches interceptors to certain phases. For example, the logging plugin notes the start of the call; authentication checks credentials; content negotiation converts bodies.
  4. The routing plugin matches the URL against your route tree and runs the selected handler.
  5. When the handler calls call.respond(...), the response goes through the send pipeline, where plugins can transform it (for example, serialize an object to JSON or compress it) before the engine writes it to the socket.

Pipelines and phases

A pipeline is a list of phases, and each phase holds interceptors. For server calls, the main phases are:

Phase Typical use
Setup Prepare the call, attach attributes (request ID)
Monitoring Logging, metrics, call IDs
Plugins Most plugins: sessions, authentication, content negotiation
Call The routing and your handler
Fallback Handle calls nobody answered (404 Not Found)

An interceptor can run code before and after proceed(). proceed() means "continue to the next interceptor". This is how a logging plugin measures request time: record the start, call proceed(), then record the end. An interceptor that never calls proceed() short-circuits the call, which is exactly what an authentication plugin does when the credentials are bad.

Stand-in: a pipeline with interceptors

The stand-in below implements this idea in plain Kotlin with coroutines. Each interceptor is a suspend function that receives the call and a proceed function. It is not Ktor's code, but the shape is the same.

Kotlin Stand-in: a request pipeline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Study the second request: the log interceptor ran its first line, the auth interceptor rejected the call and never called proceed(), so the handler was skipped, yet the log interceptor still ran its "after" line. That is the pattern behind every Ktor plugin you will install in the plugins chapter.

Why suspend functions scale

Ktor handlers are suspend lambdas. When a handler awaits something slow, such as a database query through a coroutine-aware driver, a remote HTTP call or delay, it suspends: its thread is released to serve other calls, and the coroutine resumes later. To see the effect, the next program handles 1,000 "requests" that each wait 100 ms, on a single thread, and finishes in roughly one wait, not 100 seconds.

Kotlin Stand-in: 1,000 concurrent waits on one thread

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The flip side: blocking calls (Thread.sleep, a blocking JDBC call, reading a big file) hold the thread and stall every other call that thread would have run. Move them to withContext(Dispatchers.IO) { ... }. See coroutine builders for the background, and the deployment chapter of this track for tuning.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does an interceptor have to do to let the call continue to the handler?

    proceed() continues to the next interceptor or the handler; not calling it short-circuits the call.
  2. 2. Which component turns bytes from the socket into an ApplicationCall?

    The engine parses HTTP and creates the call that enters the pipeline.
  3. 3. Why is a blocking JDBC call inside a handler a problem?

    Blocking holds the thread; suspend calls free it. Wrap blocking work in withContext(Dispatchers.IO).
  4. 4. An authentication interceptor rejects a call with 401. What happens to the route handler?

    Rejecting without proceed() short-circuits the pipeline before routing.

Summary

  • The engine creates an ApplicationCall; it flows through the pipeline, plugins, routing and your handler, then back out through the send pipeline.
  • Plugins attach interceptors to phases; proceed() continues, not calling it short-circuits.
  • Handlers are suspend functions, so waiting does not hold a thread.
  • Keep blocking work off the event threads with Dispatchers.IO.

You now know what a Ktor application is made of. Next up: routing, the part you will write the most.

Next: Routing Basics