Skip to content

Collision Detection Pattern in URL Shorteners

The Collision Detection Pattern is a critical error-handling strategy in URL shortener implementation. It specifically addresses the scenario where the system attempts to generate or assign a short code that already exists in the database^[001-TODO__Cloudflare_Workers_自架短網址_-10_分鐘完工教學.md]. Without this pattern, newly created URLs could overwrite existing mappings, leading to data loss or incorrect redirects^[001-TODO__Cloudflare_Workers_自架短網址-_10_分鐘完工教學.md].

Core Mechanism

When a request is made to shorten a URL, the system must verify the uniqueness of the generated key before committing it to storage^[001-TODO__Cloudflare_Workers_自架短網址_-_10_分鐘完工教學.md]. This is typically implemented as a "check-then-act" sequence within the API handler:

  1. Generate: Produce a short code (either randomly or via hash).
  2. Check: Query the [[Key-Value Store]] (or database) to see if the key is already in use.
  3. Handle:
    • If Unique: Proceed to save the new mapping.
    • If Exists: Abort the operation and return a specific error status.

Implementation Example (Cloudflare Workers)

In a serverless environment using a Key-Value store like [[Cloudflare KV]], the logic for creating a short URL (POST request) should explicitly include this verification^[001-TODO__Cloudflare_Workers_自架短網址_-_10_分鐘完工教學.md].

If the application allows users to specify their own custom short slugs, the collision check is mandatory to prevent one user from hijacking another's active link^[001-TODO__Cloudflare_Workers_自架短網址_-_10_分鐘完工教學.md].

Error Handling and Status Codes

When a collision is detected, the application should not proceed with the write operation^[001-TODO__Cloudflare_Workers_自架短網址_-_10_分鐘完工教學.md]. Instead, it should communicate the conflict to the client.

The standard HTTP status code for this scenario is 409 Conflict^[001-TODO__Cloudflare_Workers_自架短網址_-_10_分鐘完工教學.md]. This informs the client that the requested short code is already taken and allows them to retry with a different identifier (or allow the system to auto-generate a new one).

Consequences of Omission

Failing to implement the Collision Detection Pattern results in "silent overwrites." In this state, the database updates the existing key with a new value, causing the original long URL to be permanently lost^[001-TODO__Cloudflare_Workers_自架短網址_-_10_分鐘完工教學.md].

Debugging this issue can be time-consuming, as the system appears to function correctly (redirects still work), but the destination targets are incorrect^[001-TODO__Cloudflare_Workers_自架短網址_-_10_分鐘完工教學.md].

Sources

  • 001-TODO__Cloudflare_Workers_自架短網址_-_10_分鐘完工教學.md