Batch cache population
Write several related cache entries while reducing client-server round trips.
Redis · Module
MSET atomically assigns string values to one or more keys in a single command. Existing values are overwritten, and a successful command returns OK.
MSET accepts one or more key-value pairs and writes every pair as a single atomic operation. Existing values are replaced, and the command returns OK when the operation completes successfully.
MSET key value [key value ...]| Name | Type | Description |
|---|---|---|
key | string | A key whose string value will be written. |
value | string | The string value assigned to the preceding key. |
key value ... | repeated key-value pairs | Additional key-value pairs; at least one pair is required. |
Simple string reply: OK.
MSET user:1 Alice user:2 Bob
GET user:1
GET user:2Stores two string values in one command, then reads them back.
Write several related cache entries while reducing client-server round trips.
Replace a group of string values so readers see either the old or complete new state.
Initialize multiple independent string keys in one request.
MSET writes multiple string key-value pairs in one command and replaces values that already exist. It is atomic, so clients cannot observe only part of the batch.
Follow-up: How does its complexity scale? It is O(N), where N is the number of keys being set.
The command takes alternating keys and values: MSET key value [key value ...]. It returns the simple string reply OK because the command cannot fail under its documented conditions.
Follow-up: What would you use to avoid overwriting existing keys? MSETNX, which provides conditional multi-key creation.
MSET is useful for reducing round trips when several string values must be written together. In clustered deployments, however, its multi-key behavior varies, so key placement must be considered.
Follow-up: What cluster constraint should be investigated? Whether the participating keys can be handled together according to Redis cluster multi-key operation rules.
MSETNXMGETSETmulti-key operations