# I Told an AI Agent to Stop 404 Links. It Crashed Production Instead

> Source: <https://dev.to/galadev/i-told-an-ai-agent-to-stop-404-links-it-crashed-production-instead-4n5j>
> Published: 2026-11-26 20:38:35+00:00

**Recommendation:** When an agent writes a validation check, verify it tests the real data condition, not just URL syntax, and batch database lookups rather than querying per link.
More in the playbook "Working with AI coding agents": <https://wpnews.pro/playbooks/coding-agents>

I asked an AI coding agent to fix a classic programmatic SEO problem on my directory sites: stop rendering internal links to pages that 404.

It took twenty minutes. The agent submitted a clean pull request, passed fourteen unit tests, and deployed without errors.

Three days later, Googlebot reported the exact same 404 spikes. When I asked the agent to fix the check, it introduced a per-link database query that triggered a cold-start cache stampede and brought my production server to a 100% CPU lockup.

Here is what went wrong, why unit tests gave me false confidence, and how I finally got batch link resolution to work without melting my database.

If you build data-driven directories, you know the hub-and-spoke model.

You take a public dataset, say municipal sports facilities, and generate route hierarchies like `/region/{province}/{category}`.

On paper, the taxonomy makes complete sense. Every province can theoretically have entries in every category.

In reality, real-world data is lumpy.

Madrid might have three hundred entries for swimming pools. A rural province like Soria might have zero.

If your template loops through categories and generates anchor tags for all fifty provinces, you produce hundreds of internal links pointing straight to empty pages.

When search crawlers follow those links, they hit 404s and burn your crawl budget on dead ends. Worse, visitors click promising links only to find blank screens.

I wanted a simple `LinkGuard` component: if the target page has active records, render `<a href="...">Category</a>`. If it has no records, render plain text without an anchor tag.

Sounds like a straightforward task for an autonomous coding agent, right?

I gave the coding agent a clear brief: inspect incoming URLs in the template renderer, verify whether the target route is valid, and suppress the link tag if the destination does not exist.

Twenty minutes later, the pull request was ready.

The agent had written a dedicated `LinkGuard` class, integrated it into the template pipeline, and added unit tests covering relative paths, query strings, and trailing slashes.

Every test passed:

``` python
class LinkGuard:
    def __init__(self, router):
        self.router = router

    def can_resolve(self, path: str) -> bool:
        # Check if the path matches any registered application route
        route_match = self.router.match(path)
        return route_match is not None

    def render(self, path: str, anchor_text: str) -> str:
        if not self.can_resolve(path):
            return f"<span>{anchor_text}</span>"
        return f'<a href="{path}">{anchor_text}</a>'
```

Can you spot the trap?

The agent wrote a method called `can_resolve()`, but it never checked whether the page actually existed. It only checked whether the URL matched a registered route pattern in the routing table.

Because `/region/{province}/{category}` was a valid route definition, the regex matched every single string passed to it.

`/region/madrid/swimming` matched the pattern.

`/region/soria/swimming` also matched the pattern.

Even `/region/atlantis/spaceships` would match, because the router only checked URL syntax, not database rows.

The unit tests passed because the agent tested that valid URL patterns returned true and malformed paths like `///invalid??url` returned false.

In CI, everything was green. In production, Googlebot kept crawling hundreds of empty 404 URLs, because the template continued rendering every single link exactly as before.

The code had shipped, passed review, and accomplished precisely nothing.

*Notice the gap: the router matches URL syntax while the database has zero matching records, producing a silent false positive.*

I pulled up the diff and left a blunt prompt for the agent:

"Matching a route pattern in the router does not mean the row exists in the database. You need to check if the target collection actually contains records before claiming the link resolves."

The agent apologized immediately:

"You are completely right. I will update `can_resolve()` to query the underlying repository to confirm record counts."

Within thirty minutes, a second pull request arrived:

``` python
class DatabaseLinkGuard:
    def __init__(self, router, repository):
        self.router = router
        self.repo = repository

    def can_resolve(self, path: str) -> bool:
        route = self.router.match(path)
        if not route:
            return False

        # Extract route parameters: e.g. {"province": "soria", "cat": "swimming"}
        params = route.params
        record_count = self.repo.count_by_filter(params)
        return record_count > 0
```

The agent updated tests with in-memory SQLite mocks. If a filter returned zero rows, `can_resolve()` returned false and omitted the `href`.

I tested it locally against a small fixture. Populated categories had blue links; empty categories were plain text. The 404 links were gone.

I merged the pull request, triggered deployment, and congratulated myself on delegating work to autonomous agents.

Then I triggered a cache purge.

Here is an architectural detail I forgot to specify in the agent prompt: how my page caching works.

