akcoban
akcoban

Reputation: 973

What happens when multiple requests come to server

I am not sure about this topic. I'll try to explain that with examples.

Let's suppose, I have a payment method on php webserver. Firstly the method checks are there unpaid orders. If yes, send request to bank servers to charge from the credit card.

Now, client sent two consecutive requests to the server. While first request waiting for response from the bank servers to charge, second request came to same method. What'll do web servers if requests sent from same clients or the second request sent from another client? I thought on same clients, they should be put in order so there's no problem. But on different clients? Can there be a bug which charge payment from the card twice?

Also, what happens on java, go or node.js servers? How works that handler system on multi-thread or single-thread languages?

Don't focus the payment method. That's only an example.

Upvotes: 1

Views: 3518

Answers (1)

AterLux
AterLux

Reputation: 4654

Even if the request made from a new tab by the same user, the web server starts a new thread. (That is generally speaking. Although some imaginary server can perform them in queue in a single thread, but usually they are multithreaded and do not care about users) So, requests are performed simultaneously.

It is your responsibility to take care about synchronization. So, although php is a single-threaded language, when writing a script always keep in mind another instance or your script can be running in parallel.

For example, if scripts are reading and writing from/to files, they should lock files. (See flock)

When queries to a database are performed, they have to be done in transactions. (See START TRANSACTION, ROLLBACK, COMMIT for example, also SELECT ... FOR UPDATE).

I.e. in example with payments is may be somthing like

  START TRANSACTION; -- starts the transaction
  SELECT needed, data FROM table_with_payments FOR UPDATE; 
  -- any other script selecting these rows will be locked until this one release the transaction
  UPDATE table_with_payments WHERE this = that ... ; -- update 
  COMMIT; -- ends transaction, applying all the changes at once

Upvotes: 2

Related Questions