Skip to content
Mohamad Doughman
Go back

Sample: Idempotent Likes with a Unique Index

Category:.NET

This is the second sample post. It’s part 2 of the Building This Blog series and lives in the .NET category, so you can see how series and categories link posts together.

One like per visitor

The rule is simple: a visitor can like a post once. Instead of checking first and inserting second (which races under load), let the database enforce it:

CREATE UNIQUE INDEX UX_PostLikes_Slug_Visitor
    ON PostLikes (Slug, VisitorId);

Treat duplicates as success

If the insert hits the unique index, the visitor already liked the post. That’s not an error from their point of view:

try
{
    db.PostLikes.Add(new PostLike(slug, visitorId));
    await db.SaveChangesAsync();
}
catch (DbUpdateException ex) when (IsUniqueViolation(ex))
{
    // Already liked: same result as a successful like.
}
return Results.NoContent();
Tip

Idempotent endpoints are easier to retry. A double-click or a network retry can’t create two likes.


Share this post:

Previous Post
Sample: Counting Page Views with Redis