Skip to content

Using check-and-set (CAS)  #5917

Closed
Closed

Description

@Stashchenko

image
The APP will always return old data until someone DEL the key again.
How to manage such race condition?

Activity

  1. changed the title [-]How to use check-and-set (CAS) [/-] [+]Using check-and-set (CAS) [/+] on Mar 11, 2019
  2. Stashchenko commented on Mar 12, 2019

    @Stashchenko
    Author

    I've found a solution: Instead of DEL in Thread 2, I decided to use:
    SETNX "id:1" "" with empty value
    EXPIRE "id:1" 0

    Then in EXEC (Thread 1) we'll see error since key "id:1" was modified
    Thread 3 doesn't GET data by "id:1" since expire == 0 (+double checking (in APP) on empty string "")

  3. eyjian commented on Apr 2, 2019

    @eyjian

    LUA:
    -- KEYS[1] data key
    -- ARGV[1] version fieldname
    -- ARGV[2] new version value
    -- ARGV[3] data fieldname
    -- ARGV[4] data
    -- ARGV[5] old version value
    local oldver=redis.call('HGET',KEYS[1],ARGV[1])
    if oldver then
    if tonumber(oldver)~=tonumber(ARGV[5]) then
    -- Get and return new values
    return redis.call('HMGET',KEYS[1],ARGV[1],ARGV[3])
    end
    end
    -- Set value when there is no conflict
    redis.call('HMSET',KEYS[1],ARGV[1],ARGV[2],ARGV[3],ARGV[4])
    return redis.status_reply('OK')

  4. Stashchenko commented on Apr 2, 2019

    @Stashchenko
    Author

    Thanks @eyjian. Could we use CAS without LUA scripting?
    Since we are monitoring KEY via WATCH. Logically, everything what would touch my KEY should show me in EXEC of my transaction.
    If another thread tries to DEL key (no matter exist or not), better to know that someone changed our key. I wonder if it's correct situation.

  5. sundb commented on Oct 28, 2025

    @sundb
    Collaborator

    Close via #14435

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions