Update same field from multiple transaction I have a service which makes some manipulations in DB, everything is working normally until I tried to make two requests in parallel.

Below see the sql debug log:

Executing (2c4cb493-7090-4a83-942a-1b3078a96a7b): START TRANSACTION;
Executing (f49986af-9741-4f20-94ba-0644fbafea05): START TRANSACTION;
Executing (2c4cb493-7090-4a83-942a-1b3078a96a7b): INSERT INTO `history` (`id`,`value`) VALUES (DEFAULT,'value data');
Executing (f49986af-9741-4f20-94ba-0644fbafea05): INSERT INTO `history` (`id`,`value`) VALUES (DEFAULT,'value data');
Executing (2c4cb493-7090-4a83-942a-1b3078a96a7b): UPDATE `table_2` SET `count`=count + 1 WHERE `id` = 1
Executing (f49986af-9741-4f20-94ba-0644fbafea05): UPDATE `table_2` SET `count`=count + 1 WHERE `id` = 1
Executing (2c4cb493-7090-4a83-942a-1b3078a96a7b): COMMIT;
Executing (f49986af-9741-4f20-94ba-0644fbafea05): ROLLBACK;

Deadlock found when trying to get lock; try restarting transaction


I don't understand why a transaction does not wait for another to end, but a Deadlock exception is thrown?

Thanks.
Databases are designed to support multiple concurrent users.  "Waiting for the other transaction to finish" is mutually exclusive with that requirement.  The ability to support multiple concurrent users is why you use a Database instead of flat files.

You must design your algorithm accordingly.

In your example, you want to serialize this process.  (note:  Serialization is the same as setting the configuration parameter SLOW=TRUE)

You can serialize this process by putting a Row Lock on Table_2 first.  In MySQL (and other RDBMS), you do that by using the SELECT ... FOR UPDATE syntax at the beginning of the transaction.

The process should look like this:

START TRANSACTION;
select count from test_2 where id=1 for update;
INSERT INTO `history` (`id`,`value`) VALUES (DEFAULT,'value data');
UPDATE `table_2` SET `count`=count + 1 WHERE `id` = 1;
commit;