@@ -171,9 +171,40 @@ func (c *Cache[K, V]) Set(ctx context.Context, key K, value V, ttl time.Duration
171171 return nil
172172}
173173
174+ // SetAsync adds or updates a value in the cache with optional TTL, handling persistence asynchronously.
175+ // Key validation and in-memory caching happen synchronously. Persistence errors are logged but not returned.
176+ // Returns an error only for validation failures (e.g., invalid key format).
177+ func (c * Cache [K , V ]) SetAsync (ctx context.Context , key K , value V , ttl time.Duration ) error {
178+ var expiry time.Time
179+ if ttl > 0 {
180+ expiry = time .Now ().Add (ttl )
181+ } else if c .opts .DefaultTTL > 0 {
182+ expiry = time .Now ().Add (c .opts .DefaultTTL )
183+ }
184+
185+ // Validate key early if persistence is enabled (synchronous)
186+ if c .persist != nil {
187+ if err := c .persist .ValidateKey (key ); err != nil {
188+ return err
189+ }
190+ }
191+
192+ // ALWAYS update memory first - reliability guarantee (synchronous)
193+ c .memory .setToMemory (key , value , expiry )
194+
195+ // Update persistence asynchronously if available
196+ if c .persist != nil {
197+ go func () {
198+ if err := c .persist .Store (ctx , key , value , expiry ); err != nil {
199+ slog .Warn ("async persistence store failed" , "error" , err , "key" , key )
200+ }
201+ }()
202+ }
203+
204+ return nil
205+ }
206+
174207// Delete removes a value from the cache.
175- //
176- //nolint:revive // confusing-naming - standard cache operation
177208func (c * Cache [K , V ]) Delete (ctx context.Context , key K ) {
178209 // Remove from memory
179210 c .memory .deleteFromMemory (key )
@@ -194,8 +225,6 @@ func (c *Cache[K, V]) Delete(ctx context.Context, key K) {
194225
195226// Cleanup removes expired entries from the cache.
196227// Returns the number of entries removed.
197- //
198- //nolint:revive // confusing-naming - standard cache operation
199228func (c * Cache [K , V ]) Cleanup () int {
200229 return c .memory .cleanupMemory ()
201230}
@@ -206,8 +235,6 @@ func (c *Cache[K, V]) Len() int {
206235}
207236
208237// Close releases resources held by the cache.
209- //
210- //nolint:revive // confusing-naming - standard cache operation
211238func (c * Cache [K , V ]) Close () error {
212239 if c .persist != nil {
213240 if err := c .persist .Close (); err != nil {
0 commit comments