Junior — Middle
What is the best way to organize temporary data storage in a system?
sobes.tech AI
Answer from AI
For storing temporary data in the system, it is best to use specialized storage solutions that support automatic deletion or expiration of data. In the context of Golang and server applications, the following approaches are often used:
- In-memory caches: for example, using libraries like
groupcacheorbigcachefor fast storage and access to temporary data. - Redis: a popular solution for storing temporary data with TTL (time-to-live) support, which allows automatic removal of outdated records.
- Temporary tables in a database: if data needs to be accessible across service restarts, tables with a time field and periodic cleanup can be used.
Example of using Redis with TTL in Go:
import (
"github.com/go-redis/redis/v8"
"context"
"time"
)
ctx := context.Background()
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
// Set a key with a TTL of 10 minutes
err := client.Set(ctx, "tempKey", "someValue", 10*time.Minute).Err()
if err != nil {
panic(err)
}
Thus, the choice depends on requirements for availability, data volume, and lifetime.