Table of Contents
Question content
Solution
Concept part
trade
Lock kv storage
coding
Home Backend Development Golang How are keys in KV Store locked?

How are keys in KV Store locked?

Feb 09, 2024 pm 01:20 PM
concurrent access

KV Store 中的密钥是如何锁定的?

php Editor Zimo will reveal the secret of key locking in KV Store for you. In KV Store, key locking is achieved through a series of complex algorithms and technologies. First, the system generates a unique identifier for each key and stores it with the corresponding value in the database. At the same time, the system will also use a hash function to encrypt the key to ensure its security. In addition, the system also uses access control lists (ACLs) to restrict access to keys so that only authorized users can perform read and write operations. Through these security measures, KV Store ensures the security and reliability of keys and provides users with safe and reliable data storage services.

Question content

I am building a distributed kv store just to learn more about distributed systems and concurrency. The implementation of kv storage I'm building is fully transactional, with an in-memory transaction log. To keep things simple, storage is also entirely in-memory. The api exposes get, insert, update, remove. Note that all endpoints operate on a single key, not a range of keys.

I manage concurrency through locks. However, I have a global lock that locks the entire data store. This sounds very inefficient, because if I want to read the value of k1 while updating k2, I have to wait for k2 to finish updating, although that's irrelevant.

I know some databases use more fine-grained locking. For example, in mysql server there are row level locks. How to implement key-level locking?

I have

type storage struct {
  store map[string]int32
}
Copy after login

Should I add something like this? :

type Storage struct {
  store map[string]int32
  locks map[string]mutex.Lock
}
Copy after login

If I do this, the problem is that locks must be kept in sync with store. Another option would be to merge the two maps, but even then I would encounter removing entries in the map while locked if the remove request comes before the get The problem.

Solution

Concept part

trade

First of all, strong consistency does not require transaction logs. Transaction logs are useful for maintaining acid properties.

Transactions are also not a strict requirement for strong consistency in a database, but they can be a useful tool for ensuring consistency in many situations.

Strong consistency refers to the property that ensures that all reads from the database will return the most recent write, regardless of where the read operation is performed. In other words, strong consistency guarantees that all clients will see the same data and that the data will be up-to-date and consistent across the system.

You can use consensus algorithms such as paxos or raft to ensure strong consistency. When storing data, you can store a version of the data and use it as an id in paxos.

Lock kv storage

In a key-value (kv) store, keys are usually locked using some kind of locking mechanism, such as a mutex or reader-writer lock (as @paulsm4 suggested). This allows multiple threads or processes to access and modify data in the kv store simultaneously while still ensuring that the data remains consistent and correct.

For example, when a thread or process wants to read or modify a specific key in the kv store, it can acquire a lock on that key. This prevents other threads or processes from modifying the same key at the same time, causing race conditions and other problems. Once a thread or process has finished reading or modifying the key, the lock can be released, allowing other threads or processes to access the key.

The specific details of how keys are locked in kv storage may vary depending on the implementation of kv storage. Some kv stores may use global locks (as you are already doing, which is sometimes inefficient) to lock the entire data store, while other kv stores may use more fine-grained locking mechanisms such as row-level locks or key-level Lock to allow more operations. Concurrent access to data.

So, tldr; conceptually, you're right. The problem lies in the implementation details of locking.

coding

To strictly answer the question about locking, consider reader-writer locks as @paulsm4 suggested. In golang, a similar lock is rwmutex. It is used for sync. map.

Here is a short example:

type Storage struct {
  store sync.Map // a concurrent map
}

// GET retrieves the value for the given key.
func (s *Storage) GET(key string) (int32, error) {
  // Acquire a read lock for the key.
  v, ok := s.store.Load(key)
  if !ok {
    return 0, fmt.Errorf("key not found: %s", key)
  }

  // Return the value.
  return v.(int32), nil
}

// INSERT inserts the given key-value pair into the data store.
func (s *Storage) INSERT(key string, value int32) error {
  // Acquire a write lock for the key.
  s.store.Store(key, value)
  return nil
}

// UPDATE updates the value for the given key.
func (s *Storage) UPDATE(key string, value int32) error {
  // Acquire a write lock for the key.
  s.store.Store(key, value)
  return nil
}

// REMOVE removes the key-value pair for the given key from the data store.
func (s *Storage) REMOVE(key string) error {
  // Acquire a write lock for the key.
  s.store.Delete(key)
  return nil
}
Copy after login

In addition to this, you need paxos to ensure consistency between replicas.

