Java Back-end Skills Summary
0 Report
A mind map of the Java back-end skill knowledge system, covering core technical areas such as Java fundamentals, development frameworks, data storage, caching, message middleware, microservices, and container services, and organizing the knowledge structure and learning directions for Java back-end development.
Related Recommendations
Other works by the author
Outline/Content
See more
Java fundamentals
Multithreading
Thread pools
The process of pre-creating threads in a thread pool
If the number of threads in the thread pool is less than coreThreadCount, a new thread is created when handling a new task;
If the number of threads is greater than coreThreadCount, the task is put into a queue to be executed by a currently idle thread;
When the queue becomes full of tasks, threads continue to be created until maxThreadCount is reached;
When the number of threads reaches maxTheadCount and new tasks are still submitted, we have to discard them.
Issues to note about thread pools
This thread pool implemented by the JDK prefers to put tasks into a queue for temporary storage rather than creating more threads, which makes it suitable for executing CPU-intensive tasks, that is, tasks requiring a large amount of CPU computation. Why? Because when executing CPU-intensive tasks the CPU is busy, so it is enough to create as many threads as there are CPU cores; more threads would instead cause thread context switching and reduce task execution efficiency. Therefore, when the current number of threads exceeds the core thread count, the thread pool does not add threads but puts tasks in the queue to wait for a core thread to become free.
However, the Web systems we usually develop have a large number of IO operations, such as querying databases and caches. While a task is performing an IO operation the CPU is idle, so if we increase the number of threads executing tasks instead of temporarily storing tasks in a queue, more tasks can be executed per unit time, greatly improving task throughput. So you can see that the thread pool used by Tomcat is not the native JDK thread pool but a modified one: when the number of threads exceeds coreThreadCount, it preferentially creates new threads until the count reaches maxThreadCount, which suits scenarios with many IO operations in Web systems. You can also refer to this approach in practice.
Second, the backlog of the queue used in the thread pool is also an important metric we need to monitor; for tasks with high real-time requirements, this metric is especially critical.
Finally, if you use a thread pool, remember never to use an unbounded queue (i.e., a queue with no fixed size). You might think that with an unbounded queue tasks are never discarded and, as long as they are not time-critical, they will eventually be consumed. However, a large backlog of tasks consumes a lot of memory; once memory is full, Full GC is triggered frequently, causing service unavailability. A GC-induced outage I once investigated was caused precisely by a thread pool in the system using an unbounded queue.
Locks
Synchronized
One is to decorate a code block
When Synchronized decorates a synchronized code block, synchronization is implemented by the monitorenter and monitorexit instructions. After entering the monitorenter instruction, the thread holds the Monitor object; after exiting the monitorenter instruction, the thread releases the Monitor object.
One is to decorate a method
When Synchronized decorates a synchronized method, no monitorenter or monitorexit instruction is found; instead, an ACC_SYNCHRONIZED flag appears.
This is because the JVM uses the ACC_SYNCHRONIZED access flag to distinguish whether a method is synchronized. When a method is called, the invocation instruction checks whether the method has the ACC_SYNCHRONIZED flag set. If set, the executing thread first acquires the Monitor object and then executes the method. During the method's execution, other threads cannot acquire the Mointor object; after the method completes, the Monitor object is released.
Synchronization in the JVM is implemented based on entering and exiting the monitor (Monitor) object. Every object instance has a Monitor, which can be created and destroyed together with the object. The Monitor is implemented by ObjectMonitor, which in turn is implemented in the C++ file ObjectMonitor.hpp, as shown below:
When multiple threads access a synchronized code section at the same time, they are first stored in the ContentionList and _EntryList collections; threads in the block state are added to these lists. Next, when a thread acquires the object's Monitor, the Monitor relies on the underlying operating system's Mutex Lock to achieve mutual exclusion. If a thread successfully requests the Mutex, it holds it and other threads cannot obtain it; the threads that fail competition enter ContentionList again and are suspended.
If a thread calls the wait() method, it releases the currently held Mutex and enters the WaitSet collection, waiting to be awakened next time. If the current thread completes the method successfully, it also releases the Mutex.
Lock upgrade optimization
Biased locking
Biased locking is mainly used to optimize contention when the same thread requests the same lock repeatedly. In some cases, most of the time the same thread competes for the lock resource — for example, when creating a thread and executing a loop to listen inside it, or when a single thread operates on a thread-safe collection. Each time the same thread must acquire and release the lock, and each operation involves a switch between user mode and kernel mode.
The role of biased locking is that when a thread accesses the synchronized code or method again, it only needs to check the Mark Word in the object header to see whether there is a biased lock pointing to its ID, without entering the Monitor to compete for the object again. When an object is used as a synchronization lock and a thread wins the lock, the lock flag is still 01, the "biased lock" flag is set to 1, and the thread ID of the winner is recorded, indicating entry into the biased-locking state.
Once another thread competes for the lock resource, the biased lock is revoked. Revoking a biased lock requires waiting for a global safepoint, suspending the thread holding the lock, and checking whether that thread is still executing the method: if so, the lock is upgraded; otherwise it is seized by the other thread.
In high-concurrency scenarios, when many threads compete for the same lock resource, biased locking is revoked. Once a stop the world occurs, enabling biased locking will undoubtedly bring greater performance overhead. At this point we can tune system performance by adding a JVM parameter to disable biased locking, as shown below: -XX:-UseBiasedLocking //disable biased locking (enabled by default)
The process of biased lock acquisition and revocation
Lightweight lock
When another thread competes for the lock, since it is already a biased lock, if the thread finds that the thread ID in the object header Mark Word is not its own, it performs a CAS operation to acquire the lock. If successful, it directly replaces the thread ID in the Mark Word with its own and the lock remains biased; if acquisition fails, it means there is some contention, and the biased lock is upgraded to a lightweight lock.
Lightweight locks are suitable for scenarios where threads execute synchronized blocks alternately, and for the vast majority of locks there is no long-term contention throughout the synchronization period.
The process of upgrading to a lightweight lock
Spin locks and heavyweight locks
If a lightweight lock fails to acquire the lock via CAS, the thread is suspended and enters a blocked state. If the thread holding the lock releases the resource in a very short time, the blocked thread will undoubtedly have to request the lock resource again.
The JVM provides a spin lock, which keeps trying to acquire the lock by spinning so as to avoid suspending and blocking the thread. This is based on the fact that in most cases a thread does not hold a lock for very long; after all, suspending and blocking a thread may cost more than it gains.
Since JDK1.7, spin locks are enabled by default, and the number of spins is determined by JVM settings. I do not recommend setting too many retries here, because CAS retry operations mean occupying the CPU for a long time.
If the spin lock still fails to acquire the lock after retries, the synchronization lock is upgraded to a heavyweight lock and the lock flag is changed to 10. In this state, threads that fail to acquire the lock enter the Monitor and are then blocked in the _WaitSet queue.
The process of upgrading to a heavyweight lock after spinning
When lock contention is not intense and the lock is held for a very short time, spin locks can improve system performance. Once contention becomes fierce or the lock is held too long, spin locks cause many threads to stay in a CAS retry state, consuming CPU resources and actually increasing system overhead. Therefore, the use of spin locks and heavyweight locks must be combined with the actual scenario.
Under high-load, high-concurrency scenarios, we can disable spin locks by setting JVM parameters to optimize system performance, as shown below:
-XX:-UseSpinning //parameter to disable spin lock optimization (enabled by default)
-XX:PreBlockSpin //parameter to change the default number of spins. Removed after JDK1.7; controlled by the JVM
-XX:-UseSpinning //parameter to disable spin lock optimization (enabled by default)
-XX:PreBlockSpin //parameter to change the default number of spins. Removed after JDK1.7; controlled by the JVM
Lock elimination / lock coarsening through dynamic compilation
Java also uses the compiler to optimize locks. When the JIT compiler dynamically compiles a synchronized block, it uses a technique called escape analysis to determine whether the lock object used by the block can only be accessed by one thread and is not published to other threads.
When compiling this synchronized block, the JIT compiler does not generate machine code for applying and releasing the lock represented by synchronized, that is, it eliminates the use of the lock. In versions after Java7, no manual configuration is needed; this operation can be implemented automatically.
Lock coarsening works similarly: when the JIT compiler dynamically compiles, if it finds several adjacent synchronized blocks using the same lock instance, it merges them into one large synchronized block, avoiding the performance overhead of a thread "repeatedly acquiring and releasing the same lock".
Lock
AQS
The AQS class structure contains a wait queue implemented as a linked list (the CLH queue), which is used to store all blocked threads,
There is also a state variable in AQS, which for ReentrantLock represents the locking state.
Process of acquiring the lock
Optimizing lock separation with the Lock synchronization lock
Read–write lock ReentrantReadWriteLock
RRW is also implemented based on AQS. Its custom synchronizer (inheriting AQS) needs to maintain the state of multiple reading threads and one writing thread on the synchronization state state, and the design of this state is the key to implementing a read-write lock. RRW makes good use of high and low bits to control two states with a single integer: the read-write lock splits the variable into two parts, with the high 16 bits representing reads and the low 16 bits representing writes.
Process of acquiring the write lock
When a thread tries to acquire the write lock, it first checks whether the synchronization state state is 0. If state equals 0, no other thread currently holds the lock; if state is not 0, another thread has acquired it.
At this point, check whether the low 16 bits (w) of the synchronization state state is 0. If w is 0, another thread has acquired the read lock, so the thread enters the CLH queue to block and wait. If w is not 0, another thread has acquired the write lock; then check whether the write-lock holder is the current thread. If not, enter the CLH queue to block and wait; if so, check whether the current thread has exceeded the maximum number of write-lock acquisitions — if so, throw an exception, otherwise update the synchronization state.
Process of acquiring the read lock
When a thread tries to acquire the read lock, it likewise first checks whether the synchronization state state is 0. If state equals 0, no other thread currently holds the lock; it then decides whether blocking is needed — if so, it enters the CLH queue to block and wait; if not, it uses CAS to update the synchronization state to the read state.
If state is not 0, the low 16 bits of the synchronization state are checked. If a write lock exists, acquiring the read lock fails and the thread enters the CLH blocking queue. Otherwise, it determines whether the current thread should be blocked; if not, it tries to update the synchronization state via CAS, and on success updates the synchronization lock to the read state.
Further optimizing the read–write lock with StampedLock
RRW is well applied in concurrent scenarios with more reads than writes, but there is still room for performance improvement. When there are many reads and few writes, RRW can cause write-thread starvation: a writing thread remains waiting because it cannot acquire the lock for a long time.
Java provides the StampedLock class to solve this problem. StampedLock is not implemented based on AQS, but its implementation principle is the same as AQS: both are based on queues and lock state. Unlike RRW, StampedLock has three lock modes: write, pessimistic read, and optimistic read, and when acquiring a lock it returns a stamp. The acquired stamp must be checked not only when releasing the lock, but also, in optimistic read mode, as a second validation after reading the shared resource. I will explain how stamp works later.
When a writing thread acquires the write lock, it first obtains a stamp through WriteLock. WriteLock is an exclusive lock, so only one thread can hold it at a time. After a thread acquires the lock, other requesting threads must wait; the lock can only be acquired when no thread holds a read or write lock. Upon successful acquisition, a stamp variable is returned to represent the version of the lock. When releasing the lock, you need to call unlockWrite and pass the stamp parameter.
The process for a reading thread to acquire the lock is as follows. First, the thread obtains a stamp through the optimistic lock operation tryOptimisticRead. If no thread currently holds the write lock, a non-zero stamp version is returned. After obtaining the stamp, the thread copies a share of the resource to the method stack, and all subsequent concrete operations are based on the copied data in the method stack.
Afterwards, the method needs to call validate to check whether the stamp previously returned by tryOptimisticRead is currently invalidated by another thread holding the write lock. If so, validate returns 0 and the lock is upgraded to a pessimistic lock; otherwise the lock of that stamp version can be used to operate on the data.
Compared with RRW, StampedLock acquires the read lock only by checking with AND/OR operations, without CAS operations. Even if the first optimistic acquisition fails, it immediately upgrades to a pessimistic lock, avoiding the CPU occupation and performance issues caused by continuous CAS operations. Therefore StampedLock is more efficient.
Optimistic lock
CAS is the core algorithm for implementing optimistic locking. It contains 3 parameters: V (the variable to be updated), E (the expected value), and N (the latest value).
Only when the variable to be updated equals the expected value is it set to the latest value. If the update value differs from the expected value, it means another thread has already updated the variable; in that case the current thread does nothing and returns the real value of V.
How does CAS achieve atomic operations
In the concurrent package of the JDK, all classes under the atomic path are implemented based on CAS. AtomicInteger is a thread-safe integer class implemented with CAS.
We can see that AtomicInteger's increment method getAndIncrement uses the Unsafe method getAndAddInt. Clearly AtomicInteger relies on the native Unsafe class, whose methods call low-level CPU instructions to achieve atomic operations.
How does a processor achieve atomic operations
Communication between the processor and physical memory is much slower than processing within the processor, so processors have their own internal caches. As shown below, during execution, frequently used memory data is cached in the processor's L1, L2 and L3 caches to speed up frequent reads.
Processors provide two mechanisms, bus locking and cache locking, to guarantee the atomicity of complex memory operations.
When a processor wants to operate on a shared variable, it emits a Lock signal on the bus, so other processors cannot operate on the shared variable and this processor has exclusive access to it. But while bus locking blocks other processors' requests to access the shared variable, it may also cause heavy blocking, increasing system performance overhead.
Later processors all provide a cache locking mechanism: when a processor operates on a shared variable in its cache, it notifies other processors to discard their copy of the shared resource or re-read it. All the latest processors support cache locking.
Optimizing CAS optimistic locking
Although optimistic locking is superior to pessimistic locking in concurrent performance, in scenarios with more writes than reads the probability of CAS failure increases. If we do not give up the CAS operation, we must loop and retry, which undoubtedly occupies the CPU for a long time.
In JDK1.8, Java provides a new atomic class, LongAdder. LongAdder performs better than AtomicInteger and AtomicLong in high-concurrency scenarios, at the cost of consuming more memory space.
The principle of LongAdder is to reduce the concurrency of operations on a shared variable, that is, to spread the pressure of operating on a single shared variable across multiple variable values. The value of each competing write thread is distributed into an array, different threads hit different slots of the array, each thread performs a CAS operation only on the value in its own slot, and finally, when the value is read, the shared variable of the atomic operation and all the values dispersed in the array are added up to return an approximately accurate value.
Internally, LongAdder consists of a base variable and a cell[] array. When there is only one writing thread and no contention, LongAdder directly uses the base variable as the atomic operation variable and modifies it through a CAS operation. When multiple writing threads compete, apart from the one thread occupying the base variable, each of the other threads writes its modified variable into its own slot in the cell[] array. The final result can be calculated by the following formula:
We can see that the value returned by LongAdder after an operation is only approximately accurate, but the final value returned by LongAdder is accurate. Therefore, in scenarios with high real-time requirements, LongAdder cannot replace AtomicInteger or AtomicLong.
Multithreading tuning
In a concurrent program, starting more threads does not necessarily maximize concurrency. Too few threads prevent the program from fully utilizing system resources; too many threads may cause excessive resource contention, leading to extra system overhead from context switches.
The context switching problem
Voluntary context switching
Voluntary context switching refers to a thread being switched out due to calls in the Java program. In multithreaded programming, calling the following methods or keywords often triggers voluntary context switching: sleep() wait() yield() join() park() synchronized lock
Subtopic
Non-voluntary context switch
Refers to a thread being forcibly switched out by the scheduler. Common causes include: the thread's allocated time slice is exhausted, virtual machine garbage collection, or execution priority issues.
In the Java virtual machine, object memory is allocated from the VM's heap. During program execution, new objects are constantly created; if old objects are not reclaimed after use, the heap memory will soon be exhausted. The Java virtual machine provides a reclamation mechanism that reclaims objects no longer used after creation, ensuring sustainable heap allocation. However, the use of this garbage collection mechanism may cause stop-the-world events, which are essentially a form of thread pause.
How can multithreaded context switching be optimized?
Contended lock optimization
1. Reduce the time the lock is held
, you can move some lock-independent code out of the synchronized block, especially operations with high overhead and operations that may block.
2. Reduce lock granularity
We can consider splitting the lock granularity into smaller units to avoid excessively fierce contention among all threads for one lock resource.
Lock separation
Unlike traditional locks, a read-write lock implements lock separation: it consists of two locks, a "read lock" and a "write lock", with the rule that reads can be shared but there is only one writer. The benefit is that with multiple threads reading, read–read is not mutually exclusive, while read–write and write–write are mutually exclusive. With a traditional exclusive lock that does not distinguish reads from writes, read and write operations are generally: read–read mutually exclusive, read–write mutually exclusive, and write–write mutually exclusive. Therefore, in multithreaded scenarios where reads far outnumber writes, lock separation avoids resource contention under high-concurrency reads and thus avoids context switching.
Lock segmentation
When using locks to guarantee the atomicity of a collection or a large object, we can consider decomposing the lock object further. For example, as I mentioned earlier, the pre- Java1.8 version of ConcurrentHashMap used lock striping.
3. Replace contended locks with non-blocking optimistic locks
CAS is a lock-free algorithm that guarantees consistency in read and write operations on a shared variable. A CAS operation has 3 operands: the memory value V, the old expected value A, and the new value B to be written. If and only if A equals V, it changes V to B; otherwise it does nothing. The CAS algorithm does not cause context switches. Java's Atomic package uses the CAS algorithm to update data, so no extra locking is needed.
In JDK1.6, the JVM divided the Synchronized lock into biased locking, lightweight locking, spin locking, and heavyweight locking, with the optimization path following this same order. When the JIT compiler dynamically compiles a synchronized block, it also optimizes the lock through lock elimination and lock coarsening.
wait/notify optimization
Calling the wait() method in a thread blocks it, waiting for notification from other threads (which call notify() or notifyAll()). Calling notify() or notifyAll() in a thread notifies other threads to return from wait().
The use of wait/notify leads to more context switches
Before a consumer acquires the lock for the first time, if it finds no goods to consume, it executes the Object.wait() method, which suspends the thread and puts it into a blocked state — this is one context switch.
After the producer acquires the lock and calls notifyAll(), the blocked consumer threads are awakened, and another context switch occurs here.
When an awakened waiting thread continues running, it must re-acquire the internal lock of the corresponding object. At this point it may need to compete with other newly arrived active threads for the internal lock, which may also cause context switches.
If multiple consumer threads are blocked at the same time, using notifyAll() wakes all blocked threads. But some goods are still out of stock, so waking the consumer threads for those goods too early may cause them to enter the blocked state again, leading to unnecessary context switches.
Optimize the use of wait/notify to reduce context switches
First, in different consumption scenarios, we can use Object.notify() instead of Object.notifyAll(). Because Object.notify() only wakes a specified thread and does not prematurely wake other blocked threads whose conditions are not met, it can reduce the corresponding context switches.
Second, after a producer calls Object.notify() / notifyAll() to wake other threads, it should release the internal lock as soon as possible, to avoid other threads holding the lock for a long time handling business operations after being woken and thus making the awakened threads wait again for the lock to be released when they re-acquire the corresponding internal lock.
Finally, to avoid long waits, we often use Object.wait(long) to set a wait timeout, but a thread cannot tell whether it returned because the wait timed out or because it was awakened by a notifying thread, so it tries to acquire the lock again, increasing context switches.
Here I suggest using a Lock combined with the Condition interface to replace the wait / notify of the Synchronized internal lock for wait/notification. This not only solves the above problem that Object.wait(long) cannot distinguish the cause of return, but also solves the problem of threads being awakened too early.
Set the thread pool size reasonably and avoid creating too many threads
For example, a thread pool created with Executors.newCachedThreadPool() reuses its internal idle threads to handle newly submitted tasks; if none are available, it creates new threads (not limited by MAX_VALUE). When faced with many long-running tasks, such a pool creates a very large number of worker threads, leading to frequent context switches. Therefore, this kind of thread pool is only suitable for handling many short, non-blocking tasks.
Using coroutines to achieve non-blocking waiting
A coroutine is something lighter than a thread. Compared with processes and threads managed by the operating system kernel, coroutines are completely controlled by the program itself, that is, they execute in user mode. Coroutines avoid the context switches caused by thread switching, greatly improving performance.
Reduce garbage collection in the Java virtual machine
When reclaiming old objects, the JVM garbage collectors (the serial collector and the ParNew collector) produce memory fragmentation, which requires memory compaction; in this process, live objects must be moved. Moving objects means their memory addresses change, so threads must be suspended before the move and awakened again after it completes. Therefore, reducing the frequency of JVM garbage collection can effectively reduce context switching.
Selection of concurrent containers
Map
Hashtable 🆚 ConcurrentHashMap
Hashtable uses the Synchronized lock to decorate methods such as put, get, and remove. Therefore, under high concurrency, both read and write operations involve heavy lock contention, bringing performance overhead to the system.
Compared with Hashtable, ConcurrentHashMap offers better concurrent performance while ensuring thread safety. In JDK1.7, ConcurrentHashMap used the segment lock Segment to reduce lock granularity, thereby optimizing concurrent lock operations.
In JDK1.8, ConcurrentHashMap underwent extensive changes and abandoned the Segment concept. Since the performance of the Synchronized lock was greatly improved after Java6, Java re-enabled the Synchronized lock in JDK1.8, using Synchronized with HashEntry as the lock granularity. This change simplified the data structure and made operations clearer and smoother.
As with the put method in JDK1.7, JDK1.8 uses CAS to add elements when there is no hash conflict; if there is a conflict, it locks the linked list with Synchronized and then performs the subsequent operations.
Although the overall performance of ConcurrentHashMap is better than that of Hashtable, in some scenarios it still cannot replace Hashtable. For example, in strong-consistency scenarios ConcurrentHashMap is not suitable, because its get, size and other methods do not use locks and it is weakly consistent, so a read may fail to immediately obtain written data.
ConcurrentHashMap 🆚 ConcurrentSkipListMap
When the amount of data is relatively large, the linked list in ConcurrentHashMap is converted into a red-black tree. Under concurrency, the balancing process during deletion and insertion involves a large number of nodes, so the cost of competing for lock resources is relatively high.
Skip-list operations are local and require fewer nodes to be locked, so performance is better in concurrent scenarios. A skip list consists of several levels of linked lists, each implementing an ordered linked-list index. Only the bottom level contains all the data; each level points upward through a pointer to the element with the same value in the upper level, and the data decreases level by level until the top level retains only a portion of the data.
This structure of a skip list uses space to trade for time to improve query efficiency. The program always starts querying from the top level and narrows the query range by comparing element values. We can understand the specific implementation of a skip list through the following figures.
If strong data consistency is required, use Hashtable; in most scenarios, where weak consistency is usually acceptable, ConcurrentHashMap is sufficient; if the data volume is in the tens of millions with many additions, deletions, and modifications, consider using ConcurrentSkipListMap.
List
Vector is also thread-safe based on the Synchronized lock. The Synchronized keyword decorates almost all externally exposed methods, so in scenarios where reads far outnumber writes, Vector experiences heavy lock contention, bringing performance overhead to the system.
By contrast, CopyOnWriteArrayList is provided by the java.util.concurrent package: it achieves lock-free read operations, while write operations work on a new copy of the underlying array — a read–write separation concurrency strategy. We can understand the specific implementation principle of CopyOnWriteArrayList through the following diagram.
JVM
JVM memory model
Heap
The heap is the largest memory space in the JVM; it is shared by all threads, and almost all objects and arrays are allocated in the heap. The heap is divided into the young generation and the old generation, and the young generation is further divided into the Eden and Survivor areas; finally, Survivor consists of From Survivor and To Survivor.
In Java6, the permanent generation was in the non-heap memory area; in Java7, the permanent generation's static variables and runtime constant pool were merged into the heap; and in Java8, the permanent generation was replaced by metaspace. The structure is shown below:
Program counter
The program counter is a very small memory space, mainly used to record the address of the bytecode executed by each thread. Branching, looping, jumping, exception handling, and thread recovery all rely on the counter.
Since Java is a multithreaded language, when the number of executing threads exceeds the number of CPU cores, threads compete for CPU resources in a time-slice round-robin. If a thread's time slice is used up, or its CPU resources are seized early for other reasons, the exiting thread needs a separate program counter to record the next instruction to execute.
Method area
The method area mainly stores information about classes loaded by the VM, including class information, the runtime constant pool, and the string constant pool. Class information in turn includes the class version, fields, methods, interfaces, and superclass.
When the JVM executes a class, it must go through loading, linking, and initialization, and linking includes three phases: verification, preparation, and resolution. When loading a class, the JVM first loads the class file. Besides descriptive information such as the class version, fields, methods, and interfaces, a class file also contains a constant pool (Constant Pool Table), which stores various literals and symbolic references generated during compilation.
Literals include strings (String a="b") and constants of primitive types (variables decorated with final). Symbolic references include the fully qualified names of classes and methods (for example, the class String, whose fully qualified name is Java/lang/String), as well as field names and descriptors and method names and descriptors.
After a class is loaded into memory, the JVM stores the contents of the class file constant pool into the runtime constant pool. During the resolution phase, the JVM replaces symbolic references with direct references (object index values).
For example, when a string constant in a class is in the class file, it is stored in the constant pool of the class file. After the JVM loads the class, the JVM puts the string constant into the runtime constant pool and, during the resolution phase, assigns an index value to the string object. The runtime constant pool is globally shared: multiple classes share one runtime constant pool, and identical strings from the constant pools of several class files exist only once in the runtime constant pool.
Like the heap, the method area is a shared memory region, so it is shared by threads. If two threads both try to access the same class information in the method area and the class has not yet been loaded into the JVM, only one thread is allowed to load it and the other must wait.
In the HotSpot VM, Java7 already moved the permanent generation's static variables and runtime constant pool into the heap, with the rest stored in the JVM's non-heap memory. Java8 removed the permanent generation implemented in the method area and replaced it with metaspace (class metadata), which is stored in local memory. The class metadata previously in the permanent generation is now in metaspace, while the permanent generation's static variables (class static variables) and runtime constant pool (runtime constant pool), as in Java7, were moved into the heap.
Virtual machine stack
The Java virtual machine stack is a thread-private memory space created together with the Java thread. When a thread is created, a thread stack is requested in the virtual machine stack to hold information such as method local variables, the operand stack, dynamic links, and return addresses, and to participate in method invocation and return. Each method invocation is accompanied by a stack-frame push, and each method return corresponds to a stack-frame pop.
Native method stack
The native method stack is similar in function to the Java virtual machine stack: the Java VM stack manages calls to Java functions, while the native method stack manages calls to native methods. Native methods are not implemented in Java but in C.
When we run the above code through Java, the entire processing flow of the JVM
1. The JVM requests memory from the operating system. The first step is to request a memory space from the OS through configured or default parameters, find the specific memory allocation table according to the memory size, and then assign the start and end addresses of the memory segment to the JVM, after which the JVM performs its internal allocation.
2. After the JVM obtains the memory space, it allocates the memory sizes for the heap, stack, and method area according to the configuration parameters.
Loading, verification, preparation, and resolution of a class file. In the preparation phase, memory is allocated for the class's static variables and initialized to the system's initial values.
4. After the previous step, the final initialization phase takes place. In this phase, the JVM first executes the constructor method. When a .java file is compiled into a .class file, the compiler collects all class initialization code — including static variable assignments, static blocks, and static methods — and combines it into the () method.
5. Execute the method. Start the main thread, execute the main method, and begin executing the first line of code. At this point a student object is created in the heap, and the object reference student is stored on the stack.
6. At this point another JVMCase object is created and the non-static method sayHello is called. The sayHello method belongs to the JVMCase object, so sayHello is pushed onto the stack and, through the student reference on the stack, calls the Student object in the heap. Then the static method print is called; the static method print belongs to the JVMCase class and is obtained from the static method area, then placed on the stack, also calling the student object in the heap through the student reference.
How can the garbage collection mechanism be optimized?
Garbage collection mechanism
Where does reclamation occur?
In the JVM's memory areas, the program counter, the VM stack, and the native method stack are private to threads — these 3 areas are created when a thread is created and destroyed when it is destroyed. Stack frames are pushed and popped as methods are entered and exited, and the amount of memory allocated to each stack frame is basically known once the class structure is determined, so the memory allocation and reclamation of these three areas are deterministic.
Therefore, garbage collection focuses on memory in the heap and the method area: collection in the heap is mainly of objects, while collection in the method area is mainly of obsolete constants and unused classes.
When can an object be reclaimed?
How does the JVM determine that an object can be reclaimed? Generally, if an object is no longer referenced, it can be reclaimed.
Reference counting algorithm: this algorithm uses an object's reference counter to determine whether the object is referenced. Each time the object is referenced, the counter is incremented by 1; each time a reference becomes invalid, the counter is decremented by 1. When the counter reaches 0, the object is no longer referenced and can be reclaimed. It should be emphasized that although reference counting is simple to implement and highly efficient, it suffers from the problem of circular references between objects.
Reachability analysis algorithm: GC Roots are the basis of this algorithm. The GC Roots are the root objects of all objects; when the JVM loads, it creates some ordinary object references to normal objects. These objects serve as the starting points for normal objects. During garbage collection, the search proceeds downward from these GC Roots; when there is no reference chain connecting an object to the GC Roots, the object is proven to be unusable. This is the algorithm used by the current HotSpot VM.
How are these objects reclaimed?
Automaticity: Java provides a system-level thread to track every allocated block of memory. When the JVM is in an idle loop, the garbage collector thread automatically checks every allocated memory block and reclaims each free block.
Unpredictability: once an object is no longer referenced, is it immediately reclaimed? The answer is unpredictable. It is hard to determine whether an unreferenced object will be reclaimed immediately, because the object may still remain in memory after the program ends.
Garbage collection threads run automatically in the JVM and cannot be forced by a Java program. The only thing we can do is call the System.gc method to "suggest" running the garbage collector, but whether it actually runs and when are still unpredictable.
GC performance metrics
Throughput
Here throughput refers to the ratio of the time spent by the application to the total system runtime. We can calculate GC throughput with this formula: total system runtime = application time +GC time. If the system runs for 100 minutes and GC takes 1 minute, the system throughput is 99%. GC throughput generally should not fall below 95%.
Pause time
Refers to the pause time of the application while the garbage collector is running. For a serial collector, the pause may be relatively long; with a concurrent collector, because the garbage collector and the application run alternately, the pause is shorter, but its efficiency may be lower than that of an exclusive collector, and system throughput is likely to decrease.
Garbage collection frequency
How often does garbage collection occur? Generally, the lower the frequency of garbage collection the better. Enlarging the heap can effectively reduce the frequency of garbage collection, but it also means more unreclaimed objects accumulate, which eventually increases the pause time during collection. Therefore, we only need to enlarge the heap appropriately to maintain a normal garbage collection frequency.
GC tuning strategies
1. Reduce the frequency of Minor GC
Because the young generation is small, the Eden area is quickly filled, leading to frequent Minor GC. We can therefore reduce the frequency of Minor GC by increasing the young generation space.
2. Reduce the frequency of Full GC
Avoid creating large objects: in ordinary business scenarios, we are used to querying a large object from the database at once for web-side display. For example, I once encountered a business operation that queried 60 fields at a time. If such a large object exceeds the maximum object threshold of the young generation, it is created directly in the old generation; even if it is created in the young generation, due to the limited memory space there it will move to the old generation after a Minor GC. Such large objects easily cause many Full GCs.
Increase the heap memory space: when the heap is insufficient, enlarging it and setting the initial heap size equal to the maximum heap size can also reduce the frequency of Full GC.
Choosing the right GC collector
Suppose we have a requirement that the response time of every operation must be within 500ms. In this case we usually choose a fast-response GC collector; both the CMS (Concurrent Mark Sweep) collector and the G1 collector are good choices.
When our requirements call for high system throughput, we can choose the Parallel Scavenge collector to improve throughput.
Framework
SpringBoot
Spring
Mybatis
SpringCloud Alibaba
Registry center Nacos
The heartbeat mechanism of the Nacos registry
Every 5 seconds after a microservice starts, its built-in Nacos client proactively sends a heartbeat packet (HeartBeat) to the Nacos server. The heartbeat packet contains information such as the current service instance's name, IP, port, cluster name, and weight.
Upon receiving a heartbeat packet, the naming module first checks whether Nacos already has this service instance based on the IP and port. If the instance information does not exist, the instance is registered in Nacos. Registration essentially means storing the new instance object in the "instance Map" collection;
If the instance information already exists, record the sending time of this heartbeat packet
Set the instance status to "healthy";
The naming module returns the heartbeat packet interval.
Push a "microservice status change" message;
How to deploy a Nacos cluster in a production environment
Nacos nodes expose ports 8848 and 7848. Port 8848 is used to expose APIs and synchronize data between cluster nodes, while port 7848 is used for node election to determine the cluster leader (Leader). Meanwhile, in a cluster environment, Nacos needs to persist built-in data such as application configurations, user permissions, and history information, so an additional MySQL database is required to provide unified storage.
How is the Leader node in a Nacos cluster elected
The Nacos cluster is implemented with the Raft algorithm. It is a relatively simple election algorithm used to elect the most important Leader node in the Nacos cluster.
Leader: the leader, the most important role in the cluster, used to issue instructions to other nodes.
Candidate: a contender, a node that participates in the election for Leader.
Follower: a follower, used to receive and process requests from the Leader or a Candidate.
When an election is triggered
Election after a Nacos node starts but before a Leader has been produced
Re-elect when the total number of cluster members changes;
Re-election when the Leader stops serving.
The data synchronization process between Nacos nodes
Step 1: The Follower automatically forwards the registration heartbeat packet to the Leader node;
Step 2: The Leader node completes the actual registration work;
Step 3: after completing registration, issue a "sync registration log" instruction to the other Follower nodes;
Step 4: all available Followers, after receiving the instruction, send an "ack" response to notify the Leader that the message has been received;
Step 5: after the Leader receives "ack" responses from more than half of the Follower nodes, it returns a "registration successful" response to the microservice.
In addition, for other invalid Follower nodes, the Leader keeps resending until all Followers are in sync with the Leader.
Load balancing Ribbon
How to configure the Ribbon load-balancing strategy
RoundRobinRule: the round-robin strategy, the default strategy of Ribbon. By default, if the server obtained in more than 10 attempts is unavailable, an empty server is returned.
RandomRule: the random strategy. If the randomly selected server is null or unavailable, it keeps looping to select again.
RetryRule: the retry strategy, which retries in a loop within a certain time limit. By default it inherits RoundRobinRule, and custom injection is also supported. After each selection, RetryRule checks whether the selected server is null or alive, and keeps selecting and checking within 500ms. The failure condition of RoundRobinRule is exceeding 10 attempts, while RandomRule has no concept of failure time as long as not all servers in the serverList are down.
BestAvailableRule: the least-connections rule. It traverses the serverList and selects the available server with the fewest connections.
AvailabilityFilteringRule: the availability filtering rule. It extends the round-robin rule: it first selects a server through the default round-robin, then checks whether that server is available without timeouts and whether the current connection count exceeds the limit, and returns it only if all checks succeed.
ZoneAvoidanceRule: the zone avoidance strategy. It extends the round-robin strategy: besides filtering out servers with timeouts and too many connections, it also filters out all nodes in zones that do not meet the requirements, always ensuring that round-robin is performed among service instances in one region/data center.
Service communication Feign
API gateway SpringCloud gateway
The execution flow of Spring Cloud Gateway
At startup, Spring Cloud Gateway listens on a specified port based on Netty Server (this port can be customized through the server.port property). When a front-end application sends a request to the gateway, it enters the Gateway Handler Mapping process, and the gateway decides which microservice will handle the request according to the predicates (Predicate) configured on the current Gateway.
Once the microservice is determined, the request proceeds into the Gateway Web Handler processing flow. In this flow, Gateway, according to the filter (Filters) configuration, passes the request in order to the Filter chain for pre-processing (Pre), which usually performs checks on the request — for example, whether it contains a specified header, whether the request's IP source is legitimate, and whether the included parameters are correct.
After the pre-processing (Pre) of the filter chain is complete, the request is forwarded by Gateway to the actual microservice instance for processing. The microservice returns response data, which travels back along the original path to be post-processed (Post) by the filter chain configured on Gateway. Post-processing usually performs additional handling of the response, such as writing the process to logs, attaching extra response headers, or traffic monitoring.
Throughout the processing, predicates (Predicate) and filters (Filter) play important roles: the predicate determines the path matching rule, letting Gateway decide which microservice to apply, while the Filter performs substantial pre- and post-processing on the request or response.
Configuration center Nacos
Configuration hot-loading technology
Nacos supports configuration hot loading, allowing new configuration items to be reloaded directly at runtime without a manual restart. First let's understand the mechanism behind hot loading.
Nacos uses the Pull mode, but not a simple Pull — it is a long-polling mechanism. The client periodically initiates Pull requests in a long-polling manner to check whether the server's configuration has changed; if it has, the client obtains the latest configuration from the changed data. The so-called long polling means that after the client initiates a polling request, if the server has a configuration change, it returns immediately.
If, after the client initiates a Pull request, it finds that the server's configuration is consistent with the client's, the server first "holds" the request — that is, after receiving the connection, the server does not return a result for a specified period of time until a configuration change occurs within that period, at which point it returns the previously "held" request, as shown in the figure:
Nacos uses the Pull mode, but not a simple Pull — it is a long-polling mechanism. The client periodically initiates Pull requests in a long-polling manner to check whether the server's configuration has changed; if it has, the client obtains the latest configuration from the changed data. The so-called long polling means that after the client initiates a polling request, if the server has a configuration change, it returns immediately.
If, after the client initiates a Pull request, it finds that the server's configuration is consistent with the client's, the server first "holds" the request — that is, after receiving the connection, the server does not return a result for a specified period of time until a configuration change occurs within that period, at which point it returns the previously "held" request, as shown in the figure:
After receiving a request, the Nacos server first checks whether the configuration has changed. If not, it sets a scheduled task to execute after a delay of 29.5s and adds the current client's long-polling connection to the allSubs queue. At this point there are two ways to trigger the return of the connection result:
The first is that after waiting 29.5s, an automatic check mechanism is triggered, and regardless of whether the configuration has changed, the result is returned to the client. The 29.5s is exactly the duration for which this long connection is held.
The second is that at any moment within 29.5s, the configuration is modified through the Nacos Dashboard or API. This triggers an event mechanism: the task listening for this event traverses the allSubs queue, finds the ClientLongPolling task corresponding to the changed configuration item, and returns the changed data through that task's connection, completing a "push" operation.
System protection Sentinel
The execution flow of Sentinel
Sentinel Core establishes a connection with Sentinel Dashboard;
To continuously receive data from the Dashboard, Sentinel Core listens on port 8719 on the microservice instance host, and it reports this 8719 port in heartbeat packets rather than the microservice's own 80 port.
After Sentinel Dashboard receives a heartbeat packet, the AppName, IP, and port information from Sentinel Core is encapsulated into a MachineInfo object and put into a ConcurrentHashMap stored in the JVM's memory for later use.
Sentinel Dashboard delivers new protection rules to Sentinel Core;
If new protection rules are set in the Dashboard page, the information of microservice instances that meet the requirements is first extracted from the current MachineInfo, then the new rules are packaged and pushed to the microservice instances' Sentinel Core through the Dashboard's built-in transport module. After receiving the new rules, Sentinel Core updates the local rules in the microservice application, and these new rules are stored in the microservice instance's JVM memory.
Sentinel Core applies the new protection rules and performs actions such as flow control and circuit breaking.
Sentinel Core provides a core interceptor SentinelWebInterceptor for service flow control and circuit breaking. By default this interceptor intercepts all requests /** and then starts the chained processing flow. Each node that processes a request is called a Slot, and multiple slots are connected to form a processing chain. During the flow of a request, if any Slot fails validation, a BlockException is generated, the request processing chain is interrupted, and the exception message "Blocked by sentinel" is returned.
NodeSelectorSlot collects resource paths and stores the call paths of these resources in a tree structure, for flow control and degradation based on call paths;
ClusterBuilderSlot stores statistical information about resources and caller information, such as the resource's RT (runtime), QPS, thread count, etc. This information is used as the basis for multi-dimensional flow control and degradation;
StatistcSlot records and counts runtime information of different dimensions;
SystemSlot controls the total entry traffic based on system status, such as CPU and memory;
AuthoritySlot performs blacklist and whitelist control;
FlowSlot performs flow control according to preset flow-control rules and the state previously counted by the slot;
DegradeSlot performs circuit breaking and degradation based on statistics and preset rules.
ClusterBuilderSlot stores statistical information about resources and caller information, such as the resource's RT (runtime), QPS, thread count, etc. This information is used as the basis for multi-dimensional flow control and degradation;
StatistcSlot records and counts runtime information of different dimensions;
SystemSlot controls the total entry traffic based on system status, such as CPU and memory;
AuthoritySlot performs blacklist and whitelist control;
FlowSlot performs flow control according to preset flow-control rules and the state previously counted by the slot;
DegradeSlot performs circuit breaking and degradation based on statistics and preset rules.
Sentinel uses a sliding-window algorithm to count access volume
The idea of the sliding window algorithm is to divide the whole time period into equal segments, count each independently, and then aggregate the statistics. It is widely used in various flow-control scenarios.
The circuit-breaking process of Sentinel
Subtopic
The figure below clearly illustrates the circuit-breaking process of Sentinel:
Set the trigger condition for circuit breaking: when more than 20% of requests to an interface fail, circuit breaking is triggered;
In the circuit-broken state, all requests to that interface within a few seconds directly throw a BlockException and are rejected.
After the circuit breaker period, the next request accesses the interface again; the interface is now in the "half-open state", and subsequent processing falls into two cases.
If the current request is processed successfully, the interface returns to normal.
If the current request fails, the circuit breaking continues.
Set the trigger condition for circuit breaking: when more than 20% of requests to an interface fail, circuit breaking is triggered;
In the circuit-broken state, all requests to that interface within a few seconds directly throw a BlockException and are rejected.
After the circuit breaker period, the next request accesses the interface again; the interface is now in the "half-open state", and subsequent processing falls into two cases.
If the current request is processed successfully, the interface returns to normal.
If the current request fails, the circuit breaking continues.
Message queue RocketMQ
Deploy a RocketMQ cluster
Multi- Master mode is the simplest to configure and also the most widely used. Its advantage is that the failure or restart of a single Master for maintenance has no impact on applications; when disks are configured as RAID10, even if a machine fails unrecoverably, synchronous-flushed messages are not lost because RAID10 disks are very reliable, and performance is the highest. The drawback is that while a machine is down, the unconsumed messages on it cannot be subscribed to until the machine recovers, so message real-time performance is affected.
Multi- Master multi- Slave asynchronous replication mode. Each Master is configured with one Slave, forming multiple Master–Slave pairs, and HA uses asynchronous replication. There is a short millisecond-level message delay between master and slave; even if a disk is damaged, only a small number of messages are lost, and message real-time performance is unaffected. Meanwhile, after a Master fails, consumers can still consume from the Slave, and this process is transparent to the application with no manual intervention. Performance is almost the same as multi- Master mode. The drawback is that if the Master fails and the disk is damaged, a small number of messages will be lost.
Multi- Master multi- Slave synchronous dual-write mode: HA uses synchronous dual writing, that is, success is returned to the application only after both master and slave have written successfully. This mode has no single point of failure for either data or service; when the Master goes down, there is no message delay and both service availability and data availability are very high. The drawback is that performance is about 10% lower than asynchronous replication mode, the execution time for sending a single message is slightly longer, and in the current version the slave cannot automatically switch to master after the master node fails.
Dual-Master cluster
In the dual- Master architecture, a new role appears: NameServer (the naming server). NameServer is a lightweight routing registry built into RocketMQ, supporting dynamic registration and discovery of Brokers. After a Broker starts, it automatically sends heartbeat packets to NameServer to announce that it is online. The Provider obtains routing information from NameServer and then establishes a long connection with the designated Broker to complete data transmission.
To avoid a single-node bottleneck, NameServer is usually deployed on two or more instances as high-availability redundancy. NameServer itself is stateless and its instances do not communicate with each other, so when configuring a Broker cluster you must configure all NameServer nodes to ensure state synchronization.
Log management SLS
Distributed transaction Seata
Scheduled task SchedulerX
Distributed storage OSS
Storage
Mysql
High availability HA
mysqldump full backup
Binlog incremental backup
How is SQL executed in a database?
When a SQL statement is executed in a database, it is first parsed syntactically into an AST, then the AST is converted into a logical execution plan, which after optimization is converted into a physical execution plan, and after further optimization the query is executed according to the optimized physical plan. Almost all databases consist of two parts: an executor and a storage engine. The executor performs computation, and the storage engine stores data.
Why shouldn't a primary key be too long? Because every index in a table stores the value of the primary key, an overlong primary key makes every index large. Another example: once we understand the optimization process of execution plans, it is easy to see why sometimes an index exists but is not used — when optimizing the physical execution plan, the database estimates that skipping the index and doing a full table scan is the better choice.
Transaction isolation levels
Read uncommitted
A write lock is held throughout the transaction scope, but no read lock is applied; reads do not require a read lock. Therefore it is impossible to prevent reading data that another transaction is writing (with a write lock) but has not yet committed (dirty data), because the absence of a read lock means it will not be blocked by another transaction's write lock, resulting in dirty reads.
Read committed
A write lock is held throughout the transaction scope, but the read lock is not held throughout — it is released as soon as the read finishes. Therefore, if data is read and another transaction then modifies it, this cannot be prevented, leading to different values on two reads — the non-repeatable read problem.
Repeatable read
Write locks and read locks are held throughout the transaction scope, but no range lock is applied. Therefore, if new data is inserted into a range, it cannot be locked and phantom reads occur: previously there were 5 rows, and after a new matching row is inserted there are 6, like an illusion.
Serializable
Write locks, read locks, and range locks are held throughout the transaction scope
Indexes
Indexing principles of InnoDB
The InnoDB storage engine uses the table's primary key as the primary key index by default; this primary key index is the clustered index (Clustered Index). If no primary key is defined for the table, InnoDB generates a hidden 6-byte primary key ID value as the primary key index, and the created primary key index uses the B+Tree index by default.
MySQL execution plan
The type field of EXPLAIN
ALL (full table scan)
index (full index scan)
range (index range scan)
ref (non-unique index scan)
eq_ref (unique index scan)
const (primary key or unique index scan returning only one row)
Cases where indexes become invalid
If an expression is computed in an index, the index becomes invalid
If a function is used on an index, the index becomes invalid
When Like is used for a fuzzy query, the character after Like cannot be %
When using a composite index, note the leftmost prefix principle
Techniques for building efficient indexes
Prefix index optimization
When indexing fields with very long strings, using a prefix index can help reduce the size of index entries.
Covering index optimization
A covering index is one where all fields queried in the SQL can be found in the leaf nodes of the index B+tree. The record is obtained from the secondary index without needing to query the clustered index.
Composite index
Match indexes in a leftmost-first manner
Distributed locks
Pessimistic lock
Lock the row with a database row lock: select for update
May cause deadlock problems
Optimistic lock
The version-number approach: first add an int field ver to the database, then retrieve the ver value in the SELECT, and finally, when performing the UPDATE, check whether the ver value is the same as the version value obtained in step 2.
If the number of records updated is 1, it means success; if it is 0, the record has already been updated by another application, and exception handling is needed.
Hot–cold separation
How to determine whether data is cold or hot?
It mainly uses a combination of 1 or more fields in the main table as the distinguishing identifier. Such a field can be a time dimension or a status dimension.
How to trigger hot–cold data separation?
Modify the business code of write operations: recommended when the business code is relatively simple and hot and cold data are not distinguished by time
Monitor database change logs: recommended when the business code is complex and risky to change, and hot and cold data are not distinguished by time
Periodically scan the database: recommended when distinguishing hot and cold data by time.
How to delete large amounts of data in batches?
Find the largest order ID among the qualifying historical orders, then convert the delete condition in the delete statement into batch deletion by primary key.
select max(id) from orderswhere timestamp < SUBDATE(CURDATE(),INTERVAL 3 month);delete from orderswhere id <= ?order by id limit 1000;
In this way, each deletion uses a primary-key comparison as the condition. In the InnoDB storage engine of MySQL, the table data structure is a B+ tree organized by primary key, and a B+ tree is inherently ordered, so not only is lookup very fast, but no additional sorting is needed either.
Why must a sort be added to a delete statement? Because after sorting by ID, each batch of records we delete is basically a contiguous batch of IDs. Due to the ordering of the B+ tree, records with similar IDs are roughly stored together in the physical file on disk, so deletion is more efficient and it is easier for MySQL to reclaim pages.
After a large amount of historical order data has been deleted, if you check the disk space occupied by MySQL, you will find that it has not become smaller. Why? This is also related to the physical storage structure of InnoDB. Although logically each table is a B+ tree, physically each record is stored in a disk file, and these records are organized into a B+ tree through location pointers. When MySQL deletes a record, it can only find the record's position in the file, mark that area of the file as free, and then modify some related pointers in the B+ tree to complete the deletion. In fact, the deleted record still lies at that position in the file, so disk space is not released.
If database disk space is tight and you must free it, you can execute OPTIMIZE TABLE to release storage space. For InnoDB, executing OPTIMIZE TABLE actually rebuilds the table, and the table remains locked during execution — meaning that orders cannot be placed at that time, which should be noted. In addition, this optimization has a prerequisite: MySQL must be configured with one tablespace per table (innodb_file_per_table = ON). If all tables are stored together, executing OPTIMIZE TABLE will not free disk space.
During table rebuilding, indexes are also rebuilt, so both table data and index data become more compact: disk usage is smaller and query efficiency improves. For tables with frequent insertions and deletions of large amounts of data, if table locking is acceptable, periodically executing OPTIMIZE TABLE is very worthwhile.
If our system can tolerate a temporary service outage, the fastest approach is this: directly create a temporary order table, copy the current orders into it, rename the old order table, and finally rename the temporary table to the official order table. This is equivalent to manually rebuilding the order table, but without the lengthy process of deleting historical orders.
-- Create a new temporary order table: create table orders_temp like orders;
-- Copy the current orders to the temporary order table: insert into orders_temp select * from orders where timestamp >= SUBDATE(CURDATE(),INTERVAL 3 month);
-- Modify and replace the table name: rename table orders to orders_to_be_droppd, orders_temp to orders;
-- Drop the old table: drop table orders_to_be_dropp
Read–write separation
The principle of master–slave replication
Write Binlog: the master writes the binlog, commits the transaction, and updates the locally stored data.
Synchronize Binlog: replicate the binlog (log dump thread) to all slaves, and each slave writes the binlog into a temporary log (relay log).
Replay Binlog: the slave also creates a SQL thread to read the contents of the relay log, replay the binlog, and update the stored data.
Master–slave replication mode
Synchronous replication: the transaction thread must wait for successful replication responses from all slaves.
Asynchronous replication: the transaction thread does not wait at all for successful replication responses from the slaves.
Semi-synchronous replication: a replication mode added after MySQL 5.7, lying between the two. The transaction thread does not need to wait for successful replication responses from all slaves; a partial response is enough. For example, in a cluster with one master and two slaves, as soon as the data is successfully replicated to any one slave, the master's transaction thread can return to the client.
The parameter "rpl_semi_sync_master_wait_slave_count" means "wait until data has been replicated to at least N slave nodes before returning". The larger this number is configured, the smaller the risk of data loss, but the worse the cluster's performance and availability. It can be set as high as the number of slave nodes, in which case it becomes synchronous replication. Normally, leaving it at the default value 1 is enough: the performance loss is minimal and availability is high, and as long as one slave is alive, master reads and writes are unaffected.
Another important parameter is "rpl_semi_sync_master_wait_point", which controls whether the master's transaction thread waits for replication before committing the transaction (AFTER_SYNC) or after committing (AFTER_COMMIT). The default is AFTER_SYNC, that is, wait for replication first and then commit the transaction, which loses no data at all. AFTER_COMMIT offers better performance and does not lock tables for a long time, but still carries the risk of data loss on a crash.
If the thread that commits a transaction on the master times out waiting for replication, the transaction is still committed normally. Moreover, MySQL automatically downgrades to asynchronous replication mode until enough slaves (rpl_semi_sync_master_wait_no_slave) have caught up with the master, at which point semi-synchronous replication is restored. If the master goes down during this period, there is still a risk of data loss.
Replicated state machine
The goal is to achieve state consistency across all nodes in the cluster through log replication and replay.
In Redis Cluster, a full backup is called a Snapshot, and the operation log is called the backlog.
Elasticsearch uses the translog, and the principle and implementation of its data backup and recovery are exactly the same.
Resolving master–slave replication delay
Solve it with caching
Data redundancy
Query the master database directly
Database and table sharding
Database sharding
The performance of a single database cannot meet the requirements
Table sharding
The large data volume causes slow transaction execution
Hash sharding
Modulo operation
Scalability is very poor: when the number of nodes changes, the Hash must be recalculated, leading to large-scale data migration.
Consistent Hash
It refers to mapping both storage nodes and data onto a hash ring connected end to end. Storage nodes can generally be hashed based on their IP addresses, and the storage location of data is the first storage node found clockwise starting from the position where the data maps on the ring.
The advantage is that data can be distributed fairly evenly across nodes, and its concurrent write performance is also good.
Uneven distribution of cache nodes on the ring puts greater pressure on some nodes; when a node fails, all the accesses it was responsible for are shifted to the next node, putting pressure on that node.
Consistent Hash based on virtual nodes
Solves the problem in consistent hashing where removing the previous node causes the next node to be overloaded
It computes multiple Hash values for a cache node and distributes them to different positions on the ring. This achieves even data distribution, and when a node fails or leaves, the Keys it previously held are distributed to other nodes in a more balanced way, thus avoiding avalanches.
The single-hotspot problem still exists
Range sharding
Based on shard metadata
How to ensure the availability and data consistency of the shard metadata service?
Build a dedicated service cluster for metadata and replicate data through a consensus algorithm
It shifts the problems of high availability and data consistency of the metadata service to an external coordination component, such as an ETCD cluster.
Build a cluster service for shard metadata and store data shard information through ETCD.
Each data storage instance node periodically synchronizes heartbeat and shard information with the metadata service cluster.
When a request from a caller arrives, the metadata service node only needs to ensure high availability and caching.
What is the consensus algorithm of ETCD
ETCD uses the Raft algorithm
Raft is an implementation of Multi Paxos. It achieves consensus on a series of values by making the leader authoritative in all matters, but not every node can be elected Leader. The Raft algorithm restricts the election of the Leader: only the node with the most complete log can be elected. Because ETCD chose Raft, it provided a reliable engineering reference for the industry, and more engineering implementations chose to build on Raft — for example, TiDB is an optimization based on the Raft algorithm.
Program-side modifications
Proxy mode
Client mode
Solving the problems introduced by database and table sharding
Once a sharding key is introduced, all our subsequent queries must include this field to locate the database and table holding the data; otherwise we can only send the query to all databases and tables.
Another problem is that some database features may become very difficult to implement. For example, a multi-table JOIN can be done with a single SQL statement in one database, but after splitting into multiple databases you cannot execute SQL across databases. Fortunately, we do not have much need for JOIN; even when we do, we generally fetch the data from the two tables and filter it in business code — somewhat complex, but feasible. Another example: before sharding, querying the total number of records only required a count() in SQL; now that data is scattered across multiple databases and tables, we may need other approaches, such as storing the count data in a separate table or recording it in Redis.
ID generator (distributed ID)
Snowflake algorithm
The core idea of Snowflake is to divide a 64bit binary number into several parts, each storing data with a specific meaning, such as a timestamp, machine ID, sequence number, and so on, ultimately generating a globally unique ordered ID. Its standard algorithm is as follows:
From the figure above we can see that a 41-bit timestamp can support about pow(2,41)/1000/60/60/24/365 years, approximately 69 years, which is sufficient for a system. If your system is deployed in multiple data centers, the 10-bit machine ID can be further divided into a 2–3-bit IDC identifier (supporting 4 or 8 IDC data centers) and a 7–8-bit machine ID (supporting 128–256 machines); the 12-bit sequence number means that each node can generate at most 4096 IDs per millisecond.
Disadvantages
There are some drawbacks, the biggest being that it depends on the system timestamp: if the system time is inaccurate, duplicate IDs may be generated. So if we find the system clock is inaccurate, we can have the ID generator temporarily refuse to issue IDs until the clock is correct.
In addition, if the QPS of requests to the ID generator is not high — for example, it issues only one ID per millisecond — the last digit of the generated ID will always be 1. Then, if the ID is used as the partition key when sharding databases and tables, the data will be unevenly distributed. This is a pitfall I have encountered in real projects, and there are two main solutions:
1. The timestamp records seconds rather than milliseconds, so that more IDs can be issued within a time interval, avoiding uneven data distribution when sharding databases and tables. 2. The starting number of the generated sequence can be randomized — 21 in this second and 30 in the next — so that it is balanced as much as possible.
How to replace a database without downtime?
Deploy a synchronization program to copy data from the old database to the new one and keep them synchronized in real time;
Binlog real-time data synchronization
Deploy the dual-write order service, reading from and writing to only the old database
The DAO layer needs the following changes: support dual writes to both the old and new databases, and reserve a hot-switch switch that can control three write states: writing only to the old database, writing only to the new database, and synchronous dual writing. Support reading from both the old and new databases, and likewise reserve a hot-switch switch to control whether reads go to the old or the new database.
Then deploy the new version of the order service. At this point, the order service still only reads from and writes to the old database, and does not read from or write to the new one. Let this new version of the order service run stably for at least one to two weeks. During this period, in addition to verifying the stability of the new order service, it is also necessary to verify whether the data in the old and new order databases is consistent. During this process, if there is a problem with the new order service, it can be taken offline immediately and rolled back to the old version of the order service.
Enable dual writing and stop the synchronization program at the same time
The business logic of dual writing must be: write to the old database first, then the new one, and the result of writing to the old database prevails.
If the write to the old database succeeds but the write to the new one fails, return success but log the event; we will use this log later to verify whether the new database still has problems. If the write to the old database fails, return failure directly and do not write to the new database. The reason is that the new database must not be allowed to affect the availability and data accuracy of existing business. If a problem occurs in the above process, dual writing can be disabled, rolling back to reading and writing only the old database.
After switching to dual writing, the data in the new and old databases may be inconsistent for two reasons: first, it is hard to seamlessly connect stopping the synchronization program and starting dual writing; second, the dual-write strategy does not guarantee strong consistency between the old and new databases. At this point we need to deploy a comparison and compensation program, which compares recent data changes in the old database, checks whether the data in the new database is consistent, and compensates if it is not.
Start the comparison and compensation program to ensure that the data in the old and new databases is exactly the same;
After enabling dual writing, the system must run stably for at least several weeks, during which we must continuously check to ensure that there is no case where a write to the old database succeeds but the write to the new one fails. If the comparison program also finds no inconsistency between the old and new databases, we can consider that the data in the two databases has remained synchronized.
Gradually shift read requests to the new database;
Next, read requests can be shifted to the new database little by little, in a way similar to a canary release. Likewise, if problems occur during this period, you can switch back to the old database. Once all read requests have been switched to the new database, both reads and writes are effectively on the new database and the actual switch is complete, though follow-up steps remain.
Take the comparison and compensation program offline, disable dual writing, and switch both reads and writes to the new database;
After another period of stability, the comparison program can be stopped and the write state of the order service changed to writing only to the new database. At this point the old database can be taken offline. Note that throughout the entire migration process, only this step is irreversible. However, the main operation here is simply removing the old database that is no longer in use; nothing changes for the new database in service, so the possibility of actual problems is already very small.
Using NoSQL to improve write performance
For the InnoDB storage engine of MySQL, updating binlog, redolog, and undolog are all sequential IO operations, while updating datafile and index files is random IO. To reduce the occurrence of random IO, relational databases have made many optimizations — for example, writing to memory first and then flushing to disk in batches — but random IO still occurs.
In the InnoDB engine, indexes are organized as B+ trees, and the MySQL primary key is a clustered index (a type of index in which data and index data are stored together). Since data and index data are stored together, when inserting or updating data we need to find the insertion position and then write the data to that specific position, which generates random IO. Moreover, once a page split occurs, data movement is inevitable, greatly degrading write performance.
An LSM-tree-based storage engine used by many NoSQL databases
The LSM tree (Log-Structured Merge Tree) sacrifices some read performance for high write performance; Hbase, Cassandra, and LevelDB all use this algorithm as their storage engine.
Its idea is simple: data is first written into an in-memory structure called MemTable, where data is sorted by the written Key. To prevent data in the MemTable from being lost due to power failure or restart, data is usually backed up on disk by writing a Write Ahead Log.
When a MemTable accumulates to a certain size, it is flushed to generate a new file, which we call an SSTable (Sorted String Table). When the number of SSTables reaches a certain threshold, we merge these SSTables to reduce the number of files; since SSTables are all sorted, the merge is also fast.
When reading data from an LSM tree, we first look in the MemTable; if the data is not found, we then look in the SSTable. Because the stored data is sorted, lookup efficiency is very high; only because the data is split into multiple SSTables is read efficiency lower than that of a B+ tree index.
Subtopic
Massive data scenarios
How is clickstream data stored?
The first approach is to use Kafka for storage
Kafka provides "unlimited" message accumulation capability and extremely high throughput, which can satisfy most of our requirements for storing raw data. When writing clickstream data, each raw data collection service acts as a producer and simply sends data to Kafka. Downstream computing tasks can act as consumers to subscribe to messages, or read data by time or by offset. Moreover, as a de facto standard, Kafka is highly compatible and well integrated with most open-source software in the big data ecosystem; most computing platforms such as Flink and Spark provide components for direct Kafka access.
The second approach is to use HDFS for storage
Using HDFS to store data is also simple: write the raw data into text files one by one and save them in HDFS. We need to organize the directory structure and file names by time and business attributes so that downstream computing programs can read them. For example, "click/20200808/Beijing_0001.csv" represents clickstream data collected from users in Beijing on August 8, 2020, and is the first file of that day.
For the specific scenario of storing massive raw data, the throughput of HDFS is far inferior to that of Kafka. Calculated per node, Kafka's throughput can easily reach several hundred megabytes per second, while HDFS only reaches about a hundred megabytes. This means that to achieve the same throughput, using HDFS requires several times as many servers as Kafka.
But HDFS has its advantages too. The first is that it can provide truly unlimited storage capacity: if storage space is insufficient, horizontal scaling solves the problem. Another advantage is that HDFS provides stronger data query capabilities than Kafka. Kafka can only retrieve data by time or by offset, whereas HDFS together with Hive directly supports querying data with SQL. Although query performance is relatively poor, the query capability is far stronger than that of Kafka.
How to query massive data faster?
If your system's data volume is below the GB scale, MySQL is still worth considering, because its query capability is sufficient for most analytical system requirements. It can also share a database with the online business system, avoiding ETL (data extraction), which saves effort and offers good real-time performance. Still, I would remind you to configure a separate MySQL instance for the analytical system to avoid affecting online business.
If the data scale has exceeded the limits of MySQL, you can choose some columnar databases such as HBase, Cassandra, and ClickHouse. These products have very good query performance for massive data; when used correctly, queries over 10GB-scale data can basically return in seconds. The price of high performance is reduced functionality: these databases have some restrictions on how data is organized and are not as flexible as MySQL in query methods. Most require you to understand their characteristics well and use them in the prescribed way to achieve the expected performance.
Another option worth considering is Elasticsearch (ES). ES was originally a storage product born for search, but it also supports the storage and querying of structured data. Since its data is all stored in memory and it supports distributed parallel queries similar to Map-Reduce, its query performance for massive structured data is also very good.
When the data scale exceeds the TB level, no storage system can make statistical analysis of such a large volume fast; the performance bottleneck at that point is disk IO and network bandwidth. In this case, real-time query and analysis are simply not feasible. The solution is always to periodically aggregate and precompute the data, save the results, and perform secondary queries on the results when needed. Data of this scale is generally stored in HDFS, together with big data ecosystem products such as Map-Reduce, Spark, and Hive for data aggregation and computation.
Database
Database connection pools
Database connection pool parameters
If the current number of connections is less than the minimum, create a new connection to handle the database request;
If there are idle connections in the connection pool, reuse them;
If there are no connections in the idle pool and the current connection count is less than the maximum, create a new connection to handle the request;
If the current number of connections is greater than or equal to the maximum, wait for an old connection to become available for the time set in the configuration (the C3P0 connection pool configuration is checkoutTimeout);
If the wait exceeds this set time, an error is thrown to the user.
Connection liveness detection mechanism
1. Start a thread to periodically check whether the connections in the connection pool are available. For example, use the connection to send a "select 1" command to the database and see whether an exception is thrown; if an exception is thrown, remove the connection from the pool and try to close it. Currently the C3P0 connection pool can use this approach to check connection availability, and it is the method I recommend.
2. After obtaining a connection, first verify that the connection is available before executing the SQL statement. For example, the testOnBorrow configuration item of the DBCP connection pool controls whether this validation is enabled. This approach introduces extra overhead when acquiring connections, so try to avoid enabling it in production systems; it can be used on test servers.
ElasticSearch
Microservices
RPC
A complete RPC flow
The caller continuously serializes the request parameter objects into binary data and transmits them to the service provider over TCP;
The service provider receives binary data from the TCP channel;
According to the RPC protocol, the service provider separates different request data from the binary data, deserializes the binary data back into request objects, finds the corresponding implementation class, and performs the actual method invocation.
Then the service provider serializes the execution result and writes it back to the corresponding TCP channel;
After receiving the response data packet, the caller deserializes it into a response object.
RPC serialization methods
JSON: the most widely used, and requires more memory during communication
Hessian: a compact binary serialization framework that performs well in terms of performance and size
Protobuf: after serialization its size is even smaller than JSON and Hessian, and its compatibility is also quite good.
RPC network communication performance
Synchronous blocking I/O (BIO)
Whenever a client sends a connection request to the server, the server starts a new thread to handle the read and write operations of that connection — that is, each Socket corresponds to an independent thread, with a 1:1 ratio between client Sockets and server worker threads. This exhausts server resources and makes high-concurrency network development impossible.
The number of Socket connections is limited, so it is not suitable for high-concurrency scenarios;
There are two blocking points: waiting for a user to initiate a connection and waiting for a user to send data.
Synchronous non-blocking I/O
I/O multiplexing (NIO)
System calls such as select, poll, and epoll in Linux are all I/O multiplexing mechanisms.
The 3 threading models of Reactor are the single-threaded Reactor model, the multi-threaded Reactor model, and the master–slave Reactor model.
and asynchronous I/O (AIO)
Debugging network parameters
There are some recommended empirical values here. For example, set tcp_nodelay to true. Some parameters need to be tuned at runtime, such as the sizes of the receive and send buffers and the size of the client connection request buffer queue (back log).
Registry center
Nacos
Configuration center
Nacos
Full-link monitoring
SkyWalking
The data collection mechanism of SkyWalking
The service has a local cache in which all collected log data is first stored; a background thread then asynchronously sends the logs in the cache to the SkyWalking server. Through this mechanism, at the log instrumentation points we do not need to wait for the server to receive the data, so system performance is not affected.
What happens if the SkyWalking server goes down?
If the server goes down, in theory the data in the log cache will have no consumer. Could this cause data to accumulate more and more and eventually blow up the memory?
In SkyWalking, we set the cache size. If this data exceeds the cache size, the Trace will not be saved, so we know whether the memory will be blown up.
In SkyWalking, we set the cache size. If this data exceeds the cache size, the Trace will not be saved, so we know whether the memory will be blown up.
How to control the volume of log data when traffic is high?
SkyWalking configures a sampling ratio on each server. For example, setting it to 100 means that 1% of request data will be collected, as shown in the following code.
Once forceSampleErrorSegment is enabled, all data is collected when errors occur, and sampleRate no longer applies to erroneous requests.
It is best to keep the sampleRate of all related services consistent. If A calls B and their sampling rates differ, a Trace may not be linkable.
Log retention time
Configuring scheduled cleanup in SkyWalking
Cluster configuration: how to ensure high availability?
SkyWalking's receiver service (Receiver) and aggregator service (Aggregator) support cluster mode. Meanwhile, in a clustered service, multiple service nodes need coordination services to coordinate the relationships among them; they support Kubernetes-ZooKeeper, Consul, Etcd, and Nacos (basically all open-source coordination services are supported).
Circuit breaking
Hystrix
Thread isolation mechanism
The Hystrix approach is to maintain a thread pool for each dependent interface (several interfaces can also be configured to share one), and then isolate each service's calls to dependent interfaces through the thread pool size, queue length, and so on.
Circuit breaker mechanism
Under what conditions is the circuit breaker triggered?
In the Hystrix mechanism, we configure a continuously rolling statistical time window metrics.rollingStats.timeInMilliseconds. Within each window, when the total number of interface calls reaches circuitBreakerRequestVolumeThreshold, and the ratio of timed-out or exceptional calls to total calls exceeds circuitBreakerErrorThresholdPercentage, the circuit breaker is triggered.
What happens when the circuit breaks?
If the circuit breaker is triggered, during the circuitBreakerSleepWindowInMilliseconds period we no longer call the external interface, but directly invoke a local fallback method.
How to recover after the circuit breaks?
When circuitBreakerSleepWindowInMilliseconds elapses, Hystrix first lifts the restriction on the interface (circuit breaker state HALF-OPEN), then tries to call the interface with 1 request. If the call succeeds, normal operation resumes (circuit breaker state CLOSED); if the call fails or times out, it must wait another circuitBreakerSleepWindowInMilliseconds before retrying.
The process of switching among the three states
When the number of failed calls accumulates to a certain threshold, the circuit breaker state switches from closed to open. In typical implementations, a single successful call resets the failure count.
When the circuit breaker is in the open state, we start a timeout timer; when it expires, the state switches to half-open. You can also set a timer to periodically probe whether the service has recovered.
When the circuit breaker is in the half-open state, requests can reach the backend service. If a certain number of successes accumulates, the state switches to closed; if a call fails, it switches to open.
Rolling (sliding) time window
Degradation
Switch-based degradation refers to pre-embedding some "switches" in the code to control the return values of service calls.
For read scenarios, we generally adopt the strategy of directly returning degraded data. For example, if database pressure is high, we can choose to read only the cache during degradation and not the database; if a non-core interface fails, we can directly return "service busy" or fixed degraded data.
For scenarios that poll for data, such as fetching the unread count every 30 seconds, you can reduce the fetch frequency (e.g. to once every 10 minutes).
For write-data scenarios, we generally consider converting synchronous writes to asynchronous writes, sacrificing some data consistency to guarantee system availability.
Only switches that have been drill-tested are useful switches
Distributed transactions
2PC
Prepare phase
The coordinator asks all participants in the transaction whether they are ready to commit: those ready reply Prepared, otherwise they reply Non-Prepared.
Execution phase
If the coordinator receives Prepared messages from all transaction participants in the prepare phase, it first persists the transaction state locally as Commit, then sends Commit instructions to all participants, which immediately execute the commit. Otherwise, if any participant replies with a Non-Prepared message, or any participant times out without replying, the coordinator persists its transaction state as "Abort" and then sends Abort instructions to all participants, which immediately execute a rollback.
Disadvantages
Single point of failure
Participants cannot apply timeout handling while waiting for the coordinator's instructions. Once the coordinator goes down, all participants are affected. If the coordinator never recovers and fails to send Commit or Rollback instructions, all participants must keep waiting.
Performance issues
During two-phase commit, all participants are effectively bound into a uniformly scheduled whole. The process involves two remote service calls and three data persistences (writing the redo log in the prepare phase, the coordinator persisting state, and writing the Commit Record to the log in the commit phase), and the entire process lasts until the slowest participant in the cluster finishes its operation. This determines that the performance of two-phase commit is usually poor.
Consistency risks
If, after issuing the prepare instruction, the coordinator determines from the information returned by the participants that the transaction can be committed, it first persists the transaction state and commits its own transaction. If the network suddenly disconnects at this point and the Commit instruction cannot be sent to all participants, part of the data (the coordinator's) will be committed while part (the participants') is neither committed nor can be rolled back, resulting in data inconsistency.
3PC
Three-phase commit subdivides the prepare phase of the original two-phase commit into two phases, called CanCommit and PreCommit, and changes the commit phase into the DoCommit phase. The newly added CanCommit is an inquiry phase in which the coordinator asks each participating database to assess, based on its own state, whether the transaction is likely to complete successfully.
The reason for splitting the prepare phase in two is that it is a heavy-load operation: once the coordinator sends the message to start preparing, every participant immediately begins writing the redo log, and the data resources involved are all locked. If at this point one participant cannot complete the commit, it is as if all participants have done a round of useless work.
Therefore, by adding an extra inquiry round, if all responses are positive, we can be much more confident that the transaction will commit successfully, which also means the risk of a total rollback due to a crash of one participant during commit is relatively reduced.
Therefore, in scenarios where transactions need to be rolled back, three-phase commit usually performs much better than two-phase commit. But in scenarios where transactions can commit normally, both two-phase and three-phase commit perform poorly, and three-phase commit is even worse because of the extra inquiry round.
Likewise, because the inquiry phase reduces the probability of transaction failure and rollback, in three-phase commit, if the coordinator goes down after the PreCommit phase begins and the participants do not receive the DoCommit message, the default strategy is to commit the transaction rather than roll it back or keep waiting. You can see that this effectively avoids the single-point problem of the coordinator.
Disadvantage: three-phase commit improves the single-point problem and the performance problem during rollback, but it does not improve the consistency risk at all and may even increase it. Why? Let's look at an example. Suppose that after entering the PreCommit phase, the coordinator's instruction is not Ack but Abort, and due to network problems some participants do not receive the coordinator's Abort instruction until they time out; these participants will mistakenly commit the transaction, resulting in data inconsistency among different participants.
TCC
Try: the trial execution phase, which completes all checks on business executability (to ensure consistency) and reserves all business resources needed by the transaction (to ensure isolation).
Confirm: the confirmation phase, which performs no business checks and directly uses the resources prepared in the Try phase to complete business processing. Note that the Confirm phase may be executed repeatedly, so it must satisfy idempotency.
Cancel: the cancellation phase, which releases the business resources reserved in the Try phase. Note that the Cancel phase may also be executed repeatedly, so it must also satisfy idempotency.
TCC is actually somewhat similar to the prepare and commit phases of 2PC, but TCC lies at the user code level rather than the infrastructure level, which brings high flexibility to its implementation: we can design the granularity of resource locking as needed.
Disadvantage: the main limitation of TCC is its strong business invasiveness, which refers not to the coding workload it brings but to the constraints on technical controllability it requires.
Seata
Saga splits a large transaction into several sub-transactions: T1, T2, …, Ti, …, Tn
Each sub-transaction corresponds to a compensation action: C1, C2, …, Ci, …, Cn
If the Ti transaction fails to commit, the entire transaction must be rolled back: through compensation actions Ci, …, C2, C1, the effects of transactions T1, T2, …, Ti are restored in sequence, returning to the initial state.
The Saga pattern is suitable for business systems with long and numerous business processes that need to guarantee eventual consistency of transactions.
Advantages: local database transactions are committed in one phase, with no locks and high performance; the compensation service is easy to understand and implement.
Disadvantage: Sage cannot guarantee isolation and requires additional locking.
A reliable message delivery scheme based on MQ
Message loss caused by the MQ automatic acknowledgment mechanism
You need to send the acknowledgment manually in code
Message loss caused by message backlog in high-concurrency scenarios
A scheduled task scans and redelivers unfinished messages to perform message compensation. This is the key to implementing distributed transactions based on a message queue, and it is a two-way message confirmation mechanism.
Rate limiting
Algorithms
Fixed time window counting algorithm
It cannot limit bursts of traffic within a short period. Suppose we need to process only 10 requests per second. If 10 requests occur in the previous second, all concentrated in the last 10 milliseconds, and 10 more requests occur in the first 10 milliseconds of the next second, then 20 requests occur within those 20 milliseconds, exceeding the rate-limit threshold. But because these 20 requests fall in two time windows, rate limiting is not triggered, so the strategy does not take effect.
Sliding time window counting algorithm
The principle of this algorithm is to divide the time window into multiple small windows, each with its own request counter.
Although the sliding window algorithm solves the problem of heavy traffic at window boundaries, like the fixed window algorithm it still cannot limit concentrated traffic within a short period — that is, it cannot make traffic smoother.
Leaky bucket algorithm
Any incoming request directly enters the leaky bucket and waits in the queue;
Process requests in the leaky bucket queue at a specific rate;
New requests beyond the leaky bucket's capacity are simply discarded and cannot enter the queue.
For example, when a server is idle, in theory it could handle a burst directly, but the leaky bucket mechanism keeps the request processing rate constant, so server resources can only gradually process requests at the constant leak rate and cannot be used for other rate-limiting scenarios. The token bucket algorithm can solve this problem.
Token bucket algorithm
Generate tokens at a specific rate and store them in the token bucket; if the bucket is full, no new tokens are generated;
If an incoming request needs to be processed, it consumes one token from the bucket;
If there is a token in the bucket, consume one directly;
If there is no token in the bucket, join a queue to wait for a new token;
If the queue waiting for tokens is full, new requests are simply discarded.
If the tokens are generated before the flash sale starts, then at the beginning of the sale the request count is already 100, and the first 100 requests will be allowed through — in other words, the bots have once again grabbed all the goods.
When facing burst traffic, the leaky bucket algorithm buffers it in the bucket, which increases response time and conflicts with the low-latency requirements of Internet business. The token bucket algorithm, by contrast, can store a certain number of tokens in advance and handle a certain amount of burst traffic, so I generally use the token bucket algorithm to implement rate limiting; the rate-limiting solution in Guava is implemented with the token bucket algorithm.
Rate-limiting techniques
Standalone algorithm Guava
An implementation library based on the token bucket algorithm.
3 configuration items
permitsPerSecond: the number of requests allowed per second.
warmupPeriod: how long it takes for the token bucket to fill up.
The timeout of tryAcquire: how long to wait for a new token when the token bucket is empty
Distributed algorithms
Sentinel
Redis
Distributed scheduled tasks
Database-based distributed locks
Elastic-job
xxl-job
Cache
Redis
Distributed lock
Acquire the lock
SET lock_key unique_value NX PX 10000
Release the lock
// When releasing the lock, first compare whether unique_value is equal to avoid accidental release of the lock
if redis.call("get",KEYS[1]) == ARGV[1] then
return redis.call("del",KEYS[1])
else
return 0
end
if redis.call("get",KEYS[1]) == ARGV[1] then
return redis.call("del",KEYS[1])
else
return 0
end
The process of unlocking is to delete the lock_key key, but it cannot be deleted indiscriminately. It must be ensured that the client performing the operation is the client that acquired the lock. This can be implemented by using a lua script to determine whether unique_value belongs to the client that acquired the lock.
Advantages
High performance
Easy to implement
Avoid single point of failure
Disadvantages
Unreasonable timeout setting
The data synchronization mechanisms of a Rediscluster can all lead to the unreliability of distributed locks.
Reliability of distributed locks in a cluster
The basic idea of the Redlock algorithm is to have the client request locks from multiple independent Redis instances in sequence. If the client can successfully complete the locking operation with more than half of the instances, we consider that the client has successfully acquired the distributed lock; otherwise, the lock acquisition fails. Even if a Redisinstance fails, because the lock data is also stored on other instances, the client can still perform lock operations normally and the lock data will not be lost.
Cache
Why is Redisstill so fast when it uses a single thread?
Most operations in Redisare performed in memory, and it uses efficient data structures such as hash tables and skip lists.
The single-threaded model avoids competition between multiple threads, eliminates the time and performance overhead caused by thread switching, and does not lead to deadlock problems.
Redis uses I/O multiplexing to handle a large number of client Socket requests, which allows Redis to perform network communication efficiently. Because it is based on a non-blocking I/O model, the I/O read and write processes are no longer blocked.
High availability
How does Redisensure no data loss?
RDB
Write the in-memory data at a certain moment to disk in binary form
AOF
Record all operation commands and append them to a file in text form.
After Redis 4.0, a hybrid data persistence mechanism of AOF and RDB was added: write data to a file in RDB format, and then store subsequent operation commands in the file in AOF format. This both guarantees the restart speed of Redisand reduces the risk of data loss.
How does Redisachieve high service availability?
Redis Sentinel sentinel mode
Sentinel mode can monitor master and slave servers and provides automatic disaster recovery.
Redis Sentinel is also deployed as a cluster, which avoids the problem that a Sentinel node failure prevents automatic failover. Every Sentinel node is stateless. The address of the Master is configured in Sentinel, and Sentinel constantly monitors the status of the Master. When the Master does not respond within the configured time interval, it is considered that the Master has gone down. Sentinel will select one from the slave nodes and promote it to be the master, and make all other slave nodes the slaves of the new master. When arbitrating within the Sentinel cluster, the configured value determines how manySentinelnodes must consider the master down before a master-slave switch can be performed, that is, the cluster must reach agreement on the status of the cache nodes.
Redis Sentinel does not belong to the proxy-layer model, because write and read requests for the cache do not pass through Sentinel nodes. Architecturally, Sentinelnodes are on the same level as the master and slaves and exist as managers. Therefore, it can be regarded as a high-availability solution provided on the server side.
Redis Cluster (cluster)
Hash slots (Hash Slot) are used to handle the mapping relationship between data and instances.
A sharded cluster has a total of 16384 hash slots, which are similar to data partitions
According to the key of the key-value pair, a 16 bit value is calculated using the CRC16algorithm.
Then the 16bit value is used to take the modulo of 16384, obtaining a modulus in the range 0~16383. Each modulus represents a corresponding numbered hash slot.
Hash slot mapping supports manual allocation and random allocation
When a client requests a Key, the requested Redis instance first uses the above formula to calculate which slot this Key is in, then queries the mapping relationship between slots and nodes to find the real node where the data resides. If this node happens to be itself, it directly executes the command and returns the result. If the data is not on the current node, it returns a redirect command to the client, telling the client which node to connect to in order to request the data of this Key. The client then connects to the correct node to access it.
Redis Cluster supports adding one or more slave nodes to each shard. After each slave node connects to the master node, it first sends a SYNC command to the master node to request a full replication, that is, copying all the data on the master node to the slave node. After the full replication is completed, it enters the synchronization phase, in which the master node continuously forwards the commands received during the full replication and the commands received afterwards to the slave nodes.
Redis Cluster is not very suitable for building ultra-large-scale clusters, mainly because it adopts a decentralized design. As we just explained, every node of Redisstores the mapping table of all slots and nodes, so the client can access any node and then use the redirect command to find the node where the data resides. But have you ever thought about a question: how is this mapping table updated? For example, when a new node joins the cluster, or a master node goes down and a new master is elected, in these cases the mapping table on every node of the cluster needs to be updated.
Redis Cluster uses a decentralized gossip (Gossip) protocol to propagate changes in cluster configuration.
How to build an ultra-large-scale cluster with Redis?
One approach is based on a proxy: an additional proxy service layer is needed between the client and the Redis nodes. This proxy service has three functions.
The first function is to forward requests and responses between the client and the Redis nodes. The client only deals with the proxy service. After receiving a request from the client, the proxy forwards it to the corresponding Redis node, and the response returned by the node is forwarded back to the client through the proxy.
The second function is to monitor the status of all Redis nodes in the cluster and perform master-slave switching in time if a problematic node is found.
The third function is to maintain the cluster metadata, which mainly includes the master-slave information of all nodes in the cluster and the mapping table of slots to nodes.
twemproxy and Codis
The biggest advantage is transparency to the client. From the client's point of view, the entire cluster is the same as a single Redis node with huge capacity. Moreover, since the sharding algorithm is controlled by the proxy service, scaling is relatively convenient: after a new node joins the cluster, expansion can be completed by directly modifying the metadata in the proxy service.
The disadvantages of this architecture are also obvious. An extra proxy forwarding layer is added, so the path of each data access is longer, which inevitably brings a certain performance loss. Moreover, the proxy service itself is a single point of failure of the cluster. Of course, we can also make the proxy service a cluster to solve the single-point problem, but then the cluster becomes more complex.
Another approach is to not use this proxy service and move the addressing function of the proxy service to the client.
Before sending a request, the client first queries the metadata to know which shard and which node to access, and then directly connects to the corresponding Redis node to access the data.
The client does not need to query the metadata every time, because the metadata does not change much. The client can cache the metadata itself, so the access performance is basically the same as that of a stand-alone Redis. If the master node of a shard goes down and a new master is elected, the information in the metadata is updated. Scaling the cluster is also relatively simple: apart from the necessary data migration, it is only necessary to update the metadata.
Although this metadata service is still a single point of failure, its data volume is small and its access volume is not large, so it is relatively easy to implement. We can use ZooKeeper、etcd or even MySQL to meet the requirements. This solution should be the most suitable one for ultra-large-scale Redis clusters, and in
The disadvantage is that the whole architecture is relatively complex. The client cannot be generic; a customized Redis client must be developed, which only enterprises with a sufficiently large scale can afford.
The cluster solution cannot provide 100% support for multi- KEY commands such as “KEYS”. The reason is simple: after data is sharded, such multi- KEY commands are likely to need to query across multiple shards. When your system is upgraded from a single Redis database to a cluster, you may need to consider compatibility issues in this regard.
Cache strategies
Cache penetration
Each time an individual key is queried, if key does not hit in the cache system, the application system queries the database. If the data exists in the database, the data is obtained and the cache system is updated. But if the data does not exist in the database either, the cache cannot be updated, which causes a problem: when querying data that does not exist in the cache, the database has to be queried every time.
Solution 1: Pre-set a default value for all specified key, such as the empty string “Null”. When this empty string “Null” is returned, we can consider it a non-existent key
Solution 2: Bloom filter
Use multiple Hash algorithms to calculate multiple Hash values for an element. Only when the values in the array corresponding to all Hash values are 1 is the element considered to be in the set.
A Bloom filter consumes a certain amount of memory space, so when using it you need to assess how much memory is needed for your business scenario and whether the storage cost is acceptable.
The defect that a Bloom filter does not support deleting elements is also related to Hash collisions. Let me give you an example. Suppose two elements A and B are both in the set and have the same Hash value; they will be mapped to the same position in the array. If we delete A at this point, the value at the corresponding position in the array also changes from 1 to 0. Then when judging B, the value is found to be 0, so B will also be judged as not being in the set, leading to a wrong conclusion.
So how did I solve this problem? Instead of storing only the two values 0 and 1 in the array, I store a counter. For example, if A and B hit the same array index at the same time, the value at that position is 2; if A is deleted, the value is changed from 2 to 1. The array in this solution no longer stores bit bits but stores numbers, which increases space consumption. Therefore, you need to choose whether to use a Bloom filter according to the business scenario. For example, in a user registration scenario, since user deletion basically does not occur, a Bloom filter can still be used to solve the cache penetration problem.
Cache concurrency
Suppose that at the same time the cache expires, multiple clients concurrently request the same key. At this point, because key has already expired, all requests fail to find key in the cache database, so all requests go to the database to query. Then after the data is found, all requests repeatedly update the queried data into the cache. This increases the pressure on the database and occupies cache overhead.
Solution:distributed lock
Cache avalanche
When the expiration times of key are all the same, then when key expires, the cache becomes invalid collectively. If the request concurrency is high at this time, a large number of requests will hit the database, causing the database pressure to increase instantly and resulting in a cache avalanche.
Solution 1: Randomize the cache expiration time
Solution 2: Set the cache to never expire
Dynamically cache hot data and combine it with the business
MySQL Binlog + Canal + MQ
Cache Aside strategy
Read-cache strategy
First try to read data from the cache;
If there is no data in the cache or the data is expired, read the data from the database and save it to the cache;
Finally, return the cached data to the caller。
Write-cache strategy
First update the database, then delete the cache
Write Back strategy
Read-cache strategy
When reading the cache, if the cache hits, the cached data is returned directly. If the cache misses, an available cache block is found. If the cache block is “dirty”, the previous data in the cache block is written to the back-end storage, and data is loaded from the back-end storage into the cache block. If it is not dirty, the cache component loads the data from the back-end storage into the cache. Finally, we set the cache to not dirty and return the data.
Write cache
In the case of a “Write Miss”, we use the “Write Allocate” approach, that is, we write to the cache at the same time as writing to the back-end storage, so that in subsequent write requests we only need to update the cache and not the back-end storage,
MySQL To Redis
Put all the data in the Redis cluster. When processing read requests, simply read only Redisand not the database. This completely eliminates the risk of “cache penetration”
Method 2: Use Binlog to update the Rediscache in real time
The data update service is only responsible for processing business logic and updating MySQL, and does not need to care about how to update the cache at all. The service responsible for updating the cache disguises itself as a MySQL slave node, receives Binlog from MySQL, parses the Binlog to obtain real-time data change information, and then updates theRediscache according to this change information.
Message middleware
RocketMQ
Basic concepts
Message
Topic
topic:message 1:n message:topic 1:1
producer:topic 1:n consumer:topic 1:1
Tag
Queue
A Topic can contain multiple Queues, and each Queue stores the messages of that Topic. A Topic's Queue is also called a partition (Partition) of messages in a Topic.
The messages in a Topic's Queue can only be consumed by one consumer in one consumer group. Messages in a Queue are not allowed to be consumed by
multiple consumers in the same consumer group at the same time
Sharding
Sharding is different from partitioning. In RocketMQ , sharding refers to the Broker storing the corresponding Topic. Each shard creates a corresponding number of partitions, namely Queues, and each Queue has the same size.
Architecture
Porducer cluster
The message producer is responsible for producing messages. The Producer selects the corresponding Broker cluster queue for message delivery through the load balancing module of MQ. The delivery process supports fast failure and low latency.
Message producers in RocketMQ all appear in the form of producer groups (Producer Group). A producer group is a collection of producers of the same kind; these Producers send messages of the same Topic type. One producer group can send messages of multiple topics at the same time.
Consumer cluster
The message consumer is responsible for consuming messages. A message consumer obtains messages from the Broker server and performs relevant business processing on the messages.
Message consumers in RocketMQ all appear in the form of consumer groups (Consumer Group). A consumer group is a collection of consumers of the same kind; these Consumers consume messages of the same Topic type.
Consumer groups make it very easy to achieve load balancing (evenly distributing different Queues in a Topic among different Consumers of the same Consumer Group. Note that this is not load balancing of messages) and fault tolerance (if one Consmer goes down, other Consumers in that Consumer Group can continue to consume the Queue that the original Consumer was consuming) in message consumption.
The number of Consumers in a consumer group should be less than or equal to the number of Queues of the subscribed Topic. If it exceeds the number of Queues, the extra Consumers will not be able to consume messages.
A consumer group can only consume messages in one Tocpic, not multiple Tocpic messages at the same time
The consumers of a consumer group must have exactly the same Topic
Name Server cluster
NameServer is a registry for Broker and Topic routing and supports dynamic registration and discovery of Brokers.
It mainly includes two functions
Broker management: receive the registration information of the Broker cluster and save it as the basic data of routing information; provide a heartbeat detection mechanism to check whether the Broker is still alive.
Routing information management: each NameServer stores the entire routing information of the Broker cluster and the queue information used by clients for queries. Producer and Conumser can obtain the routing information of the entire Broker cluster through NameServer, so as to deliver and consume messages.
Routing registration
NameServer is usually also deployed as a cluster. However, NameServer is stateless, meaning that the various nodes in a NameServer cluster are indistinguishable and do not communicate information with each other. So how is the data on each node synchronized? When a Broker node starts, it polls the NameServer list, establishes long connections with each NameServer node, and sends registration requests. Inside NameServer, a Broker list is maintained to dynamically store Broker information.
To prove that it is alive and to maintain the long connection with NameServer, the Broker node reports the latest information to NameServer in the form of a heartbeat packet
once every 30 seconds. The heartbeat packet contains BrokerId, Broker address (IP+Port), Broker name, the name of the cluster to which the Broker belongs, and so on. After receiving the heartbeat packet, NameServer updates the heartbeat timestamp and records the latest survival time of this Broker.
once every 30 seconds. The heartbeat packet contains BrokerId, Broker address (IP+Port), Broker name, the name of the cluster to which the Broker belongs, and so on. After receiving the heartbeat packet, NameServer updates the heartbeat timestamp and records the latest survival time of this Broker.
Routing removal
If NameServer does not receive a Broker's heartbeat due to Broker shutdown, crash, or network jitter, NameServer may
remove it from the Broker list.
There is a scheduled task in NameServer that scans the Broker table every 10 seconds, checking whether the latest heartbeat timestamp of each Broker is more than 120 seconds away from the current time. If it exceeds, the Broker is judged to be invalid and then removed from the Broker list.
Route discovery
RocketMQ's route discovery uses the Pull model. When Topic routing information changes, NameServer does not proactively push to the
client; instead, the client periodically pulls the latest routes of the topic. By default, the client pulls the latest routes every 30 seconds.
client; instead, the client periodically pulls the latest routes of the topic. By default, the client pulls the latest routes every 30 seconds.
Client NameServer selection strategy
When configuring the client, you must write the address of the NameServer cluster. So which NameServer node does the client actually connect to? The client first generates a random number, then takes the modulo with the number of NameServer nodes; the result is the node index to connect to, and then it connects. If the connection fails, the round-robin strategy is used to try connecting to the other nodes one by one.
First, the random strategy is used for the selection, and after failure, the round-robin strategy is used.
Broker cluster
Broker acts as a message intermediary, responsible for storing and forwarding messages. In the RocketMQ system, Broker is responsible for receiving and storing messages sent from producers, while preparing for consumers' pull requests. Broker also stores message-related metadata, including consumer group consumption progress offset, topics, queues, etc.
Module composition
Remoting Module: the entire Broker entity, responsible for handling requests from clients. And this Broker entity is composed of the following mod ules.
Client Manager: client manager. Responsible for receiving and parsing client (Producer/Consumer) requests, and managing clients. For example, maintaining Consumer's Topic subscription information
Store Service: storage service. Provides a convenient and simple API interface, handling the functions of storing messages to the physical disk and message query .
HA Service: high availability service, providing data synchronization between Master Broker and Slave Broker.
Index Service: indexing service. Performs indexing on messages delivered to Broker according to a specific Message key, and also pro vides the function of quickly querying messages by Message Key.
Schematic diagram
Cluster deployment
To enhance Broker performance and throughput, Broker generally appears in the form of a cluster. Different Queue of the same Topic may be stored in each cluster node. However, there is a problem here: if a Broker node goes down, how can data loss be prevented? The sol ution is to scale out each Broker cluster node, that is, to build the Broker node into another HA cluster, solving the single point problem.
- The Broker node cluster is a master-slave cluster, that is, the cluster has two roles: Master and Slave. Master is responsible for handling read and write operation requ ests, Slave is responsible for backing up the data in Master. When Master goes down, Slave automatically switches to Master to work. Therefore this Broker cluster is an active-standby cluster. One Master can contain multiple Slaves, but one Slave can only belong to one Master. The corresponding relationship between Master and Slave is determined by specifying the same BrokerName and different BrokerId . BrokerId of 0 means Master, non-zero means Slave. Each Broker establishes a long connection with all nodes in the NameServer cluster, and periodically registers Topic inform ation to all NameServers.
Schematic diagram
Workflow
1) Start NameServer. After NameServer starts, it begins listening on the port, waiting for Broker, Producer, and Consumer to connect.
2) When starting Broker, Broker establishes and maintains long connections with all NameServers, then periodically sends heartbeat packets to NameServer every 30 seconds.
3) Before sending messages, you can first create a Topic. When creating a Topic, you need to specify which Brokers the Topic will be stored on. Of course, when creating the Topic, the relationship between the Topic and Broker is also written into NameServer. However, this step is optional; you can also create the Topic automatically when sending messages.
4) When Producer sends messages, at startup it first establishes a long connection with one of the NameServer cluster nodes, and obtains routing information from NameServer, that is, the mapping between the Queue of the currently sent Topic message and the Broker address (IP+Port). Then, according to the algorithm strategy, it selects a Queue from the queue and establishes a long connection with the Broker where the queue is located to send messages to the Broker. Of course, after obtaining the routing information, Producer first caches the routing information locally, then updates the routing information from NameServer every 30 seconds.
5) Consumer is similar to Producer: it establishes a long connection with one of the NameServers, obtains the routing information of the Topic it subscribes to, then according to the algorithm strategy obtains the Queue it wants to consume from the routing information, then directly establishes a long connection with the Broker and starts consuming the messages therein. After obtaining the routing information, Consumer also updates the routing information from NameServer every 30 seconds. However, unlike Producer, Consumer also sends heartbeats to Broker to ensure Broker's alive status.
Topic creation modes
When creating a Topic manually
Cluster mode: A Topic created in this mode has the same number of Queue in all Brokers in the cluster.
Broker mode: A Topic created in this mode can have different numbers of Queue in each Broker in the cluster.
When creating a Topic automatically
By default, Broker mode is used, and 4 Queue are created by default for each Broker.
Cluster construction theory
Data replication and disk flushing strategies
Replication strategy
Synchronous replication: After a message is written to master, master waits until slave has successfully synchronized the data before returning a success ACK to producer.
Asynchronous replication: After a message is written to master, master immediately returns a success ACK to producer, without waiting for slave to successfully synchronize the data.
The replication strategy is the data synchronization method between Master and Slave of Broker. It is divided into synchronous replication and asynchronous replication.
Disk flushing strategy
The disk flushing strategy refers to the disk dropping method of messages in broker, that is, the way messages are persisted to disk after being sent to broker's memory. It is divided into synchronous disk flushing and asynchronous disk flushing.
Synchronous disk flushing: A message is considered successfully written only after it is persisted to broker's disk.
Asynchronous disk flushing: Once a message is written to broker's memory, it is considered successfully written, without waiting for the message to be persisted to disk.
Broker cluster modes
Single Master
There is only one broker (which essentially cannot be called a cluster). This approach can only be used for testing; it cannot be used in a production environment because of the single point problem.
Multiple Master
The Broker cluster consists only of multiple masters, with no Slave. The Queue of the same Topic are evenly distributed across the master nodes
.
.
Advantages: simple configuration; the downtime or restart maintenance of a single Master has no impact on applications. When disks are configured as RAID10, even if a machine goes down unrecoverably, messages will not be lost because RAID10 disks are very reliable (asynchronous disk flushing loses a small number of messages, synchronous disk flushing loses none), and performance is the highest;
Disadvantages: during the downtime of a single machine, the unconsumed messages on that machine cannot be subscribed to (cannot be consumed) until the machine recovers, and the real-time nature of messages is affected.
Multiple Master, multiple Slave mode - asynchronous replication
The Broker cluster consists of multiple masters, and each master is configured with multiple slaves (when a RAID disk array is configured, one master is generally configured with just one slave). The relationship between master and slave is active-standby, that is, master handles read and write requests for messages, while slave is only responsible for backing up messages and switching roles after master goes down.
Asynchronous replication is the asynchronous replication strategy among the replication strategies described earlier, that is, after a message is successfully written to master, master immediately returns a success ACK to producer, without waiting for slave to successfully synchronize the data.
One of the biggest features of this mode is that when master goes down, slave can automatically switch to master. However, since the synchronization from master to slave has a short delay (millisecond level), this asynchronous replication method may result in the loss of a small number of messages when master goes down.
Multiple Master, multiple Slave mode - synchronous dual write
This mode is the synchronous replication implementation of the multiple Master, multiple Slave mode . The so-called synchronous dual write means that after a message is successfully written to master,
master waits until slave has successfully synchronized the data before returning a success ACK to producer, that is, both master and slave must be written successfully before a success ACK is returned, which is the dual write .
master waits until slave has successfully synchronized the data before returning a success ACK to producer, that is, both master and slave must be written successfully before a success ACK is returned, which is the dual write .
Compared with the asynchronous replication mode , this mode has the advantage of higher message security, with no message loss. However, the RT of a single message is slightly higher, resulting in slightly lower performance (about 10% lower).
This mode has a big problem: in the current version, after Master goes down, Slave will not automatically switch to Master.
Best practices
Generally, a RAID10 disk array is configured for Master, and then a Slave is configured for it. This not only takes advantage of the efficiency and security of the RAID10 disk array, but also solves the problem that may affect subscription.
Subtopic
How RocketMQ works
Message production
The message production process
Producer can write messages into a Queue in a Broker, which goes through the following process:
Before sending messages, Producer first sends a request to NameServer to obtain the routing information of the message Topic.
NameServer returns the routing table and Broker list of the Topic
Producer selects a queue from the Queue list according to the Queue selection strategy specified in the code, for subsequent message storage
Produer performs some special processing on the message, for example, if the message itself exceeds 4M, it will be compressed
Producer sends an RPC request to the Broker where the selected Queue is located, and sends the message to the selected Queue
Queue selection algorithm
For unordered messages, their Queue selection algorithm, also called the message delivery algorithm, has two common types:
Round-robin algorithm: the default selection algorithm. This algorithm ensures that messages can be obtained evenly in each Queue.
Minimum delivery delay algorithm: This algorithm counts the time delay of each message delivery, then delivers the message to the Queue with the smallest time delay according to the statistical result. If the delays are the same, the round-robin algorithm is used for delivery. This algorithm can effectively improve message delivery performance.
Message storage
Messages in RocketMQ are stored in the local file system, and these related files are by default in the store directory under the current user's home directory.
commitlog file
The commitlog directory contains many mappedFile files, and all messages in the current Broker are written to disk in these mappedFile files. The size of a mappedFile file is 1G (less than or equal to 1G), and the file name consists of 20 decimal digits, indicating the starting offset of the first message in the current file.
It should be noted that one Broker contains only one commitlog directory, and all mappedFile files are stored in this directory. That is, no matter how many Topic messages are stored in the current Broker, these messages are all sequentially written into the mappedFile files . In other words, when stored in Broker, these messages are not classified by Topic.
The content of a mappedFile file is composed of message units one by one. Each message unit contains nearly 20-plus message-related attributes, such as the total message length MsgLen, the physical
location physicalOffset of the message, the message body content Body, the body length BodyLength, the message topic Topic, the Topic length TopicLength, the message producer BornHost, the message send timestamp BornTimestamp, the queue QueueId where the message is located, and the offset QueueOffset of the message stored in the Queue.
location physicalOffset of the message, the message body content Body, the body length BodyLength, the message topic Topic, the Topic length TopicLength, the message producer BornHost, the message send timestamp BornTimestamp, the queue QueueId where the message is located, and the offset QueueOffset of the message stored in the Queue.
consumequeue
To improve efficiency, a directory is created for each Topic in ~/store/consumequeue, with the directory name being the Topic name. Under that Topic directory, another directory is created for each Queue of the Topic, with the directory name being queueId. Each directory stores several consumequeue files; a consumequeue file is an index file of commitlog, and a specific message can be located through consumequeue.
The consumequeue file name is also composed of 20 digits, indicating the starting offset of the first index entry in the current file. Unlike the mappedFile file name, subsequent file names are fixed. This is because the size of a consumequeue file is constant.
Each consumequeue file can contain 30w index entries, and each index entry contains three important message attributes: the offset of the message in the mappedFile file CommitLog Offset, the message length, and the hashcode value of the message Tag. These three attributes occupy 20 bytes, so the size of each file is fixed at 30w * 20 bytes.
Reading and writing files
Message writing
After a message enters Broker, it goes through the following processes before finally being persisted.
Broker obtains the write offset in the consumequeue directory for the index entry corresponding to the message according to queueId, that is, QueueOffset
encapsulates data such as queueId and queueOffset together with the message into a message unit, and writes the message unit to commitlog
at the same time, forms a message index entry and distributes the message index entry to the corresponding consumequeue
encapsulates data such as queueId and queueOffset together with the message into a message unit, and writes the message unit to commitlog
at the same time, forms a message index entry and distributes the message index entry to the corresponding consumequeue
Message pulling
When Consumer comes to pull messages, it goes through the following steps
1. Consumer obtains the consumption offset of the Queue where the message to be consumed is located , and calculates the message offset of the message to be consumed
2. Consumer sends a pull request to Broker, which contains the Queue of the message to be pulled, the message offset, and the message Tag.
3. Broker calculates the queueOffset in the consumequeue.
4. Starting from that queueOffset, search backward for the first index entry with the specified Tag.
5. By parsing the first 8 bytes of the index entry, you can locate the commitlog offset of the message in commitlog
6. Read the message unit from the corresponding commitlog offset and send it to Consumer
Subtopic
Performance improvement
In RocketMQ, whether the messages themselves or the message indexes, they are all stored on disk. Won't this affect message consumption? Of course not. In fact, RocketMQ's performance is very high among current MQ products, because the system greatly improves performance through a series of related mechanisms.
First, RocketMQ's file read and write operations are performed through mmap zero-copy , converting file operations into direct operations on memory addresses, thereby greatly improving file read and write efficiency.
Second, the data in consumequeue is stored sequentially, and the PageCache read-ahead mechanism is also introduced, making reads of consumequeue files almost close to memory reads, so performance is not affected even when messages accumulate.
In RocketMQ, what may affect performance is the reading of commitlog files. For commitlog files, reading messages generates a large number of random accesses, which seriously affect performance. However, if an appropriate system IO scheduling algorithm is selected, for example setting the scheduling algorithm to Deadline (if using SSD solid-state drives), the performance of random reads can also be improved.
Comparison with Kafka
Many ideas of RocketMQ come from Kafka, among which commitlog and consumequeue are examples.
The combination of the commitlog directory and consumequeue in RocketMQ is similar to the partition directory in Kafka. The mappedFile file is similar to the segment in Kafka.
Message consumption
Obtaining consumption types
Pull consumption: Consumer actively pulls messages from Broker, and the initiative is controlled by Consumer. Once a batch of messages is obtained, the consumption process starts. However, this method has weak real-time performance, that is, when new messages arrive in Broker, consumers cannot discover and consume them in time.
Push consumption: In this mode, after Broker receives data, it actively pushes it to Consumer. This acquisition method generally has high real-time performance.
Consumption modes
Broadcast consumption: Every Consumer instance in the same Consumer Group receives all messages of the same Topic. That is, every message is sent to every Consumer in the Consumer Group.
Cluster consumption: In cluster consumption mode, every Consumer instance in the same Consumer Group shares the messages of the same Topic evenly. That is, each message is only sent to a certain Consumer in the Consumer Group.
Message progress saving
Broadcast consumption: Consumption progress is saved on the consumer side. Because in broadcast mode every consumer in consumer group consumes all messages, but their consumption progress is different. Therefore, each consumer saves its own consumption progress.
Cluster mode: Consumption progress is saved in broker. All consumers in consumer group jointly consume messages in the same Topic , and the same message is consumed only once. Consumption progress participates in the load balancing of consumption, so it needs to be shared. The figure below shows the consumption progress of each Queue of each Topic stored in broker.
Rebalance mechanism
Rebalance, namely re-balancing, refers to the process of reassigning multiple Queue under a Topic among multiple Consumer in the same Consumer Group.
The original intention of the Rebalance mechanism is to improve the parallel consumption capability of messages. For example, with 5 queues under a Topic, if there is only 1 consum er, this consumer will be responsible for consuming the messages of these 5 queues. If we add another consumer at this time, we can assign 2 queues to one consumer and 3 queues to the other, thereby improving the parallel consumption capability of messages.
Rebalance limitation: Since a queue is assigned to at most one consumer, when the number of consumer instances in a consumer group is greater than the number of queues, the excess consumer instances will not be assigned any queue.
Harm of Rebalance
Consumption pause: When there is only one Consumer, it is responsible for consuming all queues; after a new Consumer is added, Rebalance is triggered. At this time, the original Consumer needs to pause the consumption of some queues, and only after these queues are assigned to the new Consumer can these paused queues continue to be consumed.
Duplicate consumption: When Consumer consumes a queue newly assigned to it, it must continue from the offset of the consumption progress previously committed by Consumer . However, by default, offset is committed asynchronously, and this asynchrony causes the offset committed to Broker to be inconsistent with the messages actually consumed by Consumer . This inconsistent difference is the messages that may be consumed repeatedly.
Consumption spike: Since Rebalance may cause duplicate consumption, if there are too many messages to be consumed repeatedly, or because Rebalance pauses for too long resulting in a backlog of some messages, it may cause a large number of messages to be consumed instantly after Rebalance ends.
Causes of Rebalance
There are only two causes of Rebalance: the number of Queue of the Topic subscribed by consumers changes, or the number of consumers in the consumer group changes.
Rebalance process
In Broker, multiple Map collections are maintained, which dynamically store information about Queue in the current Topic and information about Consumer instances in Consumer Group . Once the number of Queue subscribed by consumers changes, or the number of consumers in the consumer group changes, a Rebalance notification is immediately sent to every instance in Consumer Group.
After receiving the notification, the Consumer instance uses the Queue allocation algorithm to obtain the corresponding Queue by itself, that is, the Consumer instance performs Rebalance autonomously.
Comparison with Kafka
In Kafka, once a Rebalance condition is detected, the Broker invokes the Group Coordinator to complete the Rebalance. The Coordinator is a process within the Broker. The Coordinator elects a Group Leader from the Consumer Group. This Leader completes the reallocation of Partition partitions based on its own group situation. The reallocation result is reported to the Coordinator, and synchronized by the Coordinator to all Consumer instances in the Group.
Rebalance in Kafka is performed by the Consumer Leader. In RocketMQ, Rebalance is performed by each Consumer itself, and there is no Leader in the Group.
Queue allocation algorithm
A Queue in a Topic can only be consumed by one Consumer in a Consumer Group, while one Consumer can consume messages from more than one Queue at the same time. How is the pairing relationship between Queue and Consumer determined, that is, which Consumer a Queue is assigned to for consumption? There are also algorithmic strategies for this. Four common strategies exist. These strategies are passed in through the constructor when the Consumer is created.
Average allocation strategy: This algorithm allocates based on the calculation result of avg = QueueCount / ConsumerCount. If it is divisible, avg Queue are assigned to Consumer one by one in order; if not divisible, the extra Queue are assigned to Consumer one by one in Consumer order
Ring average strategy: The ring average algorithm means that, according to the order of consumers, allocation is performed one by one in turn in a ring composed of queue queues.
Sub-topic
Consistent hash strategy:
This algorithm stores the hash value of consumer on the hash ring as a Node node, and then puts the hash value of queue on the hash ring as well, in the clockwise direction, the consumer closest to the queue is the consumer to which the queue will be allocated.
Uneven allocation
Same-IDC strategy
Comparison
Problems with the consistent hash algorithm:
The two average allocation strategies have higher allocation efficiency, while the consistent hash strategy is lower. This is because the consistent hash algorithm is more complex. In addition, the result of the consis tent hash strategy is also very likely to be uneven.
The two average allocation strategies have higher allocation efficiency, while the consistent hash strategy is lower. This is because the consistent hash algorithm is more complex. In addition, the result of the consis tent hash strategy is also very likely to be uneven.
Significance of the consistent hash algorithm: It can effectively reduce the large number of Rebalance events caused by the expansion or shrinkage of consumer groups.
Application scenarios of the consistent hash algorithm: Scenarios where the number of Consumer changes frequently
At-least-once principle
RocketMQ has a principle: every message must be successfully consumed once.
So what is successful consumption? After consuming a message, the Consumer submits the offset of the consumed message to its consumption progress recorder and, once the offset is successfully recorded in the recorder, this consumption is considered successful.
So what is successful consumption? After consuming a message, the Consumer submits the offset of the consumed message to its consumption progress recorder and, once the offset is successfully recorded in the recorder, this consumption is considered successful.
offset management
offset local management mode:
When the consumption mode is broadcast consumption , offset is stored in local mode. Because every message is consumed by all consumers, each consu
mer manages its own consumption progress, and there is no overlap of consumption progress among consumers.
In broadcast consumption mode, the Consumer persists offset related data to the Consumer's local disk file in json format. The default fi
le path is .rocketmq_offsets/${clientId}/${group}/Offsets.json under the current user's home directory. Here ${clientId} is the current consumer id, defaulting to ip@DEFAULT; ${group} is the consumer group name.
offset remote management mode
When the consumption mode is cluster consumption , offset is managed in remote mode. Because all Cosnumer instances use balanced consumption for messages, all Consumer shares the consumption progress of Queue.
In cluster consumption mode, the Consumer persists offset related data to the Broker's disk file in json format. The file path is under the curr
ent user's home directory: store/config/consumerOffset.json .
When the Broker starts, it loads this file and writes it into a two-level Map(ConsumerOffsetManager). The key of the outer map is topic@group, and the value is the inner map. The key of the inner map is queueId, and the value is offset. When a Rebalance occurs, the new Consumer obtains the corresponding data from this Map to continue consumption.
In cluster mode, offset uses remote management mode mainly to guarantee the Rebalance mechanism.
offset usage
How does a consumer keep consuming messages from the very beginning? The starting position of the first message a consumer consumes is specified by the user through the consumer.setConsumeFromWhere() method.
After the Consumer starts, there are three commonly used starting positions for the first message to be consumed, and these positions can be set through enumeration type constants. This enumeration type is ConsumeFromWhere.
Consume from the current last message of the queue
Consume from the first message of the queue
Start consuming from messages with a specified specific timestamp
After consuming a batch of messages, the Consumer submits its consumption progress offset to the Broker. After receiving the consumption progress, the Broker up dates it to the two-level Map(ConsumerOffsetManager) and the consumerOffset.json file, and then sends an ACK to the Consumer. The ACK contains three pieces of data: the minimum offset (minOffset) of the current consumption queue, the maximum offset (maxOffset), and the starting offset (nextBeginOffset) of the next consumption.
Retry queue
When rocketMQ encounters an exception in consuming a message, it submits the offset of the exception message to the retry queue in the Broker. When a message consumption exception occurs, the system creates a retry queue for the current topic@group. This queue starts with %RETRY%, and consumption is retried when the re try time is reached.
Synchronous and asynchronous submission of offset
In cluster consumption mode, after consuming a message, the Consumer submits the consumption progress offset to the Broker. There are two submission methods:
Synchronous submission: After consuming a batch of messages, the consumer submits the offset of these messages to the broker and waits for a successful response from the broker. If a successful response is received before the wait times out, it continues to read the next batch of messages for consumption (obtaining nextBeginOffset from the ACK ). If no response is received, it resubmits until a response is obtained. During this waiting process, the consumer is blocked. This seriously affects the throughput of consumers.
Asynchronous submission: After consuming a batch of messages, the consumer submits the offset to the broker, but does not need to wait for a successful response from the Broker and can continue reading and consuming the next batch of messages. This increases consumer throughput. Note, however, that after receiving the submitted offset the broker still responds to the consumer. The ACK may not have been received yet; in this case, the Consumer obtains nextBeginOffset directly from the Broker.
Consumption idempotence
What is consumption idempotence
When a consumer repeatedly consumes a message, if the result of repeated consumption is the same as the result of consuming it once, and multiple consumptions have no negative impact on the business system, then this consumption process is idempotent.
In Internet applications, especially when the network is unstable, messages are very likely to be sent or consumed repeatedly. If repeated messages may affect business processing, idempotent processing should be applied to the messages.
Analysis of message duplication scenarios
Message duplication during sending
When a message has been successfully sent to the Broker and persisted, a network flash cut occurs, causing the Broker to fail to respond to the Producer. If the Producer realizes the send failed and tries to send the message again at this time, tw o messages with the same content and the same Message ID may appear in the Broker, and subsequent Consumer will inevitably consume the message twice.
Message duplication during consumption
The message has been delivered to the Consumer and business processing is complete, but a network flash cut occurs when the Consumer feedbacks the response to the Broker, and the Broker does not receive the consumption success response.
To guarantee the principle that a message is consumed at least once , the Broker will try to redeliver the previously processed message after the network recovers. At this time, the consumer will receive a message with the same content and the same Message ID as before.
To guarantee the principle that a message is consumed at least once , the Broker will try to redeliver the previously processed message after the network recovers. At this time, the consumer will receive a message with the same content and the same Message ID as before.
Message duplication during Rebalance
When the number of Consumer in a Consumer Group changes, or the number of Queue of the subscribed Topic changes, Rebalance is triggered, and the Consumer may receive messages that have already been consumed.
General solution
1. First, deduplicate through the cache. If an idempotency token already exists in the cache, it means this operation is a duplicate operation; if the cac he does not hit, proceed to the next step.
2. Before the uniqueness processing, first query in the database whether data with the idempotency token as an index exists. If it exists, it means this operation is a duplicate operation; if not, proceed to the next step.
3. Complete three operations in the same transaction: after uniqueness processing, write the idempotency token to the cache, and write the data with the idempotency token as a unique ind ex to the DB.
Taking the payment scenario as an example:
3. Complete three operations in a distributed transaction:
Complete the payment task
Use the current payment serial number as the key and any string as the value, through set(key, value, expireTime) write the da
ta to the Redis cache
Use the current payment serial number as the primary key and write it to the DBMS together with other related data
1. When a payment request arrives, first obtain the cached value whose key is the payment serial number from the Redis cache. If the value is not empty, it means this payment is a duplicate operation, and the business system directly returns the duplicate payment identifier to the caller; if the value is empty, proceed to the next operation
2. Query the DBMS for whether a corresponding instance exists based on the payment serial number. If it exists, it means this payment is a duplicate operation, and the business system directly returns the duplicate payment identifier to the caller; if not, it means this is the first operation, and proceed to the next step to complete uniqueness processing
3. Complete three operations in a distributed transaction:
Complete the payment task
Use the current payment serial number as the key and any string as the value, through set(key, value, expireTime) write the da
ta to the Redis cache
Use the current payment serial number as the primary key and write it to the DBMS together with other related data
Implementation of consumption idempotence
The solution for consumption idempotence is simple: assign a unique identifier to each message that will not be repeated. Because Message ID may be duplicated in some ca ses, truly safe idempotent processing does not recommend using Message ID as the basis for processing. The best approach is to use a business unique identifier as the key basis for idempotent processing, and the business unique identifier can be set through the message Key.
When a consumer receives a message, it can implement consumption idempotence based on the message Key, namely the order number:
Message accumulation and consumption delay
In the message processing flow, if the consumption speed of the Consumer cannot keep up with the sending speed of the Producer, the unprocessed messages in the MQ will become more and more (more in and less out), and these messages are called accumulated messages . Message accumulation in turn causes consumption delay of messages .
The following scenarios require special attention to message accumulation and consumption delay:
The following scenarios require special attention to message accumulation and consumption delay:
Continuous accumulation caused by mismatched upstream and downstream capabilities of the business system, which cannot recover by itself.
The business system has high requirements for real-time consumption of messages, and even a short consumption delay caused by accumulation is unacceptable.
Message cleanup
Messages are stored sequentially in commitlog file, and message sizes are not fixed-length, so messages cannot be cleaned up on a per-message basis, but on a per commitlog file basis. Otherwise, cleanup efficiency would drop sharply and the implementation logic would be complex.
A commitlog file has an expiration time , which defaults to 72 hours, that is, three days. In addition to manual cleanup by users, it is also cleaned up automatically in the following cases, regardless of whether the messages in the file have been consumed:
The file has expired and the cleanup time point (default 4 a.m.) has been reached, so expired files are automatically cleaned up the file has expired and the disk space usage has reached the expiration cleanup warning line (default 75%), expired files are automatically cleaned up regardless of whether the cleanup time point has been reached
when the disk usage reaches the cleanup warning line (default 85%), files are cleaned up according to the set rules, regardless of expiration. By default, cleanup starts from the oldest files
when the disk usage reaches the system danger warning line (default 90%), the Broker will reject message writes
when the disk usage reaches the cleanup warning line (default 85%), files are cleaned up according to the set rules, regardless of expiration. By default, cleanup starts from the oldest files
when the disk usage reaches the system danger warning line (default 90%), the Broker will reject message writes
Kafka
Kafka workflow
Subtopic
In Kafka messages are classified by topic , and producers produce messages and consumers consume messages, all oriented toward topic .
topic is a logical concept, while partition is a physical concept. Each partition corresponds to a log fi le, and what is stored in that log file is the data produced by producer . Data produced by Producer is continuously appended to the end of the log file, and each piece of data has its own offset. Each consumer in the consumer group records in real time which offset it has consumed to, so that it can resume consumption from the last position when an error occurs.
Kafka file storage mechanism
Because messages produced by producers are continuously appended to the end of the log file, to prevent the log file from becoming too large and causing low data location efficiency, Kafka adopts a sharding and indexing mechanism, dividing each partition into multiple segment files. Each segment corresponds to two files: the “.index” file and the “.log” file. These files are located in one folder, whose naming rule is: topic name + partition number. For example, if the first (this topic ) has three partitions, the corresponding folders are first- 0, first-1, first-2.
The index and log files are named after the offset of the first message in the current segment . The figure below shows the structure of the index file and the log file.
The “.index” file stores a large amount of index information, and the “.log” file stores a large amount of data. The metadata in the index file points to the physical offset address of the message in the corresponding data file.
Kafka producer
Partitioning strategy
Reasons for partitioning
It is convenient to scale in the cluster; each Partition can be adjusted to fit the machine it is on, and one topic can consist of multiple Partition parts, so the whole cluster can adapt to data of any size;
Concurrency can be improved because reading and writing can be done at the Partition level.
Principles of partitioning
When partition is specified, the specified value is directly used as the partiton value;
When no partition value is specified but a key is present, the key 's hash value is taken modulo the number of partition values of the topic to obtain the partition value;
When neither a partition value nor a key value is specified, an integer is randomly generated on the first call (incremented on each subsequent call), and this value is taken modulo the total number of available partition values of the topic to obtain the partition value, which is the commonly used round-robin algorithm.
Data reliability guarantee
To ensure that data sent by producer can be reliably sent to the specified topic, each partition of the topic must send an ack(acknowledgement confirmation of receipt) to the producer after receiving data sent by producer . If the producer receives the ack , it proceeds to the next round of sending, otherwise it resends the data.
Replica data synchronization strategy
ISR
After adopting the second scheme, imagine the following scenario: the leader receives data, all follower nodes start synchronizing data, but one follower, due to some failure, cannot synchronize with the leader in time, so the leader must keep waiting until it completes synchronization before it can send an ack. How can this problem be solved?
The leader maintains a dynamic in-sync replica set (ISR), meaning the follower set that keeps in sync with the leader . When the follower in the ISR completes data synchronization, the leader sends an ack to the follower . If a follower does not synchronize data with the leader for a long time, that follower will be kicked out of the ISR , and this time threshold is set by the replica.lag.time.max.ms parameter. After the Leader fails, a new leader is elected from the ISR.
ack response mechanism
For some less important data, the reliability requirement is not very high and a small amount of data loss can be tolerated, so there is no need to wait for all follower nodes in the ISR to receive successfully.
Therefore Kafka provides three reliability levels, and the user weighs reliability against latency requirements and chooses from the following configurations.
Therefore Kafka provides three reliability levels, and the user weighs reliability against latency requirements and chooses from the following configurations.
0:producer does not wait for the broker 's ack. This operation provides the lowest latency; the broker returns as soon as it receives the data, before it has actually been written to disk, so data may be lost when the broker fails;
1:producer waits for the broker 's ack. The partition 's leader returns the ack after successfully writing to disk. If the follower synchronizes successfully before the leader fails, data will be lost;
-1(all):producer waits for the broker 's ack, and the partition 's leader and follower all write to disk successfully before the ack is returned. However, if the leader fails after the follower synchronization completes but before the broker sends the ack , data duplication will occur
Failure handling details
LEO: refers to the largest offset of each replica
HW: refers to the largest offset visible to consumers, the smallest LEO in the ISR queue.
follower failure
After a follower fails it is temporarily kicked out of the ISR , Once the follower recovers, the follower reads the last HW recorded on the local disk , cuts off the part of the log file above the HW , and starts synchronizing with the leader from the HW . When the follower's LEO is greater than or equal to the Partition's HW , that is, the follower has caught up with the leader , it can re join the ISR .
leader failure
After the leader fails, a new leader is elected from the ISR . Then, to ensure data consistency among the replicas, the remaining follower nodes first cut off the part of their log files above the HW , and then synchronize data from the new leader.
Note: this can only guarantee data consistency among replicas, and cannot guarantee that data is not lost or not duplicated.
Kafka consumer
Consumption method
The consumer uses the pull (pull) mode to read data from the broker.
The disadvantage of the pull mode is that if kafka has no data, the consumer may fall into a loop and keep returning empty data. To address this, Kafka's consumer passes a duration parameter timeout when consuming data. If there is no data available to consume at the moment, the consumer waits for a while before returning, and this duration is the timeout .
The push (push) mode is difficult to adapt to consumers with different consumption rates, because the message sending rate is determined by the broker . Its goal is to deliver messages as fast as possible, but this can easily cause the consumer to be unable to process the messages in time, typically manifesting as denial of service and network congestion. The pull mode, on the other hand, can consume messages at an appropriate rate according to the consumer 's consumption capability.
Partition allocation strategy
A consumer group has multiple consumer nodes, and a topic has multiple partition nodes, so the allocation of partition is inevitably involved, that is, determining which partition is consumed by which consumer . Kafka has two allocation strategies, one is RoundRobin, the other is Range.
RoundRobin:
Range
offset maintenance
Since the consumer may experience power failures or crashes during consumption, after the consumer recovers it needs to continue consuming from the position before the failure, so the consumer needs to record in real time which offset it has consumed to, so that it can continue consuming after recov ery.
Kafka efficient data reading and writing
Sequential disk writing
Data produced by Kafka's producer is written to the log file, and the writing process is always appending to the end of the file, which is sequential writing. Official data shows that on the same disk, sequential writing can reach 600M/s, while random writing is only 100K/s. This is related to the mechanical structure of the disk; sequential writing is fast because it saves a large amount of head seeking time.
Zookeeper role in Kafka
In a Kafka cluster, one broker is elected as the Controller , responsible for managing the broker nodes going online and offline, the partition replica allocation of all topic nodes, and leader election.
Controller 's management work all depends on Zookeeper . The following is the partition 's leader election process:
Controller 's management work all depends on Zookeeper . The following is the partition 's leader election process:
Kafka transaction
Producer transaction
To implement transactions across partitions and sessions, a globally unique Transaction ID must be introduced, and the PID obtained by the Producer must be bound to the Transaction ID . In this way, after the Producer restarts, it can obtain the original PID through the ongoing Transaction ID.
In order to manage Transaction, Kafka introduces a new component Transaction Coordinator. Producer obtains the task status corresponding to the Transaction ID by interacting with the Transaction Coordinator. The Transaction Coordinator is also responsible for writing all transaction writes to an internal Topic in Kafka, so that even if the entire service restarts, the in-progress transaction state can be recovered because the transaction state has been preserved, allowing it to continue.
Consumer transactions
The above transaction mechanism is mainly considered from the Producer side; as for Consumer itself, the transaction guarantee is relatively weak, especially since it cannot guarantee that Commit information is consumed precisely. This is because Consumer can access arbitrary information via offset and different Segment File have different lifetimes, so messages from the same transaction may be deleted after a restart.
How to reduce message latency in a message queue system?
How to monitor message latency?
Kafka provides a tool called “kafka-consumer-groups.sh”
The first two columns in the figure show the basic information of the queue, including the topic name and partition name; the third column is the current consumption progress of the consumer; the fourth column is the total number of messages currently produced; the fifth column is the backlog of consumed messages (that is, the difference between the fourth column and the third column).
Subtopic
The second tool is JMX.
https://static001.geekbang.org/resource/image/33/2c/3384d3fcb52f98815fac667e5b543e2c.jpg
Monitor message latency by generating monitoring messages. How exactly do you do that?
You first define a special message, then start a monitoring program to write this message periodically into the message queue in a loop. The content of the message can be the timestamp when the message was generated, and it will also be consumed as data by a consumer of the queue. When the business processing program consumes this message, it discards it directly, while the monitoring program, upon consuming this message, can compare it with the generation time of the message; if the time difference reaches a certain threshold, it can alert us.
The right way to reduce message latency
Consumer side
Optimize the consumption code to improve performance
Increase the number of consumers (this approach is relatively simple).
However, the second approach is limited by the implementation of the message queue. If the message queue uses Kafka, you cannot improve message processing capability by increasing the number of consumers. Because in Kafka, a Topic (topic) can be configured with multiple Partition (partitions), and data is written to multiple partitions evenly or in the manner specified by the producer, then at consumption time, Kafka stipulates that one partition can only be consumed by one consumer — why is it designed this way? In my view, if multiple consumer (consumers) could consume data from one partition, a lock would be needed when operating on the consumption progress, which might have some impact on performance. Therefore, the number of topic partitions determines the degree of consumption parallelism; adding extra consumers is useless — you can improve consumer processing capability by adding partitions.
Although you cannot increase the number of consumer, you can increase the parallelism of message processing within a single consumer, so you can consider using multiple threads to increase processing capacity: you can pre-create one or more thread pools, and after receiving a message, throw it into the thread pool for asynchronous processing. In this way, the originally serial message consumption process becomes parallel consumption, which can improve the throughput of message consumption; under the premise of parallel processing, we can pull several more pieces of data in one interaction with the message queue and then distribute them to multiple threads for processing.
Message queue
Message storage
Initially, for simplicity, we used an ordinary database to store messages, but limited by the performance bottleneck of the database, the read QPS could only reach 2000. Later I refactored the storage module and used local disks as the storage medium. The existence of Page Cache can improve the speed of reading messages; even if the data has to be read from disk, since message reads are sequential and do not need to read data across the network, the QPS for reading messages has increased by an order of magnitude.
Zero-copy technology
Strictly speaking, zero copy does not mean we can eliminate data copying; it just means minimizing the number of copies. When reading data from the message queue, we are essentially sending data from disk to the consuming client over the network, and there are four data-copy steps in the implementation:
1. Data is copied from disk to the kernel buffer; 2. A system call copies the data from the kernel buffer to the user buffer; 3. The data in the user buffer is written to the Socket buffer; 4. The operating system then copies the data from the Socket buffer to the network card buffer.
The operating system provides the Sendfile function to reduce the number of data copies. With Sendfile, data in the kernel buffer is copied directly to the Socket buffer instead of to the user buffer, saving one copy and improving message sending performance. High-level languages wrap Sendfile; for example, the java.nio.channels.FileChannel class in Java provides the transferTo method, which provides the Sendfile functionality.
Will a message definitely be consumed and consumed only once?
The process of writing messages from the producer to the message queue;
The message queue is deployed independently on a separate server. Although the network between the two is an internal network, jitter may still occur; once jitter occurs, messages may be lost due to network errors.
For this situation, I recommend using message retransmission.
The storage scenario of messages in the message queue;
Taking Kafka as an example, messages in Kafka are stored on local disks. To reduce random I/O to disk when storing messages, we usually write messages first to the operating system's Page Cache and then flush them to disk at an appropriate time.
Kafka can be configured to flush data to disk only when a certain time interval has elapsed or a certain number of messages has accumulated, which is known as asynchronous flushing.
Messages in the Page Cache that have not yet been flushed to disk will be lost. So how do we solve this?
In a Kafka cluster, one Leader handles message writes and consumption, and there can be multiple Follower for data backup. Among the Follower there is a special set called ISR (in-sync replicas); when the Leader fails, the newly elected Leader is chosen from the ISR. By default, Leader data is asynchronously replicated to the Follower, so when the Leader loses power or goes down, Kafka consumes messages from the Follower, reducing the possibility of message loss.
Since messages are replicated asynchronously from the Leader to the Follower by default, once the Leader goes down, those messages that have not yet been replicated to the Follower will still be lost. To solve this problem, Kafka provides producers with an option called “acks”. When this option is set to “all”, every message sent by the producer is sent not only to the Leader but also to all the ISR, and is considered successfully sent only after confirmation is received from the Leader and all the ISR. In this way, messages will be lost only if both the Leader and all the ISR go down.
The process of messages being consumed by consumers.
I will still use Kafka as an example. A consumer's progress in consuming messages is recorded in the message queue cluster, and the consumption process is divided into three steps: receiving messages, processing messages, and updating the consumption progress.
Here, the processes of receiving and processing messages may both throw exceptions or fail; for example, network jitter during message reception may cause the message not to be received correctly; business exceptions may occur during message processing causing the processing flow not to complete. If the consumption progress is updated at this point, the failed message will never be processed again and can be considered lost.
So, what you need to note here is that the consumption progress must be updated only after message reception and processing are complete, but this can also cause the problem of message duplication. For example, if a consumer goes down right after processing a certain message, then because the consumption progress was not updated, the consumer will consume that message again after restarting.
How to ensure a message is consumed only once
Ensure that the process of message production and consumption is “idempotent”
During message production, both Kafka0.11 and Pulsar support the “producer idempotency” feature, which translates to idempotency of the production process. This feature guarantees that although messages may be duplicated at the production end, only one copy will eventually be stored in the message queue. It does this by giving each producer a unique ID and assigning a unique ID to each message produced; the server of the message queue stores a mapping of < producer ID, last message ID> . When a producer generates a new message, the message queue server compares whether the message ID is consistent with the stored last ID; if they are consistent, the message is considered a duplicate and the server automatically discards it.
Consumer side: add an optimistic lock
update user set amount = amount + 20, version=version+1 where userId=1 and version=1;
update user set amount = amount + 20, version=version+1 where userId=1 and version=1;
Container services
Docker
Kubernetes
The architecture of Kubernetes
Master
Master is the control node, deploying the control plane of Kubernetes, and is responsible for the management and control of the entire cluster
kube-apiserver
It is the “soul” of the entire Kubernetes cluster, the hub where information converges, and provides the only entry point for all internal and external API request operations. It is also responsible for capabilities such as authentication, authorization, access control, and service discovery for the entire cluster.
Users can interact with the APIServer through the command-line tool kubectl, thereby performing operations such as adding, deleting, modifying, and querying various resources in the cluster. The APIServer is very similar to BorgMaster, persisting all changes to Etcd while also keeping an in-memory copy
This is why we want the Master node to have good performance and large resource specifications, especially when the cluster is very large, the throughput of the APIServer as well as the occupied CPU and memory must be large. The APIServer also provides many extensible capabilities to facilitate enhancing its own functions
kube-scheduler
It is responsible for maintaining the state of the entire Kubernetes cluster, such as multi-replica creation and rolling updates. Kube-controller-manager is not a single component; internally it contains a group of resource controllers, which at startup use goroutine to launch multiple resource controllers. The logic of these controllers depends only on the current state, because in a distributed system there is no way to guarantee global state synchronization.
At implementation time, overly complex state machines are avoided, so each controller only operates on its own corresponding resource object. Moreover, controllers do a lot of fault-tolerant processing, such as adding a retry mechanism.
kube-controller-manager
Its job, simply put, is to watch unscheduled Pod and bind them to nodes that meet the conditions according to a predetermined scheduling strategy
Node
Node is a compute node, also called a workload node; each Node runs some workload containers.
Kubelet is responsible for maintaining the lifecycle of Pods, such as creating and deleting the containers corresponding to Pods. It is also responsible for storage and network management. It generally works together with CSI and CNI plugins.
Kube-Proxy is mainly responsible for service communication within Kubernetes, maintaining network rules on the host and providing forwarding and load balancing capabilities
Distributed storage system Etcd
It is used to store all objects and state information in the cluster. Sometimes, we also deploy the Etcd cluster together on the Master. But when the cluster node resources are sufficient, I personally suggest considering deploying the Etcd cluster separately, because the data in Etcd is crucial and the security of Etcd data must be guaranteed. Etcd uses the Raft protocol
CoreDNS is responsible for providing DNS services for the entire cluster;
Ingress Controller provides external network access capabilities for services;
Dashboard provides a GUI visual interface
Fluentd + Elasticsearch provide log collection, storage, and query capabilities for the cluster.
Pod
What is a Pod?
A Pod consists of one or more containers, as shown in the figure below. The containers in a Pod are inseparable and run as a whole on a Node node, that is, a Pod is the most atomic unit you can create and deploy in Kubernetes
Each Pod has its own independent network namespace, and all containers inside it share network resources, namely IP addresses and ports. The internal containers can communicate directly through localhost.
A Pod can mount multiple shared storage volumes (Volume), and then the internal containers can access the shared Volume for data reading and writing.
Running multiple containers in one Pod is more suitable for the following scenarios
File exchange occurs between containers, as in the example mentioned above. One writes a file and another reads it.
Containers need to communicate locally, for example through localhost or a local Socket. This approach can sometimes simplify business logic, because the business does not need to care about the address of another service and can access it locally.
Frequent RPC calls occur between containers, so for performance reasons they are placed in one Pod.
You want to add other functions to the application, such as log collection, monitoring data collection, configuration center, routing and circuit breaking. You can consider using the sidecar pattern (Sidecar Pattern), which does not require changing the logic of the original service itself and can add a series of functions. For example, Fluentd uses the sidecar pattern to inject a corresponding log agent into the Pod for log collection and forwarding. Istio also places a Sidecar container in the Pod to perform non-invasive service governance.
Why doesn't Kubernetes manage containers directly, but uses Pod to manage them?
Because using a new logical object, Pod, to manage containers allows more attributes to be added without reloading container information, and it also facilitates decoupling from the container runtime with high compatibility. For example:
The Liveness Probe can detect from the application's perspective whether a process is still alive, so problems can be quickly detected before the container has issues;
Operations that can be performed after the container starts and before it terminates; for example, before the container stops, some cleanup work may be needed, or the process cannot be ended immediately;
It defines the strategy to be adopted after the container terminates, such as always restarting, restarting only on a normal exit, etc.;
Why should a Pod be allowed to contain multiple containers?
Because a container is actually a “single-process” model, which is very important. If you start multiple processes in a container, it will bring a lot of trouble. Not only will their log records be mixed together, but their respective lifecycles cannot be managed either. After all, only one process can have PID 1; if the process with PID 1 fails or exits at this point, the other processes will naturally become “orphans” that cannot be managed and whose resources cannot be reclaimed.
Managing multiple containers with one Pod can maintain isolation between containers while ensuring environmental consistency of related containers. Using smaller-grained containers not only decouples dependencies between applications, but also facilitates development with different technology stacks, and makes it easy for development teams to reuse, reducing duplicated work.
Restart policies of Pod
Kubernetes defines the following three restart policies, which can be set in the Pod definition through the spec.restartPolicy field.
Always means always restart, which is also the default restart policy. Kubelet periodically queries the container status, and once a container is in the exited state, it performs a restart operation on it;
OnFailure means that a restart is performed only when the container exits abnormally, that is, when the exit code is not 0
Never means never restart;
Health checks in Pod
livenessProbe can be used to detect whether a container is really “running”, that is, “liveness”. If the detection fails, the kubelet will stop the container, and the subsequent operations of the container will be affected by its restart policy.
readinessProbe is often used to indicate whether a container can provide normal service requests to the outside, that is, “readiness”. For example, an nginx container cannot provide HTTP services when reloading its configuration.
To simplify some common processing logic, Kubernetes also has the following three built-in Handler for these Probe:
ExecAction can execute shell scripts inside the container;
HTTPGetAction facilitates executing HTTP Get requests to a specified port and IP address;
TCPSocketAction can perform TCP checks on a specified port;
ExecAction can execute shell scripts inside the container;
HTTPGetAction facilitates executing HTTP Get requests to a specified port and IP address;
TCPSocketAction can perform TCP checks on a specified port;
Hooks in the container lifecycle
PostStart can be executed right after the container starts. Note, however, that the execution order of this hook and the ENTRYPOINT command in the container is uncertain.
PreStop is executed before the container is terminated, in a blocking manner. Only after execution completes does Kubelet really start to destroy the container.
Like the Probe above, a hook also has similar Handler:
Exec is used to execute Shell commands;
HTTPGet can execute HTTP requests.
Exec is used to execute Shell commands;
HTTPGet can execute HTTP requests.
Deployment
We can create a ReplicaSet from a Deployment, and then create Pod from the ReplicaSet. When we update the information in the Deployment (for example, updating the image version), the deployment controller tracks the new desired state, automatically creates a new ReplicaSet, and gradually reduces the number of replicas of the old ReplicaSet until the upgrade is complete and the old ReplicaSet is completely deleted.
StatefulSet
Compared with Pod in an ordinary ReplicaSet, Pod managed by StatefulSet have several additional features.
Pods are created and destroyed in order: the individual Pod in a StatefulSet are created in sequence, and before creating a later Pod, the preceding Pod must be guaranteed to have transitioned to the ready state. To destroy a Pod in a StatefulSet, it is performed in the reverse order of creation.
Pods have stable network names: every Pod in Kubernetes has a unique name; in an ordinary replica set this is generated by random characters, while a Pod managed in a StatefulSet uses a sequenced number as its name and remains unchanged after a restart.
Pods have stable persistent storage: each Pod in a StatefulSet can have its own independent PersistentVolumeClaim resource. Even if a Pod is rescheduled to another node, its persistent disk will still be mounted to that Pod, which will be further introduced in the “container persistence” subsection.
ConfigMap
Service
How to access a Service within the cluster?
If the Service has a ClusterIP, we can directly use this virtual IP to access it.
Of course, we can also use the domain name of the Service, relying only on the internal DNS of the cluster.
How is load balancing inside the cluster implemented?
It is implemented through kube-proxy. Every node runs a kube-proxy service, which mainly watches Service and Endpoints in Kubernetes. When a Service or Endpoints changes, it calls the corresponding interface to create the corresponding rules; the common modes are mainly iptables mode and IPVS mode. The iptables mode is relatively simple and easy to use. The IPVS supports higher throughput and complex load balancing strategies; you can learn more about how IPVS mode works from the official documentation.
Currently the default working mode of kube-proxy is iptables mode
When you access through the domain name of a Service, CoreDNS first resolves the Cluster IP corresponding to the Service, that is, the virtual IP. Then, when the request reaches the host's network, it is intercepted by the iptables rules configured by kube-proxy, and then the request is forwarded to each actual backend Pod, thus achieving load balancing.
Headless Service
If, when defining a Service, we set spec.clusterIP to None, the created Service will not be assigned a Cluster IP; at this point it is called a Headless Service.
Headless Servicenginx-prod-demo-headless-svc resolves to the addresses of all backend Pod.
Users can choose which Pod to connect to; by querying the DNS record of the Service they obtain the real backend load IP address and choose which IP to connect to;
It can be used to deploy stateful services. Recall that in the StatefulSet lesson we also had a Headless Service example; each Pod managed by a StatefulSet has a separate DNS record, and the domain name remains unchanged, namely <PodName>.<ServiceName>.<NamespaceName>.svc.cluster.local. In this way, the individual Pod in a Statefulset can directly use the Pod name to resolve mutual identity and access issues.
DaemonSet
Usage scenarios of DaemonSet
Monitoring data collection, for example, node information can be collected and reported to Prometheus;
Log collection, rotation, and cleaning;
Monitor node status, for example by running node-problem-detector to monitor the status of nodes and report it to the APIServer;
Responsible for the operation of network, storage and other components on each node, such as glusterd, ceph, flannel etc.
Collect
Collect
0 Comments
Next Page