Recommended Free Tools
Redis strings are binary-safe values for text, serialized objects, cache fragments, tokens, and counters. Use SET to create or replace a value and GET to read it; add conditional flags such as NX or XX, expiration options such as EX or PX, and atomic counter commands when the write must be coordinated by Redis rather than by application code.
Antihost offers Linux VPS plans with full root access, unlimited traffic on a 1 Gbps port and a 14-day free trial.
What a Redis string is
A Redis string is a binary-safe value. It can contain ordinary text, serialized application data, an HTML fragment, a token, or arbitrary bytes. Redis does not interpret the contents as a particular object model: your application decides whether the bytes represent UTF-8 text, JSON, a serialized object, or something else.
As an Amazon Associate I earn from qualifying purchases.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
This makes strings a good fit for scalar values and opaque payloads. Typical examples include a rendered page fragment, a session token, a feature flag, a cached API response, or a number used as a counter. A string is less suitable when you need to update individual fields inside a record. In that case, a hash or Redis JSON provides field-level access without repeatedly reading and rewriting one large blob.
Set and get one value
Write a value with SET
The basic command is:
SET user:42:name "Ada"
SET creates the key if it does not exist. If the key already contains a string, it replaces that value. Redis documentation describes this as setting the string value of a key while ignoring its previous value type; in practice, your application should still use consistent key naming and data types so that unrelated code does not collide on the same key.
#1 Best Overall
Keys are conventionally namespaced with a colon. A pattern such as user:42:name makes ownership and purpose visible, while names such as cache:homepage or page:views make operational behavior easier to recognize.
Read a value with GET
GET user:42:name
GET returns the current string value. If the key does not exist, Redis returns a null response, which your client library may expose as null, nil, or a similar missing-value result. Distinguish that result from an existing key whose value is an empty string; they have different meanings for cache misses, defaults, and application validation.
Type errors and key ownership
String commands operate on keys containing strings. If another part of the application stores a list, set, hash, or another Redis type under the same key, a string command can fail with a wrong-type error. Use a stable naming convention and document which component owns each key. If you intentionally need to replace a key of another type, remove it first only when doing so is safe for all writers; an unconditional delete can destroy data owned by another operation.
Prevent accidental overwrites with conditional SET
A client-side sequence of GET, a decision, and SET has a race window: another writer can change the key between the read and write. Redis lets the server make the condition part of one SET operation.
Create only when absent with NX
SET cache:homepage "<html>..." EX 300 NX
NX means “only if the key does not exist.” It is useful for one-time initialization, lock-style ownership markers, and cache population where an existing value must win. If the key already exists, Redis does not replace it and the command reports that the condition was not satisfied.
Update only when present with XX
SET profile:42:status "active" XX
XX means “only if the key already exists.” Use it when creating a missing key would hide an initialization error or when a refresh operation must not create a new record accidentally. As with NX, test the command result and handle the no-op path explicitly.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOutdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchReturn the previous value with GET
SET session:abc "new-payload" GET
Adding GET asks SET to return the old string while writing the new one. This is useful when the caller needs to log, validate, or process the replaced value without issuing a separate read. Combine it with a condition when both an atomic precondition and the previous value matter, and verify the behavior supported by your Redis server and client version.
Rank #2
Choose one conditional write pattern
| Goal | Command option | Effect |
|---|---|---|
| Always replace or create | SET key value |
Writes the value regardless of whether the key exists. |
| Create only if missing | NX |
Leaves an existing key untouched. |
| Replace only if present | XX |
Does not create a missing key. |
| Return what was replaced | GET |
Returns the prior string as part of the write. |
Do not assume that a successful network round trip means a conditional write occurred. Inspect the command response and make the application branch on success versus a failed condition.
Set and preserve expiration correctly
Expiration is attached to the key, not embedded in the string value. After the timeout elapses, Redis removes the key. This prevents stale cache entries, sessions, and temporary coordination keys from living forever.
Expiration in the SET command
SET session:abc "..." EX 1800
EX specifies a lifetime in seconds. PX specifies milliseconds when finer-grained timing is required.
Free tools Windows power users keep installed
One-click scans. No signup required.
SET short-lived "value" PX 1500
Absolute expiration can be supplied with EXAT (an absolute Unix time in seconds) or PXAT (an absolute Unix time in milliseconds). These options are useful when several processes must agree on one deadline rather than each calculating a separate relative duration.
Expiration options can be combined with NX or XX, so a cache can be created only when absent while receiving a five-minute lifetime:
SET cache:homepage "<html>..." EX 300 NX
Keep an existing TTL during replacement
A normal replacement can change the key’s expiration behavior. Add KEEPTTL when updating the value must not remove the existing time-to-live:
SET cache:homepage "new-html" KEEPTTL
Use this deliberately. A refresh that should extend freshness needs a new EX or PX value; KEEPTTL instead keeps the original deadline.
Rank #3
Apply expiration after writing
SET session:abc "..."
EXPIRE session:abc 1800
EXPIRE applies a timeout in seconds to an existing key. This two-command form is useful when the lifetime is decided separately, but it creates a window between the write and the expiration command. For cache or session writes where that window matters, prefer a single SET with EX, PX, EXAT, or PXAT.
Inspect remaining lifetime
TTL session:abc
TTL reports the remaining lifetime in seconds. Use it while diagnosing unexpectedly persistent or prematurely disappearing keys. A key with no expiration has a different result from a key that is about to expire, and a missing key has its own result; client libraries commonly expose these as integer status values. Treat them according to your library’s documented conventions rather than converting every negative value into an ordinary duration.
Expiration checklist
- Attach a TTL when writing temporary or cache data.
- Use relative
EX/PXfor a duration and absoluteEXAT/PXATfor a shared deadline. - Use
KEEPTTLonly when a replacement should retain the old deadline. - Remember that replacing a value without an expiration option can change its expiration state; verify the behavior your server version implements.
- Check the TTL on the actual key when debugging, not on a related key with a similar name.
Read and write many strings efficiently
When a request needs several independent string keys, issuing one network command per key adds round trips. MGET and MSET batch those operations. Redis documents both as O(N), where N is the number of keys or key-value pairs processed.
Batch reads with MGET
MGET profile:42:name profile:42:role
The response contains one position for each requested key, preserving request order. A missing key appears as a null entry in that position, so do not shift results by filtering out missing values.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Repair Windows errors before they cause bigger problems3Scan for outdated or missing drivers - takes under a minuteBatch writes with MSET
MSET profile:42:name "Ada" profile:42:role "Engineer"
MSET writes multiple string pairs in one command. It is useful for a group of independent scalar fields, but it does not attach per-key expiration in the same command. If each value needs a TTL, use individual SET commands with expiration options or another design that applies expiration explicitly.
When batching helps
- Use
MGETwhen a page or API response needs several cache fragments. - Use
MSETwhen several scalar values can be written together without per-key conditions. - Keep key order explicit and map each returned position back to its requested key.
- Do not use batching as a substitute for a transaction when later decisions depend on an intermediate result.
Increment counters atomically
Redis provides server-side counter primitives so an increment does not require a client to perform GET, arithmetic, and SET as separate steps. This avoids lost updates when multiple writers increment the same key.
Increment by one
INCR page:views
INCR increases an integer value by one. If the key is missing, Redis uses zero as the initial value and returns the incremented result. The existing value must be a valid integer string; a non-numeric value produces an error rather than being silently converted.
Rank #4
Increment by a whole number
INCRBY page:views 10
INCRBY adds the supplied integer amount. It is appropriate for batches of events, inventory adjustments represented as integers, or any metric whose unit is a whole number.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Increment by a decimal amount
INCRBYFLOAT account:balance 0.25
INCRBYFLOAT handles decimal increments represented as floating-point strings. Decide whether floating-point representation is acceptable for the domain; financial systems often require an integer minor-unit representation or a different precision strategy. Whatever representation you choose, keep it consistent for every writer of the key.
Why a client-side counter is unsafe
This pattern is vulnerable to races:
GET page:views
# add one in application code
SET page:views new-value
Two clients can read the same old value and then overwrite each other’s result. Replace the sequence with INCR, INCRBY, or INCRBYFLOAT so Redis performs the arithmetic as one server-side operation.
Collect and reset a value with GETSET
GETSET returns the old string while replacing it atomically:
GETSET hourly:visits 0
This is useful for a periodic collector that needs to take the current count and reset the key for the next interval. The returned value is the total accumulated before the reset. Coordinate the reset with the counter’s data type and writer behavior; a process that expects an integer should not share the key with code that stores arbitrary text.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Updating without overwriting another writer
Choose the protection level that matches the race you need to prevent.
Protect creation
Use SET key value NX when the first writer should win. This is appropriate for one-time cache fill or an ownership marker. A later writer must handle the failed condition instead of assuming its value was stored.
Best Value
Protect against accidental creation
Use SET key value XX when only an existing record may be refreshed. This catches missing initialization and avoids silently creating a key with incomplete data.
Keep the old value available
Use SET key value GET when the replacement itself is unconditional but the caller needs the prior value. This avoids a separate read that could observe a different version.
Update a counter
Use the INCR family rather than reading and writing the number in application code. Counter updates are then serialized by Redis without lost increments.
Preserve a cache deadline
Use KEEPTTL when a writer must replace content while retaining the current expiration. If freshness should restart, supply a new expiration instead. Never claim that a key has a TTL merely because it is a cache key: a TTL exists only when an expiration option or an expiration command was applied.
Strings versus hashes and Redis JSON
The correct type depends on how the application accesses the data.
| Requirement | String | Hash | Redis JSON |
|---|---|---|---|
| Single scalar or opaque payload | Best fit; read and replace with GET/SET. |
More structure than needed. | More structure than needed. |
| Serialized object stored and retrieved as a whole | Works when the application owns serialization and deserialization. | Possible only after flattening fields. | Natural representation for JSON documents. |
| Update individual fields | Requires read, modify, and rewrite of the whole value. | Designed for field-level values. | Designed for paths within JSON documents. |
| Cache an HTML fragment or page | Direct and efficient for the complete fragment. | Usually unnecessary. | Usually unnecessary. |
| Very large structured value with random field access | Can make random-access string operations costly; consider another type. | Useful for flat records. | Useful for nested JSON data. |
| Atomic numeric counter | Use INCR family on an integer or float string. |
Can hold a field counter, but the field-oriented command set differs. | Use only when document semantics justify it. |
JSON text inside a string is an application convention, not the same as using Redis JSON. If callers need field-level reads or updates, storing the entire document as one string forces them to transfer and rewrite the whole payload. Redis documentation warns that random-access operations on very large string values can create performance issues and points toward hashes or Redis JSON for structured data.
Practical recipes
Cache a rendered page for five minutes
- Build the page or fragment in the application.
- Write it with
SET cache:homepage "<html>..." EX 300. - On a later request, call
GET cache:homepage. - If the result is missing, regenerate it and write it again with the same expiration policy.
Add NX when only the first concurrent generator should populate the key. If every generator may refresh the value, omit NX and make sure stale content cannot outlive the intended five-minute lifetime.
Create a session with a thirty-minute lifetime
- Generate the session payload and a unique key such as
session:abc. - Store it with
SET session:abc "..." EX 1800. - Read it with
GET session:abc. - Treat a missing result as an expired or invalid session and require reauthentication according to the application policy.
Maintain page views
- Call
INCR page:viewsfor each event orINCRBY page:views 10for a batch. - Read the returned value if the response needs the new total.
- If the metric is windowed, apply an expiration separately or include it when the key is first created; do not assume increments create a TTL automatically.
Refresh a value without extending its deadline
- Check that the key already exists if absence is an error.
- Write the replacement with
SET key new-value XX KEEPTTL. - Handle a failed
XXcondition and inspectTTL keywhen diagnosing a missing or unexpectedly persistent entry.
Common failure modes and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| The old cache value disappears unexpectedly. | An unconditional SET ran after another writer. |
Use NX, XX, or a server-side counter operation according to the desired rule. |
| A cache entry never expires. | No expiration option or EXPIRE command was applied, or a replacement changed the expiration state. |
Set the TTL in the write and verify it with TTL; use KEEPTTL only when retaining an existing deadline is intentional. |
| A refreshed entry expires too soon. | The writer preserved an old TTL with KEEPTTL. |
Supply a new EX or PX value when refresh should start a new lifetime. |
| Counts are lower than expected. | Clients used a GET-modify-SET sequence and overwrote each other’s increments. |
Use INCR, INCRBY, or INCRBYFLOAT. |
| A conditional write appears to do nothing. | NX found an existing key or XX found no key. |
Inspect the command response and choose the branch for a failed condition. |
| A string command returns a wrong-type error. | The key is storing a list, set, hash, or another non-string type. | Correct the key naming or migrate the value deliberately; do not delete a shared key blindly. |
| Batch results are mapped to the wrong fields. | The application discarded null entries or ignored the order returned by MGET. |
Keep the requested key order and map each response position explicitly. |
| A large document update is slow or expensive. | The application rewrites an entire string to change one field. | Use a hash or Redis JSON when field-level access is required. |
Command reference
| Command | Purpose | Important behavior |
|---|---|---|
SET key value |
Create or replace a string. | Can include NX, XX, GET, EX, PX, EXAT, PXAT, and KEEPTTL. |
GET key |
Read one string. | Returns a null response for a missing key. |
MSET key value ... |
Write several strings. | O(N); does not provide per-key TTL options. |
MGET key ... |
Read several strings. | O(N); response positions match request order. |
INCR key |
Add one to an integer string. | Missing keys start at zero; operation is performed by Redis. |
INCRBY key amount |
Add an integer amount. | Use for whole-number adjustments. |
INCRBYFLOAT key amount |
Add a decimal amount. | Use a consistent numeric representation. |
GETSET key value |
Return old value and replace it. | Useful for collecting and resetting a counter. |
EXPIRE key seconds |
Apply a relative timeout. | Expiration is key-level and removes the key after the timeout. |
TTL key |
Inspect remaining lifetime. | Interpret missing-key and no-expiration status values through your client library. |
Check your Redis version and client behavior
Redis command options evolve, and client libraries do not always expose every server option with identical method signatures. Check the Redis server version before relying on newer SET options or command combinations, then consult the version-matched command documentation and your client’s return-value conventions.
Test the exact responses for a successful write, a failed NX/XX condition, a missing GET, an expired key, and a wrong-type key. These small checks catch integration mistakes such as treating a null response as an empty string or interpreting a TTL status as an ordinary duration.
Quick Recap
A reliable decision process
- Classify the value: scalar, opaque payload, serialized document, cache fragment, token, or counter.
- For a scalar or opaque payload, start with
SETandGET. - Add
NXorXXwhen creation or replacement must be conditional. - Add
EX,PX,EXAT, orPXATwhenever the value must expire. - Use
KEEPTTLonly if replacement must retain the current deadline. - Use
MGETorMSETwhen independent keys can be transferred in a batch. - Use the
INCRfamily for counters instead of client-side arithmetic. - Use
GETSETfor an atomic read-and-reset operation. - Move to a hash or Redis JSON when field-level access or updates are more important than whole-value simplicity.
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




