{"slug": "i-told-an-ai-agent-to-stop-404-links-it-crashed-production-instead", "title": "I Told an AI Agent to Stop 404 Links. It Crashed Production Instead", "summary": "A developer building data-driven directory sites tasked an AI coding agent with suppressing internal links to empty pages, but the agent's LinkGuard component only matched URL patterns against the router instead of checking whether database records existed, so every link still rendered and Googlebot kept hitting 404s. A follow-up fix introduced a per-link database query that triggered a cold-start cache stampede and locked production at 100% CPU, prompting the developer to rework the approach as batch link resolution.", "body_md": "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.\n\nIt took twenty minutes. The agent submitted a clean pull request, passed fourteen unit tests, and deployed without errors.\n\nThree 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.\n\nHere 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.\n\nIf you build data-driven directories, you know the hub-and-spoke model.\n\nYou take a public dataset, say municipal sports facilities, and generate route hierarchies like `/region/{province}/{category}`.\n\nOn paper, the taxonomy makes complete sense. Every province can theoretically have entries in every category.\n\nIn reality, real-world data is lumpy.\n\nMadrid might have three hundred entries for swimming pools. A rural province like Soria might have zero.\n\nIf your template loops through categories and generates anchor tags for all fifty provinces, you produce hundreds of internal links pointing straight to empty pages.\n\nWhen 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.\n\nI 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.\n\nSounds like a straightforward task for an autonomous coding agent, right?\n\nI 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.\n\nTwenty minutes later, the pull request was ready.\n\nThe 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.\n\nEvery test passed:\n\n``` python\nclass LinkGuard:\n    def __init__(self, router):\n        self.router = router\n\n    def can_resolve(self, path: str) -> bool:\n        # Check if the path matches any registered application route\n        route_match = self.router.match(path)\n        return route_match is not None\n\n    def render(self, path: str, anchor_text: str) -> str:\n        if not self.can_resolve(path):\n            return f\"<span>{anchor_text}</span>\"\n        return f'<a href=\"{path}\">{anchor_text}</a>'\n```\n\nCan you spot the trap?\n\nThe 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.\n\nBecause `/region/{province}/{category}` was a valid route definition, the regex matched every single string passed to it.\n\n`/region/madrid/swimming` matched the pattern.\n\n`/region/soria/swimming` also matched the pattern.\n\nEven `/region/atlantis/spaceships` would match, because the router only checked URL syntax, not database rows.\n\nThe unit tests passed because the agent tested that valid URL patterns returned true and malformed paths like `///invalid??url` returned false.\n\nIn 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.\n\nThe code had shipped, passed review, and accomplished precisely nothing.\n\n*Notice the gap: the router matches URL syntax while the database has zero matching records, producing a silent false positive.*\n\nI pulled up the diff and left a blunt prompt for the agent:\n\n\"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.\"\n\nThe agent apologized immediately:\n\n\"You are completely right. I will update `can_resolve()` to query the underlying repository to confirm record counts.\"\n\nWithin thirty minutes, a second pull request arrived:\n\n``` python\nclass DatabaseLinkGuard:\n    def __init__(self, router, repository):\n        self.router = router\n        self.repo = repository\n\n    def can_resolve(self, path: str) -> bool:\n        route = self.router.match(path)\n        if not route:\n            return False\n\n        # Extract route parameters: e.g. {\"province\": \"soria\", \"cat\": \"swimming\"}\n        params = route.params\n        record_count = self.repo.count_by_filter(params)\n        return record_count > 0\n```\n\nThe agent updated tests with in-memory SQLite mocks. If a filter returned zero rows, `can_resolve()` returned false and omitted the `href`.\n\nI tested it locally against a small fixture. Populated categories had blue links; empty categories were plain text. The 404 links were gone.\n\nI merged the pull request, triggered deployment, and congratulated myself on delegating work to autonomous agents.\n\nThen I triggered a cache purge.\n\nHere is an architectural detail I forgot to specify in the agent prompt: how my page caching works.\n\nTo keep hosting costs low, my engine caches fully rendered HTML pages in Redis with versioned cache keys.\n\nWhenever 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.\n\nUnder 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.\n\nExcept now, every single page had our new `DatabaseLinkGuard` attached to it.\n\nA typical regional hub page contains around 120 internal links across navigation, province sidebars, category filters, and breadcrumbs.\n\nWith 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.\n\nNow, what happens when you deploy a version bump to production?\n\nGooglebot, 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:\n\n```\n50 concurrent requests * 120 queries per page = 6,000 database queries\n```\n\nSix thousand queries flooded the database connection pool in less than three seconds.\n\nThe connection pool dried up instantly. Latency skyrocketed from 2ms to 4,500ms.\n\nWeb 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.\n\nMy server was pinned at 100% CPU usage across all cores.\n\nI 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.\n\nThe link guard had solved the 404 problem by taking down the entire website.\n\n*The query storm in action: 120 sequential queries per template multiplied by concurrent cache misses quickly exhausts the connection pool.*\n\nOnce my pulse returned to normal, I sat down to understand why the agent had produced such an operational disaster.\n\nIt was not because the model was dumb. It was because the model solved the problem imperatively from the perspective of a single link.\n\nWhen 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.\n\nTo 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.\n\n``` python\nclass BatchLinkResolver:\n    def __init__(self, repo):\n        self.repo = repo\n        self._candidates = set()\n        self._valid_paths = set()\n\n    def register(self, path: str, route_params: dict):\n        \"\"\"Phase 1: Collect candidate paths before rendering.\"\"\"\n        self._candidates.add((path, tuple(sorted(route_params.items()))))\n\n    def resolve_all(self):\n        \"\"\"Phase 2: Verify all candidates in a single batch query.\"\"\"\n        if not self._candidates:\n            return\n\n        # Query all distinct parameter combinations in one database roundtrip\n        active_combinations = self.repo.get_active_combinations(\n            [dict(params) for _, params in self._candidates]\n        )\n\n        for path, params in self._candidates:\n            if dict(params) in active_combinations:\n                self._valid_paths.add(path)\n\n    def is_valid(self, path: str) -> bool:\n        \"\"\"Phase 3: O(1) in-memory check during HTML generation.\"\"\"\n        return path in self._valid_paths\n```\n\nInstead of querying the database 120 times inside the template loop, the controller collects all link candidates upfront.\n\nIt executes a single SQL query using an `IN (...)` or `EXISTS` clause that returns all valid combinations in one roundtrip.\n\nWhen the template renders HTML, `is_valid()` performs a simple hash set lookup in memory.\n\nZero database queries during template rendering. One database query per page on a cold cache miss.\n\nPage render time dropped from an unusable 1,800ms during the crash down to 22ms.\n\n*The batch architecture: candidate links are collected upfront, resolved in a single batch query, and checked in memory during template rendering.*\n\nThis incident taught me a big lesson about building software with AI coding agents.\n\nAgents 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.\n\nWhere agents fail catastrophically is operational topology:\n\nWhen 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.\n\nNow, I explicitly specify the operational constraints upfront:\n\nIf you do not specify the lifecycle, the agent will pick the most straightforward local path.\n\nAnd in production, the most straightforward local path is usually the one that brings down your server.\n\nHave you ever had a clean, unit-tested feature cause an immediate cache stampede or connection pool blowout in production?\n\nIf you run programmatic SEO sites or large directories, how do you handle internal link validation?\n\nDo 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?", "url": "https://wpnews.pro/news/i-told-an-ai-agent-to-stop-404-links-it-crashed-production-instead", "canonical_source": "https://dev.to/galadev/i-told-an-ai-agent-to-stop-404-links-it-crashed-production-instead-4n5j", "published_at": "2026-11-26 20:38:35+00:00", "updated_at": "2026-11-26 20:44:51.013548+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "developer-tools", "generative-engine-optimization", "ai-search"], "entities": ["Googlebot"], "also_reported_by": [], "takeaway": "An agent's route-pattern check passed 14 unit tests but never verified database rows, so links to empty pages kept rendering; the naive per-link query fix then caused a cache stampede, showing link validation must be batched.", "recommendation": {"advice": "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.", "playbook": "coding-agents", "playbook_url": "https://wpnews.pro/playbooks/coding-agents"}, "alternates": {"html": "https://wpnews.pro/news/i-told-an-ai-agent-to-stop-404-links-it-crashed-production-instead", "markdown": "https://wpnews.pro/news/i-told-an-ai-agent-to-stop-404-links-it-crashed-production-instead.md", "text": "https://wpnews.pro/news/i-told-an-ai-agent-to-stop-404-links-it-crashed-production-instead.txt", "jsonld": "https://wpnews.pro/news/i-told-an-ai-agent-to-stop-404-links-it-crashed-production-instead.jsonld"}}