docs/Reference/Lifecycle.md
<a id="lifecycle"></a>
This diagram shows the internal lifecycle of Fastify.
The right branch of each section shows the next phase of the lifecycle. The left branch shows the corresponding error code generated if the parent throws an error. All errors are automatically handled by Fastify.
Incoming Request
│
└─▶ Routing
│
└─▶ Instance Logger
│
4**/5** ◀─┴─▶ onRequest Hook
│
4**/5** ◀─┴─▶ preParsing Hook
│
4**/5** ◀─┴─▶ Parsing
│
4**/5** ◀─┴─▶ preValidation Hook
│
400 ◀─┴─▶ Validation
│
4**/5** ◀─┴─▶ preHandler Hook
│
4**/5** ◀─┴─▶ User Handler
│
└─▶ Reply
│
4**/5** ◀─┴─▶ preSerialization Hook
│
└─▶ onSend Hook
│
4**/5** ◀─┴─▶ Outgoing Response
│
└─▶ onResponse Hook
When handlerTimeout is configured, a
timer starts after routing. If the response is not sent within the allowed time,
request.signal is aborted and a 503 Service Unavailable error is sent.
The timer is cancelled when the response completes
or when reply.hijack() is called.
Before or during the User Handler, reply.hijack() can be called to:
If reply.raw is used to send a response, onResponse hooks will still
be executed.
<a id="reply-lifecycle"></a>
When the user handles the request, the result may be:
ErrorError instanceIf the reply is hijacked, all subsequent steps are skipped. Otherwise, the data flows as follows:
★ schema validation Error
│
└─▶ schemaErrorFormatter
│
reply sent ◀── JSON ─┴─ Error instance
│
│ ★ throw an Error
★ send or return │ │
│ │ │
│ ▼ │
reply sent ◀── JSON ─┴─ Error instance ──▶ onError Hook ◀───────┘
│
reply sent ◀── JSON ─┴─ Error instance ──▶ setErrorHandler
│
└─▶ reply sent
reply sent means the JSON payload will be serialized by one of the following:
JSON.stringify function<a id="shutdown-lifecycle"></a>
When fastify.close() is called, the server goes through a
graceful shutdown sequence involving
preClose hooks, connection draining, and
onClose hooks. See the
close method documentation for the full step-by-step
lifecycle.