slugme.ioclean-url-slug-generator

How to Handle Duplicate URL Slugs: 4 Strategies

Two posts called "My First Post" can't share a URL. Compare counters, IDs, scoping and dates for unique slugs, and avoid the race condition most code has.

By 4 min read
How to Handle Duplicate URL Slugs: 4 Strategies

The first time you generate slugs automatically, everything works. Then somebody publishes a second post called "My First Post", or two products are both named "Classic T-Shirt", and your app either crashes on a unique constraint or — worse — quietly gives two pages the same URL.

This guide covers the four strategies for unique slugs, how real platforms handle it, and the race condition most tutorials miss.

Why duplicates happen more than you'd think

Collisions are not just about identical titles. Slug generation is lossy by design, so different titles routinely produce the same slug:

"The Best SEO Tips"        → best-seo-tips
"Best SEO Tips!"           → best-seo-tips
"Best SEO tips (2026)"     → best-seo-tips-2026  (until you strip numbers…)
"Café Tips" / "Cafe Tips"  → cafe-tips

Add stop-word removal and a max length, and collisions become routine in any catalog of a few thousand items. You need a plan before you need it.

Strategy 1: numeric counter suffixes

The most common approach: if my-post is taken, try my-post-2, then my-post-3.

/blog/my-post
/blog/my-post-2
/blog/my-post-3

Who does this: WordPress (its wp_unique_post_slug() function appends -2, -3…), most CMSs, and libraries like @sindresorhus/slugify via slugifyWithCounter().

Pros: URLs stay clean and readable. Only the colliding items get suffixes.

Cons: The suffix carries no meaning, and -2 often hints that two pages target the same topic — which may be the real problem to fix.

Start the counter at 2, not 1: my-post is implicitly the first, and my-post-1 next to my-post looks like an error.

Strategy 2: include the ID

Put the record's unique ID in the URL, alongside the slug:

/questions/11227809/why-is-processing-a-sorted-array-faster
/products/4471-classic-t-shirt

Stack Overflow is the famous example: the number identifies the question, and the slug is decoration. Change the slug, or mistype it, and the site redirects to the canonical version — because it looks up the ID and ignores the text.

Pros: Never collides. The slug can be edited freely without breaking links, as long as you redirect non-canonical slugs.

Cons: Longer, less elegant URLs; exposes record counts.

If you choose this, always redirect wrong slugs to the canonical one. Otherwise /products/4471-anything serves the same page at infinite URLs — an URL normalization problem.

Strategy 3: scope the slug

A slug only needs to be unique where it is used. Scoping removes most collisions with no suffix at all:

/recipes/chocolate-cake          ← unique within recipes
/reviews/chocolate-cake          ← unique within reviews
/users/alice/chocolate-cake      ← unique per user
/fr/gateau-chocolat              ← unique per language

In the database, that means a composite unique index — for example UNIQUE (category_id, slug) or UNIQUE (locale, slug) — instead of a global one.

Watch out: if the scope appears in the URL and items can move between scopes (a post changing category), the URL changes. Only scope by things that are stable.

Strategy 4: dates

/2026/10/my-post

Date-scoped slugs rarely collide, but they age content and make updates awkward, as covered in blog post URL best practices. Use them for genuinely time-bound content — news, changelogs, event pages — not evergreen guides.

Which strategy to choose

Content Recommended
Blog posts, guides, landing pages Counter suffixes (and rethink true duplicates)
Large product catalogs, marketplaces Scoped slugs, or ID + slug
User-generated content (forums, profiles) ID + slug
News, changelogs Date-scoped
Multilingual sites Scope by locale

The race condition everybody forgets

The obvious implementation checks first, then inserts:

async function createPost(title) {
  const base = slugify(title)
  let slug = base
  let n = 2
  while (await db.post.exists({ slug })) {
    slug = `${base}-${n++}`
  }
  return db.post.insert({ title, slug })   // ← two requests can both get here
}

If two requests create "My Post" at the same moment, both see my-post as free, and both insert it. Without a database constraint, you now have two pages with the same URL; with one, a request fails with an error.

The robust pattern is: unique index + retry on conflict.

CREATE UNIQUE INDEX posts_slug_unique ON posts (slug);
async function createPost(title, attempt = 0) {
  const base = slugify(title) || 'post'
  const slug = await nextFreeSlug(base)
  try {
    return await db.post.insert({ title, slug })
  } catch (error) {
    if (isUniqueViolation(error) && attempt < 3) {
      return createPost(title, attempt + 1)   // someone took it — try again
    }
    throw error
  }
}

isUniqueViolation checks your driver's error code (for example 23505 in PostgreSQL or ER_DUP_ENTRY in MySQL). The pre-check keeps the common case fast; the constraint guarantees correctness under load.

Finding the next free slug in one query

Looping one query per candidate gets slow when you have my-post through my-post-40. Fetch all candidates at once instead:

SELECT slug FROM posts
WHERE slug = 'my-post' OR slug LIKE 'my-post-%';

Then, in code, collect the numeric suffixes and pick max + 1. (Filter the results with a pattern like ^my-post-(\d+)$ so my-post-office isn't counted.)

Don't forget the empty slug

Every strategy assumes slugify() returned something. Titles made entirely of emoji, symbols or unsupported scripts can produce an empty string — Django's default slugify('Привет') does exactly that, as we found when testing slug libraries. Always fall back to something (post, or the ID), or your "unique" slug becomes "", then -2.

Generating unique slugs in bulk

When you import or migrate content, generate and de-duplicate all slugs in one pass before touching the database. The bulk slug generator does this: paste one title per line, leave "Make duplicates unique" on, and download a CSV where repeats are already -2, -3. For a single title, the URL slug generator is quicker.

Frequently asked questions

Why does WordPress add -2 to my URL?

Another post, page or attachment — sometimes one in the trash, or an image you uploaded with the same file name — already uses that slug. WordPress appends -2, -3 to keep slugs unique. Delete or rename the item holding the slug and edit your post's slug back.

Is a -2 suffix bad for SEO?

Not directly, but it often signals two pages on the same topic competing for the same query. Before accepting a suffix, consider whether the new page should be merged into the existing one, or given a more specific slug.

Should I put the database ID in the URL?

It's a solid choice for large, frequently changing catalogs and user-generated content: the ID guarantees uniqueness, and you can redirect any wrong slug to the canonical one. For editorial content, clean counter-free slugs read better.

Keep reading