Originally published on tamiz.pro.
I let an AI agent auto-approve its own infrastructure changes. It was a mistake — not because the code was wrong, but because the context was. The agent shipped a Node.js service with a graceful shutdown handler that looked perfect in a pull request and broke in production in ways that no code review would have caught. This article is about that failure, and the broader lesson it reveals about the hidden costs of 'auto-approve' DevOps.
Table of Contents
- 1. The Setup: What 'Auto-Approve' Actually Means
- 2. The Breaking Change: Graceful Shutdown in Node.js
- 3. The Environment Setup Debt Nobody Talks About
- 4. The Post-Code Bugs You Can't Read Your Way Out Of
- 5. What the Agent Got Right (And Why It Didn't Matter)
- 6. A Practical Checklist for AI-Assisted Infrastructure
- 7. Frequently Asked Questions
1. The Setup: What 'Auto-Approve' Actually Means
When I say "auto-approve," I don't mean the agent had write access to production. I mean I configured my CI pipeline to accept the agent's pull requests automatically if they passed tests and type checks. The agent was generating infrastructure-as-code — Terraform, Dockerfiles, Kubernetes manifests, and a Node.js service that would act as a sidecar for health checks and metrics.
The appeal was obvious. The agent could write the boilerplate, wire up the deployment, and iterate faster than I could. The risk was equally obvious: an AI agent doesn't understand your environment. It understands the patterns it was trained on, and those patterns are generic by design.
Here's what the agent produced for the Node.js service's entry point:
// src/index.ts
import { createServer } from 'http';
import { metrics } from './metrics';
import { logger } from './logger';
const server = createServer((req, res) => {
if (req.url === '/health') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'ok' }));
return;
}
res.writeHead(404);
res.end();
});
const port = process.env.PORT || 8080;
server.listen(port, () => {
logger.info(`Server listening on port ${port}`);
});
process.on('SIGTERM', () => {
logger.info('SIGTERM received, shutting down gracefully...');
server.close(() => {
logger.info('Server closed.');
process.exit(0);
});
});
This looks fine. It handles SIGTERM, closes the server, and exits. But it's a trap, and the trap only becomes visible when you understand how Kubernetes actually kills pods.
2. The Breaking Change: Graceful Shutdown in Node.js
2.1 The Kubernetes Termination Sequence
When Kubernetes wants to terminate a pod, it doesn't just kill it. It follows a specific sequence:
- The pod's status changes to
Terminating. - The endpoint controller removes the pod from any Service endpoints (so new traffic stops).
- Kubernetes sends a
SIGTERMto the container's PID 1. - Kubernetes waits for the
terminationGracePeriodSeconds(default 30 seconds). - If the container hasn't exited, Kubernetes sends
SIGKILL.
Here's the problem with the agent's code: it only handles SIGTERM. That's correct. But the real issue is what happens inside that handler.
2.2 The In-Memory State Problem
The agent's service had no in-memory state. It was a health check sidecar. But the agent also generated a metrics collector that aggregated request counts in memory. The graceful shutdown handler closed the HTTP server, but it didn't flush the metrics. When the process exited, the last few seconds of metrics were lost.
In a sidecar, this is cosmetic. But the same pattern applied to the main application service the agent generated, which had a database connection pool. The agent's shutdown handler looked like this:
process.on('SIGTERM', () => {
logger.info('SIGTERM received, shutting down gracefully...');
server.close(() => {
logger.info('Server closed.');
process.exit(0);
});
});
What's missing? The database pool was never closed. The agent didn't know the pool existed because it was generated in a separate file, and the agent's context window didn't include the full dependency graph. The pool was left open, keeping the event loop alive, so server.close() fired but process.exit(0) was never reached because the open database connection kept the process alive.
2.3 The Event Loop Trap
Here's the subtle bug: Node.js won't exit while there are active handles. An open database connection is an active handle. So the process hangs until Kubernetes sends SIGKILL after 30 seconds. The pod gets killed forcefully, and any in-flight requests are dropped.
The fix is to track all resources and close them in order:
// src/index.ts (fixed)
import { createServer } from 'http';
import { metrics } from './metrics';
import { logger } from './logger';
import { db } from './db';
const server = createServer((req, res) => {
if (req.url === '/health') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'ok' }));
return;
}
res.writeHead(404);
res.end();
});
const port = process.env.PORT || 8080;
server.listen(port, () => {
logger.info(`Server listening on port ${port}`);
});
async function shutdown(signal: string) {
logger.info(`${signal} received, shutting down gracefully...`);
// 1. Stop accepting new connections
await new Promise<void>((resolve) => {
server.close(() => resolve());
});
// 2. Close database connections
await db.end();
// 3. Flush metrics
await metrics.flush();
// 4. Exit
process.exit(0);
}
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
// Safety timeout: force exit after 25 seconds
setTimeout(() => {
logger.error('Forced shutdown after timeout');
process.exit(1);
}, 25000).unref();
This is a fix, but it's a fix I had to write manually. The agent didn't generate it because the agent couldn't see the database module's lifecycle. It was writing code in isolation, and isolation is the enemy of graceful shutdown.
2.4 Why Code Review Can't Catch This
This is the core insight: you cannot read your way out of this bug. The code looks correct. It compiles. It passes type checks. The tests pass. But the behavior depends on the runtime environment, the resource lifecycle, and the orchestration layer's semantics.
When you review a pull request, you're looking at the code. You're not looking at the Kubernetes deployment, the database connection pool's behavior, or the metrics flush interval. The bug lives in the intersection of those systems, not in any single file.
3. The Environment Setup Debt Nobody Talks About
The second hidden cost was environment setup debt. The agent generated a .env.example file, but it didn't know which environment variables were actually required at runtime. It guessed based on common patterns.
3.1 The .env.example Problem
Here's what the agent generated:
# .env.example
PORT=8080
DATABASE_URL=postgres://user:password@localhost:5432/mydb
REDIS_URL=redis://localhost:6379
LOG_LEVEL=info
This looks reasonable. But the actual application required DATABASE_POOL_SIZE, METRICS_INTERVAL, and SHUTDOWN_TIMEOUT. The agent didn't include them because they weren't in the code it generated — they were in the infrastructure configuration, which the agent never saw.
When the service deployed, it silently fell back to defaults. The database pool size defaulted to 10, but the production database could only handle 5 concurrent connections. The metrics interval defaulted to 60 seconds, but the monitoring system expected 15-second granularity.
3.2 The Silent Default Trap
Node.js doesn't throw an error when an environment variable is missing. It returns undefined. If the code uses process.env.DATABASE_POOL_SIZE || 10, it silently uses 10. The application starts, the database connections pool to 10, and the database starts rejecting connections. The health check still returns 200 because the service is "alive" — it's just degraded.
// The agent's generated code
const poolSize = parseInt(process.env.DATABASE_POOL_SIZE || '10', 10);
This is a bug that only manifests under load. The agent's code was fine in a test environment with 2 connections. In production with 50 concurrent requests, it broke.
3.3 The Fix: Fail Fast on Missing Env
The fix is to validate environment variables at startup and fail fast if required ones are missing:
// src/config.ts
function requiredEnv(name: string): string {
const value = process.env[name];
if (!value) {
throw new Error(`Missing required environment variable: ${name}`);
}
return value;
}
export const config = {
port: parseInt(requiredEnv('PORT'), 10),
databaseUrl: requiredEnv('DATABASE_URL'),
databasePoolSize: parseInt(requiredEnv('DATABASE_POOL_SIZE'), 10),
metricsInterval: parseInt(requiredEnv('METRICS_INTERVAL'), 10),
shutdownTimeout: parseInt(requiredEnv('SHUTDOWN_TIMEOUT'), 10),
};
This is a pattern the agent didn't generate because it doesn't appear in most training data. Most examples use process.env.X || default, which is fine for local development but dangerous for production infrastructure.
4. The Post-Code Bugs You Can't Read Your Way Out Of
The third category of hidden cost is the most insidious: bugs that exist after the code is deployed and running. These aren't syntax errors or type errors. They're behavioral errors that only appear when the system interacts with its environment.
4.1 The DNS Resolution Bug
The agent's service made outbound HTTP calls to an internal API. The URL was hardcoded as http://internal-api:8080. In Kubernetes, this works because services are resolved by name. But the agent didn't account for the fact that DNS resolution can fail transiently during a rolling update.
When a pod restarts, the DNS entry for internal-api might not be ready yet. The service tries to resolve the hostname, gets ENOTFOUND, and crashes. The agent's code didn't have retry logic:
// The agent's generated code
const response = await fetch('http://internal-api:8080/data');
No retry. No exponential backoff. No circuit breaker. Just a single attempt that fails and crashes the process.
4.2 The Race Condition in Health Checks
The agent generated a health check endpoint that checked database connectivity:
app.get('/health', async (req, res) => {
try {
await db.query('SELECT 1');
res.status(200).json({ status: 'ok' });
} catch (err) {
res.status(503).json({ status: 'unhealthy' });
}
});
This looks correct. But here's the race: Kubernetes runs readiness probes every 10 seconds. If the database is temporarily unavailable, the health check returns 503. Kubernetes marks the pod as unready and removes it from the load balancer. But the pod is still running. When the database recovers, the next health check returns 200, and the pod is re-added.
This is fine. But the agent's code didn't account for the fact that Kubernetes also runs liveness probes. If the liveness probe is the same as the readiness probe, a database outage will cause Kubernetes to restart the pod. The pod is killed, the database connection is dropped, and the database connection pool is not cleaned up. The restart loop begins.
4.3 The Missing Context Propagation
The most subtle bug was missing context propagation. The agent's code used fetch() without passing the AbortSignal from the incoming request. When a client disconnects, the Node.js server fires req.on('close'), but the agent's outbound HTTP call continues. This leaks resources and causes the process to hang during shutdown because there are in-flight requests that never complete.
// The agent's generated code
app.get('/data', async (req, res) => {
const response = await fetch('http://internal-api:8080/data');
const data = await response.json();
res.json(data);
});
The fix is to pass the signal:
app.get('/data', async (req, res) => {
const controller = new AbortController();
req.on('close', () => controller.abort());
try {
const response = await fetch('http://internal-api:8080/data', {
signal: controller.signal,
});
const data = await response.json();
res.json(data);
} catch (err) {
if (err.name === 'AbortError') {
return; // Client disconnected, no need to respond
}
res.status(500).json({ error: 'Internal server error' });
}
});
This is a bug that no code review would catch because it requires understanding the HTTP lifecycle, the client's behavior, and the server's event loop. The agent didn't generate it because it wasn't in its training data.
5. What the Agent Got Right (And Why It Didn't Matter)
The agent got a lot right. The code was clean, idiomatic, and well-typed. It used proper error handling in most places. It generated good tests. The Terraform was valid and followed best practices.
But none of that mattered. The agent's code was correct in isolation. The failures happened at the boundaries: the process lifecycle, the environment configuration, the network layer, and the orchestration system.
5.1 The Boundary Problem
AI agents excel at generating code that's correct within a well-defined context. They struggle when the context spans multiple systems. The agent didn't know:
- How Kubernetes terminates pods
- How the database connection pool behaves under load
- How DNS resolution works during rolling updates
- How environment variables are injected in production
These aren't code problems. They're systems problems. The agent's training data includes code examples, but it doesn't include the operational knowledge that a senior engineer accumulates over years of running services in production.
5.2 The Verification Gap
The agent's code passed all automated checks. But automated checks only verify what they're designed to verify. They don't verify:
- Graceful shutdown under load
- Resource cleanup on SIGTERM
- Environment variable validation
- DNS resolution retry behavior
- Client disconnection handling
These require integration tests, load tests, and chaos engineering. The agent didn't write those because it didn't know they were needed.
6. A Practical Checklist for AI-Assisted Infrastructure
If you're going to let an AI agent ship infrastructure code, here's the checklist I wish I had before I started:
6.1 Graceful Shutdown
- [ ] Track all active resources (servers, pools, clients) in a registry
- [ ] Implement a shutdown function that closes resources in reverse order of creation
- [ ] Set a safety timeout that forces exit after N seconds
- [ ] Handle both SIGTERM and SIGINT
- [ ] Flush any in-memory state (metrics, logs, buffers) before exit
6.2 Environment Configuration
- [ ] Validate all required environment variables at startup
- [ ] Fail fast if a required variable is missing
- [ ] Use a config module that centralizes all environment access
- [ ] Document all environment variables in a README or schema
- [ ] Never use
process.env.X || defaultfor production-critical settings
6.3 Network Resilience
- [ ] Implement retry logic with exponential backoff for outbound calls
- [ ] Use AbortController to propagate client disconnections
- [ ] Set timeouts on all HTTP requests
- [ ] Implement circuit breakers for downstream dependencies
- [ ] Handle DNS resolution failures gracefully
6.4 Kubernetes Integration
- [ ] Separate readiness and liveness probes
- [ ] Ensure readiness probe checks dependencies, liveness probe checks process health
- [ ] Set
terminationGracePeriodSecondshigher than your shutdown timeout - [ ] Use
preStophooks to drain traffic before SIGTERM - [ ] Test pod termination under load
6.5 Verification
- [ ] Write integration tests that simulate SIGTERM
- [ ] Write load tests that verify graceful shutdown under traffic
- [ ] Use chaos engineering to test network failures
- [ ] Run the service in a staging environment that mirrors production
- [ ] Review the generated code with a human who understands the operational context
7. Frequently Asked Questions
Q: Why didn't the AI agent catch these issues?
A: Because the issues are not in the code — they're in the interaction between the code and its environment. The agent generates code in isolation, using patterns from training data. It doesn't have the operational context of a production Kubernetes cluster, a database under load, or a network with transient failures.
Q: Is AI-assisted infrastructure ever safe?
A: Yes, but only with human oversight. The agent is excellent at generating boilerplate, wiring up standard patterns, and producing clean code. It's terrible at understanding system boundaries. You need a human who understands the operational context to review the code and write the integration tests.
Q: What's the biggest lesson from this experience?
A: Code review is not enough. You need system review — testing the code in the environment it will run in, under the conditions it will face. An AI agent can write code that passes all automated checks and still fails in production because the checks don't cover the runtime environment.
This experience taught me that AI agents are powerful tools, but they're not replacements for operational knowledge. If you're exploring AI-assisted DevOps, check out Tamiz's Insights for more on the intersection of AI and infrastructure engineering.
Top comments (0)