DEV Community

Cover image for Code Smell 120 - Sequential IDs
Maxi Contieri
Maxi Contieri

Posted on • Updated on • Originally published at

Code Smell 120 - Sequential IDs

Most IDS are code smells. Sequential IDs are also a vulnerability

TL;DR: Don't expose obvious consecutive IDs.



  1. Use non-obvious keys.

  2. Use dark keys or UUIDs.


IDs are a problem when dealing with domain objects.

IDs do not exist in the real-world so, they break our bijection.

We should only use IDs when exposing internal resources to the outer world beyond system boundaries.

These are always accidental problems and should not interfere with our models.

Sample Code


class Book {
    private Long bookId; //book knows its ID
    private List<Long> authorIds; // book knows author IDs

Book harryPotter = new Book(1, {1, 2, 3});
Book cleanCode = new Book(2, {4});
Book donQuixote = new Book(3, {5});

//We can scrap from now one.
Enter fullscreen mode Exit fullscreen mode


class Author {    
    //.. Author protocol

class Book {    
    private List<Author> authors; // book knows authors
    // No strange behavior. just what a book can do
    // Real books don't know about IDs
    // ISBN is accidental to a book. Readers don't care

class BookResource {    
    private Book resource; // The resource knows the underlying book
    private id; //The id is the link we provide to external world

Book harryPotter = new Book({new Author('J. K. Rowling'));
Book cleanCode = new Book({'Robert Martin'})
Book donQuixote = new Book({'Miguel Cervantes'});

BookResource harryPotterResource = new BookResource(harryPotter, UUID.randomUUID());                             

//Books don't know they id. Just the resource does
Enter fullscreen mode Exit fullscreen mode


[X] Automatic

We can use Pentesting techniques against our system to detect this smell.


  • Security


In case we need to expose internal objects to the external world, we should use non-obvious IDs.

In this way, we can detect (and block) brute force attacks monitoring the traffic and 404 errors.

More Info


Photo by Max Bender on Unsplash

Thanks @davidkroell for the KSUID tip.

The only truly secure system is one that is powered off, cast in a block of concrete and sealed in a lead-lined room with armed guards.

Gene Spafford

This article is part of the CodeSmell Series.

Top comments (2)

davidkroell profile image
David Kröll

Besides that, I really like KSUID (originally implemented in Go, but now available for many languages). These are k-sortable based on time, such when saving to database the entities are in historical order.

mcsee profile image
Maxi Contieri

didn't know about them
Thanks for the tip!!