These days, I need to write a serial number generator API. The logic is simple. Every time a http request is sent to the API, the API returns a continuous serial number. The simple pseudo code is as follows:
- Read the last number saved in the database, defined as lastNumber
- lastNumber plus 1, and return it to the client.
Then, I got questions about concurrency. If multiple requests are sent to the Generator API at the same time, what will happen? The questions I think about are as follows:
- NodeJs is a single-thread language, and it only processes one request at a time. Under normal circumstances, the generator should generate 001, 002, 003... in sequence. When there are a large number of requests sent to API at the same time, will they all get the same last serial number from the database, thus returning a duplicate serial number? For example, several requests read lastNumber as 001 at the same time, so they all return 002.
After reading many articles, this one helps the most. How, in general, does Node.js handle 10,000 concurrent requests? There is a diagram that explains nodeJs processing requests
- Single request
user do an action
│
v
application start processing action
└──> make database request
└──> do nothing until request completes
request complete
└──> send result to user
- Multiple requests
request A ──> make database request
request B ──> make database request
request C ──> make database request
database request complete ──> send response A
database request complete ──> send response B
database request complete ──> send response C
Here comes my other question. What counts as a complete DB request? The Request of the Generator API to the database is one read + one write. Read LastNumber, and Write LastNumber+1. Is the DB request complete when both actions are completed?
Because Node is a single thread, when the database is handling the requests, Node will not be idle. It will continue to process request B, request C. Then, How far will "make DB request" of request B go? Please refer to the diagram below. The numbers are the order in which the actions are completed in my imagination.
(1) request A ──> make database request ––>(4) DB handle requests (read 001) (write 002)
(2) request B ──> make database request ––>(??)Questions: the order of process? How far will it go, then stop and wait
(3) request C ──> make database request
(5) database request complete ──> send response A
database request complete ──> send response B
database request complete ──> send response C
When (4) is not completed, How far will "make DB request" go? Since the lastNumber in DB needs to be updated to 002, request B can successfully return 003.
I don't know whether Transaction mechanism is part of the answers to my questions.
The questions may not be clearly sorted out. If you need clarification, please feel free to raise it. I will try my best to elaborate. Thank you~