The above is the detailed content of How are keys in KV Store locked?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24
How to ensure thread safety of volatile variables in Java functions? How to ensure thread safety of volatile variables in Java functions? May 04, 2024 am 10:15 AM

Methods for ensuring thread safety of volatile variables in Java: Visibility: Ensure that modifications to volatile variables by one thread are immediately visible to other threads. Atomicity: Ensure that certain operations on volatile variables (such as writing, reading, and comparison exchanges) are indivisible and will not be interrupted by other threads.

How to solve the problem of busy servers for deepseek How to solve the problem of busy servers for deepseek Mar 12, 2025 pm 01:39 PM

DeepSeek: How to deal with the popular AI that is congested with servers? As a hot AI in 2025, DeepSeek is free and open source and has a performance comparable to the official version of OpenAIo1, which shows its popularity. However, high concurrency also brings the problem of server busyness. This article will analyze the reasons and provide coping strategies. DeepSeek web version entrance: https://www.deepseek.com/DeepSeek server busy reason: High concurrent access: DeepSeek's free and powerful features attract a large number of users to use at the same time, resulting in excessive server load. Cyber ​​Attack: It is reported that DeepSeek has an impact on the US financial industry.

What pitfalls should we pay attention to when designing distributed systems with Golang technology? What pitfalls should we pay attention to when designing distributed systems with Golang technology? May 07, 2024 pm 12:39 PM

Pitfalls in Go Language When Designing Distributed Systems Go is a popular language used for developing distributed systems. However, there are some pitfalls to be aware of when using Go, which can undermine the robustness, performance, and correctness of your system. This article will explore some common pitfalls and provide practical examples on how to avoid them. 1. Overuse of concurrency Go is a concurrency language that encourages developers to use goroutines to increase parallelism. However, excessive use of concurrency can lead to system instability because too many goroutines compete for resources and cause context switching overhead. Practical case: Excessive use of concurrency leads to service response delays and resource competition, which manifests as high CPU utilization and high garbage collection overhead.

Locking and synchronization mechanism of C++ functions in concurrent programming? Locking and synchronization mechanism of C++ functions in concurrent programming? Apr 27, 2024 am 11:21 AM

Function locks and synchronization mechanisms in C++ concurrent programming are used to manage concurrent access to data in a multi-threaded environment and prevent data competition. The main mechanisms include: Mutex (Mutex): a low-level synchronization primitive that ensures that only one thread accesses the critical section at a time. Condition variable (ConditionVariable): allows threads to wait for conditions to be met and provides inter-thread communication. Atomic operation: Single instruction operation, ensuring single-threaded update of variables or data to prevent conflicts.

How to use atomic classes in Java function concurrency and multi-threading? How to use atomic classes in Java function concurrency and multi-threading? Apr 28, 2024 pm 04:12 PM

Atomic classes are thread-safe classes in Java that provide uninterruptible operations and are crucial for ensuring data integrity in concurrent environments. Java provides the following atomic classes: AtomicIntegerAtomicLongAtomicReferenceAtomicBoolean These classes provide methods for getting, setting, and comparing values ​​to ensure that the operation is atomic and will not be interrupted by threads. Atomic classes are useful when working with shared data and preventing data corruption, such as maintaining concurrent access to a shared counter.

A guide to unit testing Go concurrent functions A guide to unit testing Go concurrent functions May 03, 2024 am 10:54 AM

Unit testing concurrent functions is critical as this helps ensure their correct behavior in a concurrent environment. Fundamental principles such as mutual exclusion, synchronization, and isolation must be considered when testing concurrent functions. Concurrent functions can be unit tested by simulating, testing race conditions, and verifying results.

Lock granularity optimization skills for golang function concurrent cache Lock granularity optimization skills for golang function concurrent cache May 05, 2024 am 08:45 AM

Lock granularity tips for optimizing Go concurrent cache performance: Global lock: Simple implementation, if the lock granularity is too large, unnecessary competition will occur. Key-level locking: The lock granularity is refined to each key, but it will introduce a large number of locks and increase overhead. Shard lock: Divide the cache into multiple shards, each shard has a separate lock, to achieve a balance between concurrency and lock contention.

How do pessimistic locks and optimistic locks in Java functions achieve thread safety? How do pessimistic locks and optimistic locks in Java functions achieve thread safety? May 04, 2024 pm 04:51 PM

Two ways to achieve thread safety in Java functions: pessimistic locking: acquire the lock before accessing data to prevent concurrent access by other threads to ensure data consistency. (synchronized keyword) Optimistic locking: Verify data at the end of the transaction and roll back the transaction if the data is modified to improve concurrency. (Atomic class in java.util.concurrent.atomic package)

See all articles