Back to all questions

ACID - Consistency

Devs Hive

Devs Hive

Seen on interview: 1 user

Consistency in ACID means that every transaction moves the database from one valid state to another valid state without breaking the rules and logic of the system.

When it comes to implementing Consistency, the most effective approach is to move as many rules as possible to the database level instead of keeping them in the business logic layer.

For example, instead of validating data in the service layer, we can move the validation into Constraints or Triggers.

DROP TABLE IF EXISTS accounts;

CREATE TABLE accounts (
id bigserial PRIMARY KEY,
owner text NOT NULL,
balance numeric(12,2) NOT NULL,
-- Замість того, щоб тримати валідацю в сервісах ми робимо це на рівні бази даних
-- Таким чином, ми узгоджуємо те, що balance не може бути меншим, ніж 0
CONSTRAINT accounts_balance_nonneg CHECK (balance >= 0)
);

INSERT INTO accounts(owner, balance) VALUES
('Alice', 50.00),
('Bob', 10.00);
-- Тепер пробуємо запустити транзакцію
BEGIN;

-- Хочемо зняти 100 у Alice, але в неї 50
-- Так як ми маємо Constraint, який забезпечує те що баланс не може бути меншим, ніж 0
-- При виконанні такої транзакції ми отримаємо ROLLBACK так як узгодженість даних була порушена
UPDATE accounts
SET balance = balance - 100
WHERE owner = 'Alice';

COMMIT;

The main thing to remember is that the most reliable way to ensure Consistency is to enforce rules at the data level. That said, overusing native DB tools is not always a good idea, because it makes the system more complex. That is why in real life, data consistency is always about компроміси between simplicity and reliability.

Seen on interview?

Comments (0)

Sign in to leave a comment

No comments yet. Be the first!