Loading
Portfolio
Rayden Li
NestJS
Production debugging is not the same as running the application with a debugger attached. The goal is to restore service safely, preserve evidence, and identify the failing revision, request, dependency, or resource without exposing customer data or making the incident worse.
This guide uses a NestJS API running in Docker on Google Cloud Run, but the workflow and most of the code apply to any production platform.
When an incident starts:
Do not begin by enabling the Node.js inspector on a public interface, repeatedly restarting instances, dumping request bodies, or taking a heap snapshot on the only healthy instance.
A restart can restore service, but it also destroys useful process state and Cloud Run's local, ephemeral filesystem. Before restarting or rolling back, collect what you can without mutating the service:
varlog/system logsCloud Run automatically provides request, container, and system logs. Container output written to stdout and stderr is collected by Cloud Logging, so a container should log there instead of maintaining local log files. See the official Cloud Run logging guide.
Useful production logs answer five questions:
Use one JSON object per line. Never log authorization headers, cookies, access tokens, passwords, raw request bodies, full database URLs, or unfiltered exception objects. Treat logs and diagnostic files as sensitive production data.
The following examples target current NestJS releases. Nest's ConsoleLogger supports JSON output; current releases also support structured parameters and flattenParams. If an older NestJS version does not support flattenParams, omit it or use an established structured logger that implements Nest's LoggerService interface. Nest documents both approaches in its logging guide.
src/main.tsimport { ConsoleLogger, ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import process from 'node:process';
import { AppModule } from './app.module';
async function bootstrap(): Promise<void> {
const app = await NestFactory.create(AppModule, {
logger: new ConsoleLogger({
json: true,
flattenParams: true,
}),
});
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
}),
);
app.enableShutdownHooks();
const port = Number(process.env.PORT ?? 3000);
await app.listen(port, '0.0.0.0');
}
process.on('uncaughtExceptionMonitor', (error, origin) => {
process.stderr.write(
`${JSON.stringify({
severity: 'CRITICAL',
event: 'uncaught_exception',
errorName: error.name,
stack: error.stack,
origin,
})}\n`,
);
});
bootstrap().catch((error: unknown) => {
process.stderr.write(
`${JSON.stringify({
severity: 'CRITICAL',
event: 'startup_failed',
errorName: error instanceof Error ? error.name : 'UnknownError',
stack: error instanceof Error ? error.stack : undefined,
})}\n`,
);
process.exitCode = 1;
});
Line by line:
| Line or block | Purpose |
|---|---|
ConsoleLogger, ValidationPipe | Enables structured Nest logs and validates untrusted HTTP input. |
NestFactory and AppModule | Create the Nest application from its root module. |
process | Reads Cloud Run's PORT and writes a final crash record to stderr. |
bootstrap(): Promise<void> | Makes startup asynchronous and explicit. |
NestFactory.create(...) | Creates the application before it starts listening. |
json: true | Emits machine-readable, single-line JSON logs. |
flattenParams: true | Places structured log fields at the JSON root so fields such as requestId are easy to query. |
useGlobalPipes(...) | Applies the same input validation policy to all controllers. |
whitelist: true |
Nest's ValidationPipe documentation describes whitelisting, rejecting non-whitelisted properties, transformation, and disabling detailed validation messages. If validation messages would expose too much about a private schema, also set disableErrorMessages: true.
Do not install an uncaughtException handler and then continue serving traffic. Node.js warns that an uncaught exception leaves the application in an undefined state; use a monitor to record it and let the process exit so the platform can replace it. See the official Node.js process documentation.
Accept a client request ID only if it has a small, safe format; otherwise generate one. Cloud Run sends X-Cloud-Trace-Context. Adding its trace ID to a structured log under logging.googleapis.com/trace lets Cloud Logging correlate container and request logs.
src/observability/request-context.middleware.tsimport { Injectable, NestMiddleware } from '@nestjs/common';
import { randomUUID } from 'node:crypto';
import type { NextFunction, Request, Response } from 'express';
export type ObservedRequest = Request & {
requestId: string;
cloudTrace?: string;
};
const SAFE_REQUEST_ID = /^[A-Za-z0-9._-]{1,128}$/;
const CLOUD_TRACE_ID = /^[0-9a-f]{32}$/;
@Injectable()
export class RequestContextMiddleware implements NestMiddleware {
use(request: ObservedRequest, response: Response, next: NextFunction): void {
const suppliedId = request.header('x-request-id');
request.requestId =
suppliedId && SAFE_REQUEST_ID.test(suppliedId) ? suppliedId : randomUUID();
const traceId = request.header('x-cloud-trace-context')?.split('/')[0];
const projectId = process.env.GOOGLE_CLOUD_PROJECT;
if (traceId && projectId && CLOUD_TRACE_ID.test(traceId)) {
request.cloudTrace = `projects/${projectId}/traces/${traceId}`;
}
response.setHeader('x-request-id', request.requestId);
next();
}
}
Line by line:
| Line or block | Purpose |
|---|---|
NestMiddleware | Uses Nest's standard middleware lifecycle. |
randomUUID() | Generates a collision-resistant request ID when the caller did not provide a valid one. |
ObservedRequest | Adds typed observability fields to the Express request for later filters and interceptors. |
SAFE_REQUEST_ID | Prevents unbounded or control-character input from becoming a log field or response header. |
CLOUD_TRACE_ID | Accepts only the 32-character lowercase hexadecimal Cloud Trace ID format. |
request.header('x-request-id') | Reads an incoming correlation ID without logging any other headers. |
| Conditional assignment | Reuses a safe ID or creates a new one. |
x-cloud-trace-context split | Extracts the trace ID before the slash-delimited span/options portion. |
GOOGLE_CLOUD_PROJECT | Provides the project portion of Cloud Logging's trace resource name. |
request.cloudTrace = ... | Stores the fully qualified trace value for structured logs. |
Google documents the trace field and header correlation format in Logging and viewing logs in Cloud Run.
GOOGLE_CLOUD_PROJECT is not one of Cloud Run's automatically reserved service environment variables. Configure it explicitly in the service, or obtain the project ID through an approved Google Cloud metadata/client mechanism. If it is absent, request IDs still work but the middleware omits the Cloud Logging trace resource field.
src/observability/request-logging.interceptor.tsimport {
CallHandler,
ExecutionContext,
HttpException,
Injectable,
Logger,
NestInterceptor,
} from '@nestjs/common';
import type { Response } from 'express';
import { finalize, tap, type Observable } from 'rxjs';
import type { ObservedRequest } from './request-context.middleware';
@Injectable()
export class RequestLoggingInterceptor implements NestInterceptor {
private readonly logger = new Logger(RequestLoggingInterceptor.name);
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
const http = context.switchToHttp();
const request = http.getRequest<ObservedRequest>();
const response = http.getResponse<Response>();
const startedAt = performance.now();
let failedStatusCode: number | undefined;
return next.handle().pipe(
tap({
error: (error: unknown) => {
failedStatusCode = error instanceof HttpException ? error.getStatus() : 500;
},
}),
finalize(() => {
this.logger.log('request_complete', {
severity: 'INFO',
requestId: request.requestId,
method: request.method,
path: request.path,
statusCode: failedStatusCode ?? response.statusCode,
durationMs: Number((performance.now() - startedAt).toFixed(1)),
...(request.cloudTrace
? { 'logging.googleapis.com/trace': request.cloudTrace }
: {}),
});
}),
);
}
}
Line by line:
| Line or block | Purpose |
|---|---|
| Nest interceptor imports | Wrap the controller call without changing controller code. |
Response and ObservedRequest | Provide typed access to status and correlation fields. |
RxJS tap and finalize | Capture a thrown HTTP status, then log after success, error, or cancellation. |
new Logger(...) | Names log records with the interceptor context. |
switchToHttp() | Selects the HTTP execution context. |
getRequest / getResponse | Reads request metadata and the final response status. |
performance.now() | Uses a monotonic clock for elapsed time. |
next.handle() | Continues to the controller and returns its observable. |
tap({ error }) | Records an exception's intended status before the exception filter changes the HTTP response. Unknown exceptions are treated as 500. |
Nest recommends registering a dependency-injected global interceptor with APP_INTERCEPTOR; see the interceptors documentation.
src/observability/all-exceptions.filter.tsimport {
ArgumentsHost,
Catch,
ExceptionFilter,
HttpException,
HttpStatus,
Logger,
} from '@nestjs/common';
import type { Response } from 'express';
import type { ObservedRequest } from './request-context.middleware';
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
private readonly logger = new Logger(AllExceptionsFilter.name);
catch(exception: unknown, host: ArgumentsHost): void {
const http = host.switchToHttp();
const request = http.getRequest<ObservedRequest>();
const response = http.getResponse<Response>();
const statusCode =
exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
const exceptionResponse =
exception instanceof HttpException ? exception.getResponse() : undefined;
const clientMessage =
statusCode >= 500
? 'Internal server error'
: getPublicMessage(exceptionResponse, 'Request failed');
this.logger.error('request_failed', {
severity: 'ERROR',
requestId: request.requestId,
method: request.method,
path: request.path,
statusCode,
errorName: exception instanceof Error ? exception.name : 'UnknownError',
stack: exception instanceof Error ? exception.stack : undefined,
...(request.cloudTrace
? { 'logging.googleapis.com/trace': request.cloudTrace }
: {}),
});
response.status(statusCode).json({
statusCode,
message: clientMessage,
requestId: request.requestId,
});
}
}
function getPublicMessage(value: unknown, fallback: string): unknown {
if (typeof value === 'string') return value;
if (value && typeof value === 'object' && 'message' in value) {
return (value as { message: unknown }).message;
}
return fallback;
}
Line by line:
| Line or block | Purpose |
|---|---|
@Catch() | Catches every exception that reaches the HTTP exception layer. |
ExceptionFilter | Implements Nest's exception-filter contract. |
HttpException | Distinguishes intentional HTTP errors from unexpected failures. |
statusCode branch | Preserves expected 4xx/HTTP status codes and maps unknown failures to 500. |
exceptionResponse | Reads the public response intentionally attached to an HttpException. |
statusCode >= 500 | Ensures internal exception messages and stack traces never reach the client. |
logger.error(...) | Writes the internal diagnostic record to protected logs. |
errorName and stack | Retain the error type and call path; never add request bodies or secrets here. |
response.status(...).json(...) | Returns a stable error shape and a support-friendly request ID. |
Nest already has a built-in exception layer; a custom catch-all filter is useful only when you need a consistent public error shape and structured internal event. The official exception filters guide explains the default behavior and global filters.
src/app.module.tsimport { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { APP_FILTER, APP_INTERCEPTOR } from '@nestjs/core';
import { TerminusModule } from '@nestjs/terminus';
import { AllExceptionsFilter } from './observability/all-exceptions.filter';
import { RequestContextMiddleware } from './observability/request-context.middleware';
import { RequestLoggingInterceptor } from './observability/request-logging.interceptor';
import { HealthController } from './health.controller';
@Module({
imports: [TerminusModule],
controllers: [HealthController],
providers: [
{ provide: APP_FILTER, useClass: AllExceptionsFilter },
{ provide: APP_INTERCEPTOR, useClass: RequestLoggingInterceptor },
],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer): void {
consumer.apply(RequestContextMiddleware).forRoutes('*');
}
}
Line by line:
| Line or block | Purpose |
|---|---|
APP_FILTER, APP_INTERCEPTOR | Registers global providers while retaining dependency injection. |
TerminusModule | Supplies health-check orchestration and indicators. |
controllers | Exposes the health endpoints defined next. |
APP_FILTER provider | Applies the safe error response to every controller. |
APP_INTERCEPTOR provider | Times and logs every controller request. |
implements NestModule | Adds module-level middleware configuration. |
forRoutes('*') | Assigns a request ID before controllers, interceptors, and filters need it. |
Merge these registrations into the application's existing root or observability module; do not create a second AppModule. Import the application's database module as usual if readiness checks depend on it.
Liveness asks, “Can this process make progress?” Readiness asks, “Can this instance safely handle a real request?” Do not put the database in liveness: a database outage could trigger a restart loop across every otherwise healthy API instance.
Install Terminus if the project does not already have it:
npm install @nestjs/terminus
The following readiness example assumes the application already uses Nest's TypeORM integration.
src/health.controller.tsimport { Controller, Get } from '@nestjs/common';
import {
HealthCheck,
HealthCheckService,
TypeOrmHealthIndicator,
} from '@nestjs/terminus';
@Controller('health')
export class HealthController {
constructor(
private readonly health: HealthCheckService,
private readonly database: TypeOrmHealthIndicator,
) {}
@Get('live')
live(): { status: 'ok' } {
return { status: 'ok' };
}
@Get('ready')
@HealthCheck()
ready() {
return this.health.check([
() =>
this.database.pingCheck('database').withTimeout(1000).cacheFor(5000),
]);
}
}
Line by line:
| Line or block | Purpose |
|---|---|
HealthCheckService | Runs one or more readiness indicators and builds a standard result. |
TypeOrmHealthIndicator | Checks the existing TypeORM data source with a small database query. |
@Controller('health') | Groups endpoints under a predictable path. |
GET /health/live | Returns success without depending on external services. |
GET /health/ready | Tests whether this instance can reach its required database. |
@HealthCheck() | Applies Terminus health-check response handling. |
withTimeout(1000) | Prevents a stalled dependency from hanging the probe indefinitely. |
cacheFor(5000) | Avoids issuing a new database query on every frequent probe. |
Adapt the dependency indicator to the database library in use; Terminus includes indicators for TypeORM, Prisma, Mongoose, Sequelize, MikroORM, HTTP, gRPC, and more. Its current API, timeout chaining, caching, and shutdown recommendation are documented in NestJS health checks.
Health endpoints are externally reachable HTTP endpoints on Cloud Run. Keep responses free of version strings, credentials, hostnames, raw dependency errors, and internal topology. Configure startup, liveness, and readiness probes deliberately: a liveness failure restarts an instance, while a readiness failure stops new traffic without terminating it. See Cloud Run health checks.
TypeScript stack traces otherwise point at compiled JavaScript. Generate source maps in the build and start Node with source-map support:
{
"compilerOptions": {
"sourceMap": true
}
}
CMD ["node", "--enable-source-maps", "dist/main.js"]
--enable-source-maps makes a best effort to translate stack positions back to TypeScript. It can add latency when Error.stack is accessed, so measure it if the application constructs stacks frequently. Deploy maps inside the protected runtime image or store them in a restricted artifact system paired with the exact image digest; do not publish source maps from a public static route. See Node's --enable-source-maps documentation.
Start with commands that do not change running state.
# Read recent application output with timestamps.
docker logs --since 30m --timestamps nest-api
# Take one CPU/memory/process-count sample instead of an endless stream.
docker stats --no-stream nest-api
# Inspect exit state, restart count, limits, and health configuration.
docker inspect nest-api
# Confirm the exact immutable image reference used by the container.
docker inspect --format '{{.Image}}' nest-api
docker logs, docker stats, and docker inspect are documented in the official Docker CLI references for logs, stats, and inspect.
Cloud Run is a managed platform: you cannot SSH into an instance or use docker exec against it. Use Cloud Logging, Cloud Monitoring, traces, revision metadata, and an isolated local run of the exact image instead. The Docker commands above apply only to a Docker host you control.
Set these placeholders in your own shell; do not paste credentials into them:
PROJECT_ID='your-project-id'
REGION='your-region'
SERVICE='your-service'
# Record current service configuration and traffic assignments.
gcloud run services describe "$SERVICE" \
--project "$PROJECT_ID" \
--region "$REGION"
# Compare revisions, creation times, and traffic.
gcloud run revisions list \
--service "$SERVICE" \
--project "$PROJECT_ID" \
--region "$REGION"
# Read recent error logs without modifying the service.
gcloud run services logs read "$SERVICE" \
--project "$PROJECT_ID" \
--region "$REGION" \
--freshness 1h \
--log-filter 'severity>=ERROR' \
--limit 100
The last command is the documented gcloud run services logs read interface.
Useful Logs Explorer queries:
# All errors for one service and revision.
resource.type="cloud_run_revision"
resource.labels.service_name="your-service"
resource.labels.revision_name="your-revision"
severity>=ERROR
# Follow one application request ID.
resource.type="cloud_run_revision"
jsonPayload.requestId="the-request-id"
# Find Cloud Run system messages, including memory-limit termination.
resource.type="cloud_run_revision"
resource.labels.service_name="your-service"
logName:"varlog/system"
Cloud Logging combines separate lines with AND, and supports comparisons such as severity>=ERROR; see the Logging query language.
request_failed and request_complete records.varlog/system for memory termination, probe failures, or startup errors.A response that never reaches the exception filter may indicate a process crash, platform timeout, OOM termination, or broken container connection rather than a normal controller exception. Cloud Run's troubleshooting guide lists these platform cases.
Look for:
pool size × active instancesThen verify that queries have timeouts, connections are released in finally blocks, the pool is bounded, and shutdown hooks close it. Cloud Run autoscaling can multiply database connections quickly; compare maximum instances and per-instance concurrency with the database connection budget. Do not “fix” pool exhaustion by making every instance's pool larger without checking that total.
Separate V8 heap from total resident memory (RSS). Buffers, native libraries, threads, and file-backed allocations may grow outside the JavaScript heap.
On Cloud Run, files written to the writable filesystem consume container memory, and exceeding the memory limit terminates the instance. That behavior is documented in Cloud Run troubleshooting.
Heap snapshot warning: creating a snapshot stops work on the main thread and can temporarily double heap usage, which may crash the process. Snapshots can also contain tokens, personal data, and application objects. Node recommends taking one only where that process can crash without harming availability; see Using Heap Snapshot. Never expose a heap-snapshot HTTP endpoint publicly.
High CPU with long latency often means synchronous work is blocking the Node.js event loop: large JSON parsing/serialization, expensive regular expressions, synchronous crypto/compression, huge loops, or excessive logging.
Node can measure event-loop delay with monitorEventLoopDelay():
import { monitorEventLoopDelay } from 'node:perf_hooks';
const eventLoopDelay = monitorEventLoopDelay({ resolution: 20 });
eventLoopDelay.enable();
setInterval(() => {
const p99Ms = eventLoopDelay.percentile(99) / 1_000_000;
console.log(JSON.stringify({ event: 'event_loop_delay', p99Ms }));
eventLoopDelay.reset();
}, 30_000).unref();
Line by line:
| Line | Purpose |
|---|---|
monitorEventLoopDelay | Uses Node's built-in event-loop delay histogram. |
resolution: 20 | Samples delay at a 20 ms resolution; lower values add more overhead. |
enable() | Begins sampling. |
setInterval(...) | Reports periodically rather than on every request. |
percentile(99) | Reads the p99 delay in nanoseconds. |
/ 1_000_000 | Converts nanoseconds to milliseconds. |
reset() | Starts a fresh measurement window. |
unref() | Prevents this timer alone from keeping Node alive during shutdown. |
The API and nanosecond units are defined in Node's perf_hooks documentation. Export this as a metric in a mature service instead of relying only on logs.
For a CPU profile, reproduce the issue locally or on an isolated canary:
node --cpu-prof --cpu-prof-dir=/tmp/profiles --enable-source-maps dist/main.js
Node writes the profile when the process exits. Profiling adds overhead and the profile can reveal code paths, so protect and delete it according to the incident-data policy. The options are documented in the Node.js CLI reference.
Check the final application lines and Cloud Run system logs. Preserve the exit status locally with docker inspect. Fix the missing await, rejected promise, or thrown callback at its source; do not add an empty .catch() merely to hide it.
Node diagnostic reports contain JavaScript/native stacks, heap information, libuv handles, resource usage, environment information, and other process details. Generate them only in a protected reproduction environment:
mkdir -p /tmp/nest-diagnostics
node \
--enable-source-maps \
--report-uncaught-exception \
--report-on-fatalerror \
--report-exclude-env \
--report-directory=/tmp/nest-diagnostics \
dist/main.js
Line by line:
| Line | Purpose |
|---|---|
mkdir -p ... | Creates a private destination in the disposable reproduction environment. |
--enable-source-maps | Maps JavaScript stacks back to TypeScript. |
--report-uncaught-exception | Writes a report when an uncaught exception terminates the process. |
--report-on-fatalerror | Writes a report for fatal runtime errors such as V8 OOM. |
--report-exclude-env | Omits environment variables that may contain secrets; verify support in the deployed Node version. |
--report-directory | Sends reports to a known restricted location. |
dist/main.js | Starts the compiled Nest entry point. |
Reports may still contain network addresses, paths, code details, and customer-related process state. The official Node diagnostic report documentation lists their contents and controls. A report written inside Cloud Run's ephemeral filesystem usually disappears with the instance and consumes memory while present, so build an approved secure export path before relying on it; otherwise reproduce with the exact image outside production.
Verify all of the following:
process.env.PORT0.0.0.0These are part of Cloud Run's container runtime contract and startup troubleshooting guidance.
A request ID correlates logs; a distributed trace shows where time was spent across API, database, queue, and downstream service boundaries. Preserve incoming W3C trace context when calling downstream services, and include the trace ID in logs.
For vendor-neutral tracing, OpenTelemetry's Node auto-instrumentation can create spans for supported HTTP and framework libraries. It must initialize before application modules are loaded. Start with the official OpenTelemetry JavaScript instrumentation guide and configure an approved exporter, sampling, and attribute-redaction policy. Do not attach request bodies, authorization data, raw SQL parameters, or unrestricted user identifiers to spans.
If a new revision is clearly responsible, rollback is mitigation—not the root-cause fix:
gcloud run services update-traffic "$SERVICE" \
--project "$PROJECT_ID" \
--region "$REGION" \
--to-revisions "KNOWN_GOOD_REVISION=100"
This command changes production traffic, so have an authorized operator confirm the service, region, revision, and incident plan first.
For a fix:
Cloud Run revisions are immutable and support no-traffic deployments, traffic splits, gradual migration, and rollback. See Rollbacks, gradual rollouts, and traffic migration.
Cloud Run sends SIGTERM before shutdown and provides a short graceful-shutdown window. app.enableShutdownHooks() lets Nest run its registered cleanup hooks; keep them bounded so the application can close connections and flush buffers before termination. See Nest's lifecycle events and Cloud Run's container shutdown contract.
Do not start production with --inspect=0.0.0.0:9229, publish port 9229, or add an unauthenticated “debug” route. The Node inspector can provide powerful process access. If live inspection is unavoidable:
The Node.js inspector documentation describes its profiling and heap APIs; their availability is not a reason to expose them publicly.
SIGTERM shutdown locally.| Removes DTO properties that have no validation decorator. |
forbidNonWhitelisted: true | Rejects unexpected properties instead of silently accepting them. |
transform: true | Converts incoming values to the DTO types Nest can infer. |
enableShutdownHooks() | Lets Nest run shutdown hooks after signals such as SIGTERM. |
PORT ?? 3000 | Uses the platform-provided port, with a local-development fallback. |
listen(..., '0.0.0.0') | Listens on every container interface; Cloud Run requires the ingress container to listen on 0.0.0.0, not only 127.0.0.1. |
uncaughtExceptionMonitor | Records an otherwise fatal error without replacing Node's default crash behavior. |
severity: 'CRITICAL' | Gives Cloud Logging a severity it can filter and alert on. |
errorName, stack, origin | Preserves diagnostic context. Restrict log access because stack traces may contain sensitive values. |
bootstrap().catch(...) | Records a minimal startup failure and gives the process a non-zero exit status instead of silently discarding a rejected startup promise. |
process.exitCode = 1 | Allows pending stderr output to flush while ensuring the failed startup is reported as a failure. |
x-request-id response header | Gives clients and support staff an ID they can report. |
next() | Continues to the next Nest/Express handler. |
request_complete |
| Creates a stable event name for queries and alerts. |
method, path, failedStatusCode ?? response.statusCode | Records useful request dimensions without a query string or body, and avoids incorrectly logging a thrown request as 200. |
durationMs | Measures total time inside the Nest request pipeline. |
| Conditional trace field | Correlates the record with Cloud Trace when the header was present. |
getPublicMessage(...) |
Extracts the intended message from string or object HttpException responses. |