To keep hosting costs low, my engine caches fully rendered HTML pages in Redis with versioned cache keys.

Whenever I deploy a new template or engine release, the cache key version bumps from `v12` to `v13`, invalidating stale HTML across the entire domain simultaneously.

Under normal conditions, this is harmless. When a page gets requested for the first time after a deploy, the server spends 40 milliseconds rendering HTML, stores it in Redis, and serves subsequent hits in 6 milliseconds.

Except now, every single page had our new `DatabaseLinkGuard` attached to it.

A typical regional hub page contains around 120 internal links across navigation, province sidebars, category filters, and breadcrumbs.

With the agent's new code, rendering that page no longer took one database query. It took 121 queries: 1 query for page content, plus 120 individual `SELECT COUNT(*)` queries executed sequentially inside the template loop.

Now, what happens when you deploy a version bump to production?

Googlebot, uptime monitors, and real visitors arrive at the exact same moment. Fifty concurrent requests hit cold cache misses simultaneously. Each request spawned 120 sequential database queries:

```
50 concurrent requests * 120 queries per page = 6,000 database queries
```

Six thousand queries flooded the database connection pool in less than three seconds.

The connection pool dried up instantly. Latency skyrocketed from 2ms to 4,500ms.

Web workers piled up in the process table waiting for connections. Memory climbed until Linux started killing processes. Nginx began spitting `504 Gateway Timeout` errors to every visitor.

My server was pinned at 100% CPU usage across all cores.

I did not have time to debug. I ran `git revert`, forced a redeploy of the previous commit, killed stuck workers, and watched the server load collapse back to near zero.

The link guard had solved the 404 problem by taking down the entire website.

*The query storm in action: 120 sequential queries per template multiplied by concurrent cache misses quickly exhausts the connection pool.*

Once my pulse returned to normal, I sat down to understand why the agent had produced such an operational disaster.

It was not because the model was dumb. It was because the model solved the problem imperatively from the perspective of a single link.

When you ask an agent to implement a helper like `render_link(path, text)`, the agent focuses strictly on that individual function call. It does not see the loop wrapping it, concurrent web requests, or cache stampedes.

To make link verification viable in production, you cannot resolve links one by one during template execution. You have to separate link resolution into two distinct lifecycle phases: collection and batch verification.

``` python
class BatchLinkResolver:
    def __init__(self, repo):
        self.repo = repo
        self._candidates = set()
        self._valid_paths = set()

    def register(self, path: str, route_params: dict):
        """Phase 1: Collect candidate paths before rendering."""
        self._candidates.add((path, tuple(sorted(route_params.items()))))

    def resolve_all(self):
        """Phase 2: Verify all candidates in a single batch query."""
        if not self._candidates:
            return

        # Query all distinct parameter combinations in one database roundtrip
        active_combinations = self.repo.get_active_combinations(
            [dict(params) for _, params in self._candidates]
        )

        for path, params in self._candidates:
            if dict(params) in active_combinations:
                self._valid_paths.add(path)

    def is_valid(self, path: str) -> bool:
        """Phase 3: O(1) in-memory check during HTML generation."""
        return path in self._valid_paths
```

Instead of querying the database 120 times inside the template loop, the controller collects all link candidates upfront.

It executes a single SQL query using an `IN (...)` or `EXISTS` clause that returns all valid combinations in one roundtrip.

When the template renders HTML, `is_valid()` performs a simple hash set lookup in memory.

Zero database queries during template rendering. One database query per page on a cold cache miss.

Page render time dropped from an unusable 1,800ms during the crash down to 22ms.

*The batch architecture: candidate links are collected upfront, resolved in a single batch query, and checked in memory during template rendering.*

This incident taught me a big lesson about building software with AI coding agents.

Agents are phenomenal at unit-level algorithms. If you ask for a parsing function, a regex matcher, or a data conversion script, an agent will produce clean, idiomatic code in seconds.

Where agents fail catastrophically is operational topology:

When I run autonomous agents to help build features across my indie projects, like my [public tenders explorer](https://licitacionesalerta.es/?utm_source=devto&utm_medium=article&utm_campaign=ai-agent-404-link-guard&utm_content=outro), I no longer ask them for isolated helpers.

Now, I explicitly specify the operational constraints upfront:

If you do not specify the lifecycle, the agent will pick the most straightforward local path.

And in production, the most straightforward local path is usually the one that brings down your server.

Have you ever had a clean, unit-tested feature cause an immediate cache stampede or connection pool blowout in production?

If you run programmatic SEO sites or large directories, how do you handle internal link validation?

Do you precompute a static lookup map of valid URLs at build time, do you resolve links dynamically in batches, or do you let Googlebot hit the 404s and clean them up after the fact?
