Database / Mnesia intermediate to advanced Interview questions
How can you redesign a schema to reduce lock contention on a frequently-updated record?
The core fix is usually to split one hot, shared record into several independent pieces that different transactions can update without contending for the same lock, then combine them only when actually reading a final value.
%% instead of one shared counter record: %% #counter{name = hits, value = N} %% shard it across several independent records: %% #counter_shard{shard_id = 1, value = N1} %% #counter_shard{shard_id = 2, value = N2} %% ... %% writers pick a shard (e.g. by process/PID hash) to update independently; %% readers sum across all shards for the total.
Other common techniques: moving the hot value to a dirty operation if strict consistency on every single increment isn't actually required (accepting some race potential in exchange for no locking at all), batching many logical updates into fewer actual writes (aggregate in a process's own state, flush periodically), or restructuring the data model so what looked like "one shared thing everyone updates" is actually several independent things that only need to be reconciled occasionally.
More Related questions...