Skip to content

Commit 7de6a6d

Browse files
committed
perf: pipeline HMSET and EXPIREAT in Redis and Predis cache handlers
Send HMSET and EXPIREAT together in a single pipeline round trip rather than issuing two sequential network requests on every cache save. For normal cache usage, behavior and data structures remain identical. In error scenarios where HMSET fails (e.g. key contains a non-hash type), the pipelined EXPIREAT will still execute on the existing key, while save() returns false as expected.
1 parent 27a1e6a commit 7de6a6d

2 files changed

Lines changed: 24 additions & 10 deletions

File tree

‎system/Cache/Handlers/PredisHandler.php‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -118,15 +118,20 @@ public function save(string $key, mixed $value, int $ttl = 60): bool
118118
return false;
119119
}
120120

121-
if (! $this->redis->hmset($key, ['__ci_type' => $dataType, '__ci_value' => $value]) instanceof Status) {
122-
return false;
123-
}
121+
$fields = ['__ci_type' => $dataType, '__ci_value' => $value];
124122

125123
if ($ttl !== 0) {
126-
$this->redis->expireat($key, Time::now()->getTimestamp() + $ttl);
124+
// Send HMSET and EXPIREAT in a single round trip.
125+
$expiresAt = Time::now()->getTimestamp() + $ttl;
126+
$results = $this->redis->pipeline(static function ($pipe) use ($key, $fields, $expiresAt): void {
127+
$pipe->hmset($key, $fields);
128+
$pipe->expireat($key, $expiresAt);
129+
});
130+
131+
return is_array($results) && ($results[0] ?? null) instanceof Status;
127132
}
128133

129-
return true;
134+
return $this->redis->hmset($key, $fields) instanceof Status;
130135
}
131136

132137
public function delete(string $key): bool

‎system/Cache/Handlers/RedisHandler.php‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -134,15 +134,24 @@ public function save(string $key, mixed $value, int $ttl = 60): bool
134134
return false;
135135
}
136136

137-
if (! $this->redis->hMset($key, ['__ci_type' => $dataType, '__ci_value' => $value])) {
138-
return false;
139-
}
137+
$fields = ['__ci_type' => $dataType, '__ci_value' => $value];
140138

141139
if ($ttl !== 0) {
142-
$this->redis->expireAt($key, Time::now()->getTimestamp() + $ttl);
140+
// Send HMSET and EXPIREAT in a single round trip.
141+
$pipeline = $this->redis->multi(Redis::PIPELINE);
142+
143+
if ($pipeline === false) {
144+
return false;
145+
}
146+
147+
$pipeline->hMset($key, $fields);
148+
$pipeline->expireAt($key, Time::now()->getTimestamp() + $ttl);
149+
$results = $pipeline->exec();
150+
151+
return is_array($results) && (bool) ($results[0] ?? false);
143152
}
144153

145-
return true;
154+
return (bool) $this->redis->hMset($key, $fields);
146155
}
147156

148157
public function delete(string $key): bool

0 commit comments

Comments
 (0)