A web crawler in Java is four cooperating systems wrapped around one loop: a frontier that decides what to fetch next, a fetcher that performs HTTP requests under strict limits, a parser that pulls new URLs and content from responses, and a store that persists both pages and crawl state so a restart doesn't lose work. The design succeeds or fails on the parts that aren't the happy path — deduplication, politeness per host, robots.txt handling, redirect chains, and bounded queues. Java is a good fit because the standard library, virtual threads in recent JDKs, and mature HTTP and HTML libraries let you build all four without heavy infrastructure. The hard decisions are about scope and discipline, not cleverness.
Below is an ordered design path, from fixing boundaries to recovering from crashes, plus the failure modes that bite real crawlers.
Start by writing the crawl's contract before any code
Most broken crawlers are broken by scope, not by bugs. Before you open an IDE, write down five things:
1: Seed set — the exact URLs you start from. 2: Acceptance rule — a predicate over (URL, host, path, content type) that says "this is in scope." Example: same registered domain as the seed, HTML only, no query strings with session IDs. 3: Depth or budget cap — maximum link distance from seeds, maximum pages, or maximum bytes. Pick one primary budget; you can layer a secondary cap later. 4: Politeness constants — minimum delay between requests to one host, maximum concurrent connections per host, a User-Agent string that identifies you and a contact URL. 5: Output schema — what you store per page (final URL, status, headers you care about, fetch timestamp, body or extracted text, links found) and what you store per host (last fetch time, robots rules, crawl-delay).
Write these as constants or a small config class. The crawler code then reads like an enforcement mechanism for the contract, which makes the rest of the design far easier to reason about. If the acceptance rule is ambiguous — say, "crawl the site" — you'll discover at 2 a.m. that you've wandered into a calendar with infinite next-month links.
Sketch the core components and their responsibilities
A workable Java decomposition:
Frontier: a thread-safe queue of pending URLs, deduplicated, partitioned or keyed by host. It owns scheduling order and the per-host delay bookkeeping. Seen set: a deduplication structure mapping a normalized URL key to a state (queued, fetched, failed, skipped). In-memory for small crawls, disk-backed for large ones. Fetcher: an HTTP client wrapper that enforces timeouts, size caps, redirect limits, and per-host concurrency, and returns either a response or a typed failure. Robots cache: fetches and caches /robots.txt per host and answers "may I fetch this path, and how long should I wait." Parser/extractor: turns an HTML body into outbound links, canonical URL hints, and whatever content you actually want, without following anything itself. Store: persists pages and frontier state; also the place to record errors for later inspection. Coordinator: the loop that pulls a URL, checks politeness, fetches, parses, enqueues new URLs, marks the old one done, and decides when to stop.
Keep the parser free of network calls. It should be a pure function from bytes plus base URL to a list of candidate links and extracted fields. That separation makes it testable against saved HTML files, which is where most of your correctness work will happen.
Normalize and deduplicate URLs correctly
Deduplication is the single most valuable design decision, because a crawler that fetches the same content under five URLs wastes its entire budget. Normalize before hashing:
Lowercase the scheme and host; strip the default port (:80 for http, :443 for https). Remove the fragment (#section) — it never reaches the server. Resolve relative references against the document's base URL (respect a tag if present). Remove known-session and tracking parameters only if you have a curated list. Do not strip all query parameters: ?id=42 is often a distinct page. Normalize path dot-segments and collapse duplicate slashes. Decide explicitly whether a trailing slash is significant on your target sites. On many static sites /about and /about/ return the same content; on others they don't.
The standard java.net.URI class handles scheme, host, port, and relative resolution reasonably; URI.normalize() handles dot-segments. Note that java.net.URL is weaker for this — its equals can trigger DNS resolution, so never use URLs as hash keys. Use normalized URI or a plain string key.
A subtle trap: normalization must be deterministic. If you normalize differently in the frontier than in the seen-set, you'll enqueue duplicates. Put one normalize(URI, URI base) method in one class and call it from everywhere.
For scale, the seen-set can be a ConcurrentHashMap<String, Byte> of URL keys (a few tens of bytes per entry, so ten million URLs is on the order of hundreds of megabytes — measure before committing). Beyond that, move to an embedded key-value store; the access pattern is simple point lookups and inserts, which such stores handle well.
Handle robots.txt and crawl-delay before you fetch a page
Robots handling belongs before the fetcher in the pipeline, not inside the parser. The flow per URL:
1: Look up the host in the robots cache. 2: On a miss, fetch once, parse it, cache the result with a timestamp. 3: Evaluate the URL path against the rules for your User-Agent token, falling back to the * group. 4: Apply the group's Crawl-delay if present; otherwise use your configured default delay.
Parsing details that matter: rules are grouped by User-agent lines, and Allow and Disallow match as path prefixes with * wildcards and $ end-anchors allowed by the widely followed convention. When an Allow and a Disallow both match, the longer pattern wins; on a tie, Allow wins. An empty Disallow: means everything is permitted. Fetch robots over the same scheme and host as the target; if the robots fetch fails with a 5xx, the cautious choice is to treat the host as temporarily disallowed, while a 404 conventionally means "no restrictions." Those are conventions, not a law — document your choice.
The robots file is a request, not an authorization. Many sites don't publish one and still expect polite behavior, and robots rules don't tell you about rate limits. Your own delay and concurrency caps must be the binding constraint.
Build the fetcher with limits, not just an HTTP call
The fetcher's job is to convert the unbounded, misbehaving web into a bounded, typed result. Every limit below is load-bearing:
Connect and read timeouts. Without a read timeout, one hung connection stalls a worker indefinitely. A few seconds to connect and ten to thirty seconds to read is a common starting range; adjust per site. Redirect limit. Follow at most, say, five redirects, and record the final URL as the canonical target. Treat redirect loops and chains beyond the limit as failures. Decide whether redirected responses re-enter the seen-set as new URLs; they should, so you don't refetch them later. Response size cap. Abort bodies over a threshold (a few megabytes for HTML is generous), and skip non-HTML content types early via the Content-Type header rather than downloading first. Compression and charset. Most servers gzip; Java's HTTP clients handle this when you ask for it. Decode using the charset from the Content-Type header, then the document's , then a sane default — guessing wrong turns every non-ASCII character into garbage in your extracted text. Per-host concurrency. Cap simultaneous connections to any one host (often one or two). Global concurrency is a separate, larger number.
java.net.http.HttpClient (Java 11+) is a reasonable base: it supports asynchronous requests, timeouts, redirect policy, and HTTP/2. Set followRedirects(NEVER) if you want to implement the redirect limit and canonicalization yourself, which you usually do. Headers to send: a descriptive User-Agent, Accept: text/html,..., and Accept-Encoding. Do not send cookies by default; a cookie jar per host quietly turns your crawler into a stateful session browser.
A fetch result should be a sealed-type hierarchy in modern Java: Success(status, finalUri, headers, body), HttpError(status, finalUri), TooLarge(finalUri), Timeout(uri), NetworkFailure(uri, cause). The coordinator switches on the type; the fetcher never throws for expected failures.
Implement politeness as per-host scheduling, not a global sleep
The naive politeness implementation is Thread.sleep(delay) after each request. It works for a single-threaded crawler and collapses with concurrency: ten workers sleeping on the same host's delay still hit that host in bursts, and workers idle on slow hosts waste capacity.
The correct structure is per-host state: last-request timestamp, in-flight count, and a next-allowed time. A URL is eligible only if its host has no requests in flight (or is under its concurrency cap) and the current time is past the next-allowed time. After each request, update the host's timestamp and next-allowed time.
Implementation choices in Java:
Single scheduler thread with a priority queue keyed by next-allowed time. Simple to reason about, trivially correct, and fast enough for crawls in the tens of requests per second. When the top item isn't eligible yet, the scheduler sleeps until it is or until a new URL arrives. One worker per host (a small executor keyed by host), each pulling from that host's queue with a delay between requests. This scales per-host concurrency naturally but complicates global task accounting. Virtual threads (Java 21+) simplify blocking code enormously: you can write straightforward Thread.sleep-style per-host delays and still hold thousands of logical crawlers. You still need shared per-host state to enforce the cap across threads; virtual threads remove the thread-per-request cost, not the need for coordination.
The scheduler design also gives you backpressure. When the frontier is empty, workers should block on a queue rather than spin; a BlockingQueue with a capacity bound and a put-based enqueue gives you a natural pause when the frontier is saturated, and a bounded seen-set or store keeps memory from growing without limit. If you must cap memory, cap the frontier by total pending URLs and stop enqueuing (or drop low-priority URLs) when full — dropping is a policy decision, so log it.
Parse HTML to extract links and content safely
Use a real HTML parser rather than regular expressions; page markup is not regular. jsoup is the pragmatic Java choice: it handles malformed markup, provides CSS selectors, resolves relative URLs, and exposes a charset guess. Alternatives exist for specific needs, but the design point is the same: one parser module, deterministic input-to-links mapping, unit tests with fixture files.
Extraction rules to decide and document:
Which link attributes: , , and, if your scope includes assets, and . Forms and javascript: pseudo-links are out unless your contract says otherwise. Canonicalization: prefer a value over the fetched URL for records that represent the page's canonical identity. This avoids storing duplicates under different addresses, though it doesn't relieve you of tracking the actual URLs visited. Meta robots: honor per your contract. nofollow means don't follow the links; noindex means don't store the page as an indexed result. These are hints the site publishes for crawlers, and ignoring them invites trouble. Fragment-only and self links: discard them before the frontier; normalization handles this, but only if you resolve before dedup. A useful extraction output is ExtractedPage(finalUri, canonicalUri, title, text, List outboundLinks, metaRobots). The coordinator then only has to map outboundLinks through the acceptance rule and the seen-set. Design the frontier, ordering, and crawl budget Ordering policy determines what your crawl actually covers. Breadth-first traversal, implemented as FIFO, covers shallow pages before deep ones, which is a sensible default. Depth-first catches long tails quickly but tends to dive into one section of a site and starve the rest. Priority queues let you bias toward URLs that look important — shorter paths, more inbound links, or a whitelist of path prefixes — but priority schemes are easy to overfit. Concrete budget parameters worth tracking per crawl: URLs fetched and bytes downloaded URLs skipped by robots, by scope rejection, and by dedup (these numbers tell you whether normalization is working) Failures by type (timeout, 5xx, DNS, too-large), with sample URLs Distribution of requests per host, so you can spot a single host consuming half the budget A useful arithmetic check: if you aim for 50,000 pages and average 200 KB of HTML per page, the download budget is roughly 10 GB before compression and overhead — and at one request per second per host, a single host would take about 14 hours. That tells you whether you need more seeds, a larger delay budget, or a smaller scope, before you've written the scheduler. The stop condition is part of the design: stop when the frontier is empty (natural exhaustion), when a budget counter hits its cap (and record what's left), or when an error rate exceeds a threshold (a sign the network or peers are failing you). A crawler with no stop condition is a crawler that runs until someone kills it, usually after it has annoyed a host. Persist state so restarts don't restart the crawl Crawl state has two halves: the frontier (what's left) and the seen-set plus per-host politeness state (what's been done and how recently). Losing the seen-set means refetching everything; losing politeness state means a restart immediately re-hammers the same hosts. Both should survive a clean shutdown. The minimal robust design is an append-only log plus snapshots: 1: When a URL is enqueued, append a record {url, state=queued}. 2: When a URL is fethed, append {url, state=fetched, status, timestamp}. 3: Periodically write a snapshot of the seen-set and frontier; on restart, load the latest snapshot and replay log entries after it. For modest crawls, a relational database with a urls table (key, state, host, last_fetch, attempts) and a unique index on the normalized key gives you dedup and persistence for free, at the cost of write throughput. For larger crawls, an embedded key-value store plus a separate frontier file (or a simple disk-backed queue) is a fine middle ground. Avoid engineering a distributed system until a single-machine crawler demonstrably can't keep up; the complexity of coordination usually dwarfs the bandwidth gain for small teams. One more state item: the robots cache and per-host delays should be revalidated after a long pause. A crawler resuming after a week should not assume the previous crawl-delay still applies. Failure modes, retries, and the checks that confirm it works Troubleshooting starts by distinguishing symptoms: Every page fails with the same error — usually networking or TLS: check the User-Agent (some hosts block defaults), proxy requirements, and whether the client is following redirects into a login wall. Duplicate fetches in the store — normalization mismatch between enqueue and dedup, or redirect final URLs not being marked as seen. Host starved or hammered — per-host scheduling is wrong; inspect the in-flight counters per host. Parser returns zero links — charset mismatch turning the HTML into mojibake, a tag changing resolution, or content served as JavaScript-rendered markup with no anchors in the initial HTML. The last one is a scope signal: your contract said "HTML only," so record the page and move on rather than adding a browser engine on a whim. Memory climbs monotonically — the seen-set or frontier is unbounded, or the parser retains whole documents after extraction. Retries need a policy: retry transient statuses (429, 502, 503, 504) and network timeouts with exponential backoff and jitter, capped at a small number of attempts, and honor Retry-After when present. Never retry a 404. For 429s, the per-host delay should lengthen, not just that one request. Success checks that cost little to build: a fixture test that runs the whole pipeline against a local static site and asserts an exact set of fetched URLs (this catches normalization regressions immediately), a unit test for robots parsing against a handful of known-shape files, and a smoke run against a small seed list where you manually inspect the URL log. If those three pass, the pipeline is likely sound; the remaining risk is scale. Where the design stops and a professional is warranted If your crawl crosses into a target's authenticated areas, personal data, or a site whose terms explicitly prohibit crawling, that's a stop condition: the legal and ethical review belongs with counsel, not with the crawler's retry logic. Likewise, when you need a distributed crawl with coordination guarantees, or when the target requires rendering JavaScript at scale, the engineering changes shape substantially (headless browser fleets, crawl coordination services) and is worth a specialist's assessment before you commit to it. The design above is deliberately single-machine, single-team, and boring — and that's its strength.