Cho mình hỏi về việc thay đổi data trong hệ thống microservice
Mình cho ví dụ cụ thể như hệ thống ngân hàng. Người dùng ở ATM rút tiền, hệ thống backend yêu cầu phải đáp ứng nhanh, nên sẽ chạy theo mô hình client-server asynchronous
- Người dùng ra lệnh rút tiền, lệnh được gửi về 1 service trong backend
- Service đó sẽ kiểm tra tính hợp lệ, nếu hợp lệ thì service gửi 1 message cho service khác xử lý tiếp, cụ thể là yêu cầu update DB
- Và service đó return kết quả thành công về client (ATM) và không cần chờ kết quả của service kia
- Như vậy ngay lúc đó, data ở DB hoàn toàn chưa update
- Nếu sau đó người dùng query lại số dư, thì không thể query trực tiếp từ DB ra được (do chưa update)
Có khả năng mình cần cache cho 1 user đã rút tiền ở trên hay không ? Nghĩa là service đầu tiên sẽ add/update vô cache. Sau đó nếu người dùng query lại số dư, thì sẽ đọc từ cache thay vì đọc từ DB ra ?
4 ANSWERS
Đối với các hệ thống ngân hàng, bạn không nên áp dụng cache và Async việc update DB. Bởi vì các giao dịch ngân hàng bắt buộc phải strong consistency. Nếu lỡ như bạn đã gửi lại thông tin cho user là chuyển tiền thành công nhưng việc update DB lỗi hoặc lỗi máy ATM thì thông tin user nhận là sai. Ngoài ra còn gặp những vấn đề liên quan tới race condition nữa. Lưu trên cache cũng gặp rủi ro nếu như redis cache sập thì dữ liệu sẽ mất hết. Cách giải quyết có thể như sau:
Bước 1: Giữ chỗ (Hold/Freeze/Authorize) - Đồng bộ (Synchronous)
- Ví dụ khi bạn bấm rút 2 triệu: Service tiếp nhận lệnh và gọi đồng bộ xuống DB.
- Hệ thống sẽ thực hiện một lệnh Lock số dư của User đó (ví dụ: SELECT balance FROM accounts WHERE id = x FOR UPDATE).
- Kiểm tra số dư. Nếu đủ, hệ thống không trừ tiền ngay, mà chuyển 2 triệu đó vào trạng thái "Hold" (Tạm giữ/Phong tỏa).
- Lúc này, số dư khả dụng (Available Balance) giảm đi 2 triệu, nhưng số dư thực tế (Current Balance) vẫn giữ nguyên. Thao tác này diễn ra bằng một Transaction trong DB cực kỳ nhanh (vài mili-giây).
Bước 2: Ra lệnh cho ATM (Synchronous) Sau khi đã Hold tiền thành công trong DB, backend trả kết quả Đồng bộ về cho ATM: "Tôi đã giữ tiền an toàn, anh hãy nhả tiền mặt cho khách đi".
Bước 3: Đẩy tiền và Hoàn tất (Settle) hoặc Hủy (Rollback)
- Kịch bản 1 (Thành công): ATM nhả tiền thành công -> ATM gửi tín hiệu Confirm về Backend -> Backend thực hiện Deduct (Trừ hẳn) 2 triệu đang bị Hold trong DB (Thao tác này có thể chạy Async hoặc Sync tùy kiến trúc kiến tạo).
- Kịch bản 2 (Thất bại/Kẹt tiền): ATM không nhả được tiền -> Gửi tín hiệu Cancel về Backend -> Backend thực hiện Unhold (Giải phóng) 2 triệu đó lại cho khách hàng.
Cho mình hỏi thêm, câu lệnh SELECT ... WHERE ... FOR UPDATE nó chỉ tạo exclusive lock cho vài row. Nếu có transaction khác thực thi đồng thời, cũng dùng câu lệnh trên nhưng ở các row khác, thì nó vẫn chạy song song bình thường phải không ?
SELECT ... WHERE ... FOR UPDATE chỉ tạo exclusive lock cho những row theo điều kiện WHERE. Nếu có transaction khác thực thi đồng thời những row khác thì nó vẫn chạy song song bình thường nhé. Mà dùng cách này thì cẩn thận là ở điều kiện WHERE, cột cần WHERE phải có index. Nếu không có index thì DB sẽ phải quét toàn bộ bảng (Full Table Scan). Dẫn tới database sẽ khóa toàn bộ các dòng mà nó quét qua và khóa sạch cả bảng.
@ngoctuyen cho mình hỏi thêm về câu trả lời của bạn, bước 3. Ở kịch bản 1, nếu dùng async, thì khi đó data chưa được update kịp. Và nếu vài phút sau người dùng query balance, thì sẽ đọc data ở đâu để lấy kết quả chính xác (do lúc nãy đã rút 2tr nhưng DB chính vẫn chưa được update) ?
@ninja Cảm ơn câu hỏi của bạn, có lẽ chúng ta cần thay đổi kiến trúc, không nên update trực tiếp balance. Trong các hệ thống ngân hàng thì chúng ta không update trực tiếp cột balance, vì chúng ta cần lưu trữ lại lịch sử của những lần rút tiền. Cách giải quyết là chúng ta sẽ có một bảng là Holding chỉ để lưu giá trị số dư cần trừ của tài khoản, bảng này sẽ có cột status gồm 2 giá trị là PENDING và COMPLETED Ví dụ tài khoản đang có current_balance = 10 triệu Ở bước 1 khi ATM yêu cầu rút 2 triệu, nó phải được thực hiện đồng bộ, nó sẽ tạo một record trong bảng Holding với số tiền holding là 2 triệu và status là PENDING. Khi người dùng check số dư, backend sẽ tính available_balance = current_balance - holding = 8 triệu. Ở bước 3 sau khi ATM yêu cầu update DB async. Mặc dù DB chưa được update nhưng giá trị available_balance = current_balance - holding = 8 triệu, giá trị trả về cho người dùng luôn đúng. Việc update DB bao gồm update available_balance = 8 triệu, status của holding là COMPLETED 2 tác vụ update phải được đặt trong 1 transaction. Điều này đảm bảo người dùng luôn nhận được số dư chính xác. Tất nhiên với cách tiếp cận này, chúng ta sẽ gặp một vấn đề khác là Dual Write, giải quyết vấn đề này là một bài toán khác. Nếu có gì không hợp lý, bạn có thể hỏi mình, mình nghĩ sẽ còn nhiều vấn đề với cách tiếp cận này. 🤔
@ngoctuyen Mình nghĩ có thể tạo bảng Holding thuộc cùng 1 DB server với bảng chính chứa balance, việc update bảng Holding, status là COMPLETE và update balance cho bảng chính có thể để vô 1 transaction trong store procedure, nếu 1 trong 2 bảng update failed thì sẽ rollback, nên mình nghĩ đã giải quyết được vấn đề dual write rồi.
Nếu bạn đang hỏi về việc thay đổi dữ liệu (data) trong hệ thống microservices và cách xử lý "đúng", thì đây là một trong những vấn đề quan trọng nhất của kiến trúc microservices.
Có một số nguyên tắc phổ biến:
Mỗi service sở hữu database của riêng mình
Không service nào được update trực tiếp database của service khác.
Ví dụ:
User Service → User DB
Order Service → Order DB
Payment Service → Payment DB
Muốn thay đổi dữ liệu của service khác thì gọi API
Thay vì:
UPDATE user SET status='VIP'
từ Order Service.
Thì:
Order Service ↓ Call User Service API ↓ User Service update DB
Dùng Event-driven khi cần đồng bộ dữ liệu Ví dụ:
Order Created ↓ Publish Event (Kafka/RabbitMQ) ↓ Payment Service Inventory Service Notification Service
Mỗi service tự cập nhật dữ liệu của mình sau khi nhận event.
Chấp nhận Eventual Consistency Trong microservices, dữ liệu thường không đồng bộ ngay lập tức giữa các service. Thay vào đó, hệ thống hướng đến eventual consistency, tức là sau một khoảng thời gian ngắn, các service sẽ đạt trạng thái nhất quán. Xử lý transaction Không nên dùng transaction xuyên nhiều database như trong monolith. Thay vào đó, thường sử dụng: Saga Pattern Compensation Transaction Outbox Pattern để đảm bảo event không bị mất khi ghi dữ liệu và phát sự kiện. Ví dụ
Giả sử hệ thống thương mại điện tử:
Customer đặt hàng │ ▼ Order Service │ ├── Lưu Order └── Publish OrderCreated │ ┌──────────┼──────────┐ ▼ ▼ ▼ Inventory Payment Notification Service Service Service Order Service chỉ cập nhật dữ liệu đơn hàng. Inventory Service tự trừ tồn kho. Payment Service tự tạo giao dịch thanh toán. Notification Service gửi email hoặc SMS.
Các service không cập nhật trực tiếp database của nhau mà phối hợp thông qua API hoặc event.
Nếu bạn đang chuẩn bị cho phỏng vấn, một câu trả lời ngắn gọn có thể là:
"Trong kiến trúc microservices, mỗi service sở hữu dữ liệu của riêng mình. Khi cần thay đổi dữ liệu liên quan đến service khác, service sẽ gọi API hoặc phát event thay vì truy cập trực tiếp database của service đó. Để đảm bảo tính nhất quán, hệ thống thường sử dụng Event-driven Architecture kết hợp các mẫu như Saga hoặc Outbox Pattern, chấp nhận eventual consistency thay vì transaction phân tán."
Understanding the Importance of a US Social Security Number (SSN) in Everyday Life
30% discount on the occasion of New Year Bank service Crypto service Social accounts service Email service Review service Others service in 2026 order now
If you want to more information just contact now.
24 Hours Reply/Contact
➤Email: smmtopitworld@gmail.com
➤WhatsApp:+1 (587) 673-1518
➤Telegram:@SmmTopITWorld
To Buy More Such Verified Accounts Visit: https://smmtopitworld.com/
Have you ever pondered what precisely a Social Security Number (SSN) is and why it’s so critical in the Joined together States? The SSN is a interesting nine-digit identifier that is doled out to people by the Social Security Organization. It was to begin with presented in 1936 as a way to track workers’ profit for Social Security benefits. Over the a long time, the SSN has ended up a key piece of individual recognizable proof utilized for a wide extend of purposes, from opening a bank account to applying for a job. Your SSN is a pivotal piece of data that is tied to your character and can have genuine suggestions if it falls into the off-base hands. It is utilized by money related educate, government organizations, and bosses to confirm your personality and track critical data such as your credit history and profit. In any case, the broad utilize of SSNs has moreover made them a target for personality robbery and extortion. It’s critical to get it how to secure your SSN and take steps to defend your individual data in an progressively computerized world. Buy SSN Number Purpose of SSN Numbers? Social Security Numbers, more commonly known as SSN numbers, are a special nine-digit distinguishing proof number doled out to people in the Joined together States by the Social Security Organization. These numbers are utilized for a assortment of purposes, but basically they serve as a way to track individuals’ profit and screen their benefits from the Social Security Administration. The essential reason of SSN numbers is for recognizable proof and confirmation purposes. When you apply for a work, open a bank account, apply for credit, or record your charges, you will likely be inquired to give your SSN number. This is since your SSN number is straightforwardly connected to your personality and budgetary history, making it an vital instrument for confirming who you are and guaranteeing that you are who you say you are. Buy SSN Number Another key reason of SSN numbers is for following profit and benefits. Your SSN number is utilized by the Social Security Organization to track your profit all through your lifetime and decide the sum of Social Security benefits you are qualified to get when you resign. This data is significant for guaranteeing that people get the benefits they are entitled to based on their profit history. Who is Qualified for an SSN? The Social Security Number (SSN) is a one of a kind nine-digit number that is issued by the Social Security Organization (SSA) to people living in the Joined together States. It serves as a way to track people for Social Security benefits, as well as for other government programs and services. Buy SSN Number But who is really qualified to get an SSN? In common, anybody who is lawfully permitted to work in the Joined together States is qualified to apply for and get an SSN. This incorporates US citizens, lasting inhabitants, and a few noncitizens who are authorized to work in the country. US citizens are ordinarily alloted an SSN at birth, as portion of the application prepare for a birth certificate. Be that as it may, if for a few reason an person does not have an SSN, they can apply for one at any point in their life. This can be done by filling out an application shape at a Social Security office and giving the essential documentation to demonstrate their character and citizenship status. Permanent inhabitants, too known as green card holders, are moreover qualified to get an SSN. They can apply for one by filling out the same application frame and giving verification of their movement status. This is vital for lasting inhabitants who arrange to work in the US and pay charges, as an SSN is required for both purposes. Buy SSN Number How to Apply for an SSN? If you are a US citizen or legitimate inhabitant, getting a Social Security Number (SSN) is an basic step in your travel. Your SSN serves as a special identifier that permits you to lawfully work and get benefits in the Joined together States. Here’s a breakdown of how you can apply for an SSN. The to begin with step in applying for an SSN is to accumulate all the fundamental archives. You will require to give confirmation of your character, age, and citizenship or lawful residency status. Worthy shapes of distinguishing proof incorporate your birth certificate, visa, and driver’s permit. You may too require to give records such as your migration records or work authorization if you are a non-citizen. Once you have your archives in arrange, you will require to fill out an Application for a Social Security Card (Frame SS-5). You can download this shape from the Social Security Organization (SSA) site or choose up a duplicate at your neighborhood SSA office. Make beyond any doubt to fill out the shape precisely and honestly to maintain a strategic distance from any delays in handling your application. Buy SSN Number After completing the application frame, you will require to yield it along with your supporting reports to your closest SSA office. You can discover the area of your nearby SSA office on the SSA site or by calling their toll-free number. When submitting your application, be arranged to reply any questions the SSA agent may have with respect to your reports or application. Security and Protection Concerns with SSN Numbers? One of the most squeezing security concerns with SSNs is personality robbery. With get to to someone’s SSN, pernicious people can effortlessly imitate that individual and pick up get to to their money related accounts, restorative records, and other delicate data. This can lead to a have of issues, counting money related misfortune, harm to one’s credit score, and indeed legitimate inconveniences. It is vital, in this manner, to protect your SSN and as it were share it with trusted substances when completely necessary. Buy SSN Number Another security concern with SSNs is information breaches. In later a long time, there have been various high-profile cases of programmers picking up unauthorized get to to databases containing delicate data, counting SSNs. Once gotten, these numbers can be sold on the dull web, where they get a tall cost due to their esteem in carrying out false exercises. To ensure against this, organizations must prioritize the security of their frameworks and actualize strong conventions to anticipate unauthorized get to to SSNs and other individual data. FAQ: How do I get an SSN? You can apply for an SSN by filling out Frame SS-5 and giving the essential documentation, such as a birth certificate, verification of personality, and verification of citizenship or migration status. Is an SSN the same as a assess distinguishing proof number (TIN)? While both an SSN and a TIN are utilized for assess purposes, an SSN is particularly relegated to people by the Social Security Organization, though a TIN can be relegated to people or businesses by the IRS. Buy SSN Number Can I have more than one SSN? No, people are as it were doled out one SSN for their lifetime. Having more than one SSN is unlawful and can result in genuine consequences. What ought to I do if my SSN is stolen? If your SSN is stolen, you ought to report it to the Social Security Organization and the Government Exchange Commission as before long as conceivable to avoid character theft. Can I alter my SSN? In common, people are not permitted to alter their SSN unless they have a substantial reason, such as being a casualty of personality robbery or encountering harassment. Buy SSN Number Do children require an SSN? Yes, children require an SSN in arrange to be claimed as dependents on a charge return and to apply for government benefits. Can undocumented foreigners get an SSN? Undocumented migrants are not qualified to get an SSN, unless they have a substantial work authorization from the Division of Country Security. How long does it take to get an SSN after applying? It ordinarily takes around two weeks to get your SSN after applying, in spite of the fact that preparing times may change depending on the volume of applications. Buy SSN Number Can I utilize my SSN as a shape of identification? While your SSN can be utilized for certain purposes, such as confirming your personality for assess purposes, it is not considered a substantial frame of recognizable proof in most cases. What ought to I do if I disregard my SSN? If you disregard your SSN, you can contact the Social Security Organization to ask a substitution card or get to your number online through your My Social Security account. Buy SSN Number How can I secure my SSN from character theft? To secure your SSN from character robbery, you ought to never share it with anybody unless completely fundamental, screen your credit reports frequently, and shred any reports containing your SSN some time recently arranging of them. Can I utilize somebody else’s SSN? Using somebody else’s SSN without their authorization is illicit and can result in criminal charges and serious penalties. Buy SSN Number In conclusion Social Security Numbers (SSNs) are interesting recognizable proof numbers relegated to people by the Social Security Organization. These nine-digit numbers play a significant part in a assortment of exchanges, from applying for a work to recording charges. It is imperative to ensure your SSN from potential extortion and character burglary by as it were sharing it when vital and keeping it secure. Understanding the part of SSNs can offer assistance you explore the different circumstances in which they are utilized and secure your individual data.
30% discount on the occasion of New Year Bank service Crypto service Social accounts service Email service Review service Others service in 2026 order now If you want to more information just contact now. 24 Hours Reply/Contact ➤Email: smmtopitworld@gmail.com ➤WhatsApp:+1 (587) 673-1518 ➤Telegram:@SmmTopITWorld To Buy More Such Verified Accounts Visit: https://smmtopitworld.com/