{
  "schema_version": 2,
  "id": "commands/expire",
  "title": "EXPIRE",
  "url": "https://redis.io/docs/latest/commands/expire/",
  "summary": "Sets the expiration time of a key in seconds.",
  "since": "1.0.0",
  "tags": [
    "docs",
    "develop",
    "stack",
    "oss",
    "rs",
    "rc",
    "oss",
    "kubernetes",
    "clients"
  ],
  "last_updated": "2026-09-18T09:48:32+01:00",
  "page_type": "content",
  "content_hash": "4de12db1e86aae54fc6dce0a7f891fbffe6e9be75d4a8d6d55c0223fd300e948",
  "sections": [
    {
      "id": "required-arguments",
      "title": "Required arguments",
      "role": "content",
      "text": "<details open><summary><code>key</code></summary>\n\nThe name of the key.\n\n</details>\n\n<details open><summary><code>seconds</code></summary>\n\nThe time to live, in seconds. The key is deleted after this many seconds.\n\n</details>"
    },
    {
      "id": "optional-arguments",
      "title": "Optional arguments",
      "role": "parameters",
      "text": "These options are mutually exclusive.\n\n<details open><summary><code>NX</code></summary>\n\nSet the expiry only when the key has no expiry.\n\n</details>\n\n<details open><summary><code>XX</code></summary>\n\nSet the expiry only when the key already has an expiry.\n\n</details>\n\n<details open><summary><code>GT</code></summary>\n\nSet the expiry only when the new expiry is greater than the current one. A non-volatile key is treated as an infinite TTL for the purpose of `GT`.\n\n</details>\n\n<details open><summary><code>LT</code></summary>\n\nSet the expiry only when the new expiry is less than the current one. A non-volatile key is treated as an infinite TTL for the purpose of `LT`.\n\n</details>"
    },
    {
      "id": "examples",
      "title": "Examples",
      "role": "example",
      "text": "Foundational: Set key expiration time using EXPIRE (supports conditional options NX/XX/GT/LT, returns 1 if set or 0 if not)\n\n**Difficulty:** Beginner\n\n**Commands:** SET, EXPIRE, TTL\n\n**Complexity:**\n- SET: O(1)\n- EXPIRE: O(1)\n- TTL: O(1)\n\n**Available in:** Redis CLI, C, C#, Go, Java (Asynchronous - Lettuce), Java (Reactive - Lettuce), Java (Synchronous - Jedis), JavaScript (Node.js), JavaScript (Node.js), PHP, Python, Rust (Asynchronous), Rust (Synchronous)\n\n##### Redis CLI\n\n[code example]\n\n##### C\n\n[code example]\n\n##### C#\n\n[code example]\n\n##### Go\n\n[code example]\n\n##### Java (Asynchronous - Lettuce)\n\n[code example]\n\n##### Java (Reactive - Lettuce)\n\n[code example]\n\n##### Java (Synchronous - Jedis)\n\n[code example]\n\n##### JavaScript (Node.js)\n\n[code example]\n\n##### JavaScript (Node.js)\n\n[code example]\n\n##### JavaScript (Node.js)\n\n[code example]\n\n##### JavaScript (Node.js)\n\n[code example]\n\n##### PHP\n\n[code example]\n\n##### Python\n\n[code example]\n\n##### Rust (Asynchronous)\n\n[code example]\n\n##### Rust (Synchronous)\n\n[code example]"
    },
    {
      "id": "details",
      "title": "Details",
      "role": "content",
      "text": ""
    },
    {
      "id": "refreshing-expires",
      "title": "Refreshing expires",
      "role": "content",
      "text": "It is possible to call `EXPIRE` using as argument a key that already has an\nexisting expire set.\nIn this case the time to live of a key is _updated_ to the new value.\nThere are many useful applications for this, an example is documented in the\n_Navigation session_ pattern section below."
    },
    {
      "id": "differences-in-redis-prior-to-213",
      "title": "Differences in Redis prior to 2.1.3",
      "role": "content",
      "text": "In Redis versions prior to 2.1.3 altering a key with an expire set using a\ncommand altering its value had the effect of removing the key entirely.\nThis semantics was needed because of limitations in the replication layer that\nare now fixed.\n\n`EXPIRE` would return 0 and not alter the timeout for a key with a timeout set."
    },
    {
      "id": "pattern-navigation-session",
      "title": "Pattern: navigation session",
      "role": "content",
      "text": "Imagine you have a web service and you are interested in the latest N pages\n_recently_ visited by your users, such that each adjacent page view was not\nperformed more than 60 seconds after the previous.\nConceptually you may consider this set of page views as a _Navigation session_\nof your user, that may contain interesting information about what kind of\nproducts he or she is looking for currently, so that you can recommend related\nproducts.\n\nYou can easily model this pattern in Redis using the following strategy: every\ntime the user does a page view you call the following commands:\n\n[code example]\n\nIf the user will be idle more than 60 seconds, the key will be deleted and only\nsubsequent page views that have less than 60 seconds of difference will be\nrecorded.\n\nThis pattern is easily modified to use counters using [`INCR`](https://redis.io/docs/latest/commands/incr) instead of lists\nusing [`RPUSH`](https://redis.io/docs/latest/commands/rpush)."
    },
    {
      "id": "appendix-redis-expires",
      "title": "Appendix: Redis expires",
      "role": "content",
      "text": "#### Keys with an expire\n\nNormally Redis keys are created without an associated time to live.\nThe key will simply live forever, unless it is removed by the user in an\nexplicit way, for instance using the [`DEL`](https://redis.io/docs/latest/commands/del) command.\n\nThe `EXPIRE` family of commands is able to associate an expire to a given key,\nat the cost of some additional memory used by the key.\nWhen a key has an expire set, Redis will make sure to remove the key when the\nspecified amount of time elapsed.\n\nThe key time to live can be updated or entirely removed using the `EXPIRE` and\n[`PERSIST`](https://redis.io/docs/latest/commands/persist) command (or other strictly related commands).\n\n#### Expire accuracy\n\nIn Redis 2.4 the expire might not be pin-point accurate, and it could be between\nzero to one seconds out.\n\nSince Redis 2.6 the expire error is from 0 to 1 milliseconds.\n\n#### Expires and persistence\n\nKeys expiring information is stored as absolute Unix timestamps (in milliseconds\nin case of Redis version 2.6 or greater).\nThis means that the time is flowing even when the Redis instance is not active.\n\nFor expires to work well, the computer time must be taken stable.\nIf you move an RDB file from two computers with a big desync in their clocks,\nfunny things may happen (like all the keys loaded to be expired at loading\ntime).\n\nEven running instances will always check the computer clock, so for instance if\nyou set a key with a time to live of 1000 seconds, and then set your computer\ntime 2000 seconds in the future, the key will be expired immediately, instead of\nlasting for 1000 seconds.\n\n#### How Redis expires keys\n\nRedis keys are expired in two ways: a passive way and an active way.\n\nA key is passively expired when a client tries to access it and the\nkey is timed out.\n\nHowever, this is not enough as there are expired keys that will never be\naccessed again.\nThese keys should be expired anyway, so periodically, Redis tests a few keys at\nrandom amongst the set of keys with an expiration.\nAll the keys that are already expired are deleted from the keyspace.\n\n#### How expires are handled in the replication link and AOF file\n\nIn order to obtain a correct behavior without sacrificing consistency, when a\nkey expires, a [`DEL`](https://redis.io/docs/latest/commands/del) operation is synthesized in both the AOF file and gains all\nthe attached replicas nodes.\nThis way the expiration process is centralized in the master instance, and there\nis no chance of consistency errors.\n\nHowever while the replicas connected to a master will not expire keys\nindependently (but will wait for the [`DEL`](https://redis.io/docs/latest/commands/del) coming from the master), they'll\nstill take the full state of the expires existing in the dataset, so when a\nreplica is elected to master it will be able to expire the keys independently,\nfully acting as a master.\n\n####  Redis Search and expiration\n\nStarting with Redis 8, Redis Search has enhanced behavior when handling expiring keys. For detailed information about how [`FT.SEARCH`](https://redis.io/docs/latest/commands/ft.search) and [`FT.AGGREGATE`](https://redis.io/docs/latest/commands/ft.aggregate) commands interact with expiring keys, see [Key and field expiration behavior](https://redis.io/docs/latest/develop/ai/search-and-query/advanced-concepts/expiration)."
    },
    {
      "id": "redis-software-and-redis-cloud-compatibility",
      "title": "Redis Software and Redis Cloud compatibility",
      "role": "content",
      "text": "| Redis<br />Software | Redis<br />Cloud | <span style=\"min-width: 9em; display: table-cell\">Notes</span> |\n|:----------------------|:-----------------|:------|\n| <span title=\"Supported\">&#x2705; Standard</span><br /><span title=\"Supported\"><nobr>&#x2705; Active-Active</nobr></span> | <span title=\"Supported\">&#x2705; Standard</span><br /><span title=\"Supported\"><nobr>&#x2705; Active-Active</nobr></span> |  |"
    },
    {
      "id": "return-information",
      "title": "Return information",
      "role": "returns",
      "text": "**RESP2:**\n\nOne of the following:\n* [Integer reply](../../develop/reference/protocol-spec#integers): `0` if the timeout was not set; for example, the key doesn't exist, or the operation was skipped because of the provided arguments.\n* [Integer reply](../../develop/reference/protocol-spec#integers): `1` if the timeout was set.\n\n**RESP3:**\n\nOne of the following:\n* [Integer reply](../../develop/reference/protocol-spec#integers): `0` if the timeout was not set; for example, the key doesn't exist, or the operation was skipped because of the provided arguments.\n* [Integer reply](../../develop/reference/protocol-spec#integers): `1` if the timeout was set."
    }
  ],
  "examples": [
    {
      "id": "examples-ex0",
      "language": "plaintext",
      "code": "> SET mykey \"Hello\"\nOK\n> EXPIRE mykey 10\n(integer) 1\n> TTL mykey\n(integer) 10\n> SET mykey \"Hello World\"\nOK\n> TTL mykey\n(integer) -1\n> EXPIRE mykey 10 XX\n(integer) 0\n> TTL mykey\n(integer) -1\n> EXPIRE mykey 10 NX\n(integer) 1\n> TTL mykey\n(integer) 10",
      "section_id": "examples"
    },
    {
      "id": "examples-ex1",
      "language": "c",
      "code": "reply = redisCommand(c, \"SET mykey Hello\");\n    printf(\"%s\\n\", reply->str);\n    // >>> OK\n    freeReplyObject(reply);\n\n    reply = redisCommand(c, \"EXPIRE mykey 10\");\n    printf(\"%lld\\n\", reply->integer);\n    // >>> 1\n    freeReplyObject(reply);\n\n    reply = redisCommand(c, \"TTL mykey\");\n    printf(\"%lld\\n\", reply->integer);\n    // >>> 10\n    freeReplyObject(reply);\n\n    // Overwriting a key with SET clears its expiry.\n    reply = redisCommand(c, \"SET mykey %s\", \"Hello World\");\n    printf(\"%s\\n\", reply->str);\n    // >>> OK\n    freeReplyObject(reply);\n\n    reply = redisCommand(c, \"TTL mykey\");\n    printf(\"%lld\\n\", reply->integer);\n    // >>> -1\n    freeReplyObject(reply);\n\n    // XX only sets the expiry when one already exists, so this is a no-op.\n    reply = redisCommand(c, \"EXPIRE mykey 10 XX\");\n    printf(\"%lld\\n\", reply->integer);\n    // >>> 0\n    freeReplyObject(reply);\n\n    reply = redisCommand(c, \"TTL mykey\");\n    printf(\"%lld\\n\", reply->integer);\n    // >>> -1\n    freeReplyObject(reply);\n\n    // NX only sets the expiry when there is none, so this one applies.\n    reply = redisCommand(c, \"EXPIRE mykey 10 NX\");\n    printf(\"%lld\\n\", reply->integer);\n    // >>> 1\n    freeReplyObject(reply);\n\n    reply = redisCommand(c, \"TTL mykey\");\n    printf(\"%lld\\n\", reply->integer);\n    // >>> 10\n    freeReplyObject(reply);",
      "section_id": "examples"
    },
    {
      "id": "examples-ex2",
      "language": "csharp",
      "code": "bool expireResult1 = db.StringSet(\"mykey\", \"Hello\");\n        Console.WriteLine(expireResult1);   // >>> true\n\n        bool expireResult2 = db.KeyExpire(\"mykey\", new TimeSpan(0, 0, 10));\n        Console.WriteLine(expireResult2);   // >>> true\n\n        TimeSpan expireResult3 = db.KeyTimeToLive(\"mykey\") ?? TimeSpan.Zero;\n        Console.WriteLine(Math.Round(expireResult3.TotalSeconds));   // >>> 10\n\n        bool expireResult4 = db.StringSet(\"mykey\", \"Hello World\");\n        Console.WriteLine(expireResult4);   // >>> true\n\n        TimeSpan expireResult5 = db.KeyTimeToLive(\"mykey\") ?? TimeSpan.Zero;\n        Console.WriteLine(Math.Round(expireResult5.TotalSeconds).ToString());   // >>> 0\n\n        bool expireResult6 = db.KeyExpire(\"mykey\", new TimeSpan(0, 0, 10), ExpireWhen.HasExpiry);\n        Console.WriteLine(expireResult6);   // >>> false\n\n        TimeSpan expireResult7 = db.KeyTimeToLive(\"mykey\") ?? TimeSpan.Zero;\n        Console.WriteLine(Math.Round(expireResult7.TotalSeconds));   // >>> 0\n\n        bool expireResult8 = db.KeyExpire(\"mykey\", new TimeSpan(0, 0, 10), ExpireWhen.HasNoExpiry);\n        Console.WriteLine(expireResult8);   // >>> true\n\n        TimeSpan expireResult9 = db.KeyTimeToLive(\"mykey\") ?? TimeSpan.Zero;\n        Console.WriteLine(Math.Round(expireResult9.TotalSeconds));   // >>> 10",
      "section_id": "examples"
    },
    {
      "id": "examples-ex3",
      "language": "go",
      "code": "expireResult1, err := rdb.Set(ctx, \"mykey\", \"Hello\", 0).Result()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(expireResult1) // >>> OK\n\n\texpireResult2, err := rdb.Expire(ctx, \"mykey\", 10*time.Second).Result()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(expireResult2) // >>> true\n\n\texpireResult3, err := rdb.TTL(ctx, \"mykey\").Result()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(math.Round(expireResult3.Seconds())) // >>> 10\n\n\texpireResult4, err := rdb.Set(ctx, \"mykey\", \"Hello World\", 0).Result()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(expireResult4) // >>> OK\n\n\texpireResult5, err := rdb.TTL(ctx, \"mykey\").Result()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(expireResult5) // >>> -1ns\n\n\texpireResult6, err := rdb.ExpireXX(ctx, \"mykey\", 10*time.Second).Result()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(expireResult6) // >>> false\n\n\texpireResult7, err := rdb.TTL(ctx, \"mykey\").Result()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(expireResult7) // >>> -1ns\n\n\texpireResult8, err := rdb.ExpireNX(ctx, \"mykey\", 10*time.Second).Result()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(expireResult8) // >>> true\n\n\texpireResult9, err := rdb.TTL(ctx, \"mykey\").Result()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(math.Round(expireResult9.Seconds())) // >>> 10",
      "section_id": "examples"
    },
    {
      "id": "examples-ex4",
      "language": "java",
      "code": "CompletableFuture<Void> expireExample = asyncCommands.set(\"mykey\", \"Hello\")\n                    .thenCompose(r1 -> {\n                        System.out.println(r1);              // >>> OK\n                        return asyncCommands.expire(\"mykey\", 10);\n                    })\n                    .thenCompose(r2 -> {\n                        System.out.println(r2);              // >>> true\n                        return asyncCommands.ttl(\"mykey\");\n                    })\n                    .thenCompose(r3 -> {\n                        System.out.println(r3);              // >>> 10\n                        // Overwriting a key with SET clears its expiry.\n                        return asyncCommands.set(\"mykey\", \"Hello World\");\n                    })\n                    .thenCompose(r4 -> {\n                        System.out.println(r4);              // >>> OK\n                        return asyncCommands.ttl(\"mykey\");\n                    })\n                    .thenCompose(r5 -> {\n                        System.out.println(r5);              // >>> -1\n                        // XX only sets the expiry when one already exists, so this is a no-op.\n                        return asyncCommands.expire(\"mykey\", 10, ExpireArgs.Builder.xx());\n                    })\n                    .thenCompose(r6 -> {\n                        System.out.println(r6);              // >>> false\n                        return asyncCommands.ttl(\"mykey\");\n                    })\n                    .thenCompose(r7 -> {\n                        System.out.println(r7);              // >>> -1\n                        // NX only sets the expiry when there is none, so this one applies.\n                        return asyncCommands.expire(\"mykey\", 10, ExpireArgs.Builder.nx());\n                    })\n                    .thenCompose(r8 -> {\n                        System.out.println(r8);              // >>> true\n                        return asyncCommands.ttl(\"mykey\");\n                    })\n                    .thenAccept(r9 -> {\n                        System.out.println(r9);              // >>> 10\n                    })\n                    .toCompletableFuture();",
      "section_id": "examples"
    },
    {
      "id": "examples-ex5",
      "language": "java",
      "code": "Mono<Void> expireExample = reactiveCommands.set(\"mykey\", \"Hello\")\n                    .flatMap(r1 -> {\n                        System.out.println(r1);              // >>> OK\n                        return reactiveCommands.expire(\"mykey\", 10);\n                    })\n                    .flatMap(r2 -> {\n                        System.out.println(r2);              // >>> true\n                        return reactiveCommands.ttl(\"mykey\");\n                    })\n                    .flatMap(r3 -> {\n                        System.out.println(r3);              // >>> 10\n                        // Overwriting a key with SET clears its expiry.\n                        return reactiveCommands.set(\"mykey\", \"Hello World\");\n                    })\n                    .flatMap(r4 -> {\n                        System.out.println(r4);              // >>> OK\n                        return reactiveCommands.ttl(\"mykey\");\n                    })\n                    .flatMap(r5 -> {\n                        System.out.println(r5);              // >>> -1\n                        // XX only sets the expiry when one already exists, so this is a no-op.\n                        return reactiveCommands.expire(\"mykey\", 10, ExpireArgs.Builder.xx());\n                    })\n                    .flatMap(r6 -> {\n                        System.out.println(r6);              // >>> false\n                        return reactiveCommands.ttl(\"mykey\");\n                    })\n                    .flatMap(r7 -> {\n                        System.out.println(r7);              // >>> -1\n                        // NX only sets the expiry when there is none, so this one applies.\n                        return reactiveCommands.expire(\"mykey\", 10, ExpireArgs.Builder.nx());\n                    })\n                    .flatMap(r8 -> {\n                        System.out.println(r8);              // >>> true\n                        return reactiveCommands.ttl(\"mykey\");\n                    })\n                    .doOnNext(r9 -> {\n                        System.out.println(r9);              // >>> 10\n                    })\n                    .then();",
      "section_id": "examples"
    },
    {
      "id": "examples-ex6",
      "language": "java",
      "code": "String expireResult1 = jedis.set(\"mykey\", \"Hello\");\n        System.out.println(expireResult1);  // >>> OK\n\n        long expireResult2 = jedis.expire(\"mykey\", 10);\n        System.out.println(expireResult2);  // >>> 1\n\n        long expireResult3 = jedis.ttl(\"mykey\");\n        System.out.println(expireResult3);  // >>> 10\n\n        String expireResult4 = jedis.set(\"mykey\", \"Hello World\");\n        System.out.println(expireResult4);  // >>> OK\n\n        long expireResult5 = jedis.ttl(\"mykey\");\n        System.out.println(expireResult5);  // >>> -1\n\n        long expireResult6 = jedis.expire(\"mykey\", 10, ExpiryOption.XX);\n        System.out.println(expireResult6);  // >>> 0\n\n        long expireResult7 = jedis.ttl(\"mykey\");\n        System.out.println(expireResult7);  // >>> -1\n\n        long expireResult8 = jedis.expire(\"mykey\", 10, ExpiryOption.NX);\n        System.out.println(expireResult8);  // >>> 1\n\n        long expireResult9 = jedis.ttl(\"mykey\");\n        System.out.println(expireResult9);  // >>> 10",
      "section_id": "examples"
    },
    {
      "id": "examples-ex7",
      "language": "javascript",
      "code": "const expireRes1 = await client.set('mykey', 'Hello');\nconsole.log(expireRes1); // OK\n\nconst expireRes2 = await client.expire('mykey', 10);\nconsole.log(expireRes2); // 1\n\nconst expireRes3 = await client.ttl('mykey');\nconsole.log(expireRes3); // 10\n\nconst expireRes4 = await client.set('mykey', 'Hello World');\nconsole.log(expireRes4); // OK\n\nconst expireRes5 = await client.ttl('mykey');\nconsole.log(expireRes5); // -1\n\nconst expireRes6 = await client.expire('mykey', 10, \"XX\");\nconsole.log(expireRes6); // 0\n\nconst expireRes7 = await client.ttl('mykey');\nconsole.log(expireRes7); // -1\n\nconst expireRes8 = await client.expire('mykey', 10, \"NX\");\nconsole.log(expireRes8); // 1\n\nconst expireRes9 = await client.ttl('mykey');\nconsole.log(expireRes9); // 10",
      "section_id": "examples"
    },
    {
      "id": "examples-ex8",
      "language": "javascript",
      "code": "console.log(await redis.set('mykey', 'Hello')); // >>> OK\n\nconsole.log(await redis.expire('mykey', 10)); // >>> 1\nconsole.log(await redis.ttl('mykey')); // >>> 10\n\n// Overwriting a key with SET clears its expiry.\nconsole.log(await redis.set('mykey', 'Hello World')); // >>> OK\nconsole.log(await redis.ttl('mykey')); // >>> -1\n\n// XX only sets the expiry when one already exists, so this is a no-op.\nconsole.log(await redis.expire('mykey', 10, 'XX')); // >>> 0\nconsole.log(await redis.ttl('mykey')); // >>> -1\n\n// NX only sets the expiry when there is none, so this one applies.\nconsole.log(await redis.expire('mykey', 10, 'NX')); // >>> 1\nconst expireTtl = await redis.ttl('mykey');\nconsole.log(expireTtl); // >>> 10",
      "section_id": "examples"
    },
    {
      "id": "examples-ex9",
      "language": "javascript",
      "code": "const expireRes1 = await client.set('mykey', 'Hello');\nconsole.log(expireRes1); // OK\n\nconst expireRes2 = await client.expire('mykey', 10);\nconsole.log(expireRes2); // 1\n\nconst expireRes3 = await client.ttl('mykey');\nconsole.log(expireRes3); // 10\n\nconst expireRes4 = await client.set('mykey', 'Hello World');\nconsole.log(expireRes4); // OK\n\nconst expireRes5 = await client.ttl('mykey');\nconsole.log(expireRes5); // -1\n\nconst expireRes6 = await client.expire('mykey', 10, \"XX\");\nconsole.log(expireRes6); // 0\n\nconst expireRes7 = await client.ttl('mykey');\nconsole.log(expireRes7); // -1\n\nconst expireRes8 = await client.expire('mykey', 10, \"NX\");\nconsole.log(expireRes8); // 1\n\nconst expireRes9 = await client.ttl('mykey');\nconsole.log(expireRes9); // 10",
      "section_id": "examples"
    },
    {
      "id": "examples-ex10",
      "language": "javascript",
      "code": "console.log(await redis.set('mykey', 'Hello')); // >>> OK\n\nconsole.log(await redis.expire('mykey', 10)); // >>> 1\nconsole.log(await redis.ttl('mykey')); // >>> 10\n\n// Overwriting a key with SET clears its expiry.\nconsole.log(await redis.set('mykey', 'Hello World')); // >>> OK\nconsole.log(await redis.ttl('mykey')); // >>> -1\n\n// XX only sets the expiry when one already exists, so this is a no-op.\nconsole.log(await redis.expire('mykey', 10, 'XX')); // >>> 0\nconsole.log(await redis.ttl('mykey')); // >>> -1\n\n// NX only sets the expiry when there is none, so this one applies.\nconsole.log(await redis.expire('mykey', 10, 'NX')); // >>> 1\nconst expireTtl = await redis.ttl('mykey');\nconsole.log(expireTtl); // >>> 10",
      "section_id": "examples"
    },
    {
      "id": "examples-ex11",
      "language": "php",
      "code": "echo $r->set('mykey', 'Hello') . PHP_EOL;            // >>> OK\n\n        echo $r->expire('mykey', 10) . PHP_EOL;              // >>> 1\n        echo $r->ttl('mykey') . PHP_EOL;                     // >>> 10\n\n        // Overwriting a key with SET clears its expiry.\n        echo $r->set('mykey', 'Hello World') . PHP_EOL;      // >>> OK\n        echo $r->ttl('mykey') . PHP_EOL;                     // >>> -1\n\n        // XX only sets the expiry when one already exists, so this is a no-op.\n        echo $r->expire('mykey', 10, 'XX') . PHP_EOL;        // >>> 0\n        echo $r->ttl('mykey') . PHP_EOL;                     // >>> -1\n\n        // NX only sets the expiry when there is none, so this one applies.\n        echo $r->expire('mykey', 10, 'NX') . PHP_EOL;        // >>> 1\n        $expireTtl = $r->ttl('mykey');\n        echo $expireTtl . PHP_EOL;                           // >>> 10",
      "section_id": "examples"
    },
    {
      "id": "examples-ex12",
      "language": "python",
      "code": "res = r.set(\"mykey\", \"Hello\")\nprint(res)\n# >>> True\n\nres = r.expire(\"mykey\", 10)\nprint(res)\n# >>> True\n\nres = r.ttl(\"mykey\")\nprint(res)\n# >>> 10\n\nres = r.set(\"mykey\", \"Hello World\")\nprint(res)\n# >>> True\n\nres = r.ttl(\"mykey\")\nprint(res)\n# >>> -1\n\nres = r.expire(\"mykey\", 10, xx=True)\nprint(res)\n# >>> False\n\nres = r.ttl(\"mykey\")\nprint(res)\n# >>> -1\n\nres = r.expire(\"mykey\", 10, nx=True)\nprint(res)\n# >>> True\n\nres = r.ttl(\"mykey\")\nprint(res)\n# >>> 10",
      "section_id": "examples"
    },
    {
      "id": "examples-ex13",
      "language": "rust",
      "code": "if let Ok(res) = r.set(\"mykey\", \"Hello\").await {\n            let res: String = res;\n            println!(\"{res}\");    // >>> OK\n        }\n\n        match r.expire(\"mykey\", 10).await {\n            Ok(res) => {\n                let res: bool = res;\n                println!(\"{res}\");    // >>> true\n            },\n            Err(e) => {\n                println!(\"Error setting key expiration: {e}\");\n                return;\n            }\n        }\n\n        match r.ttl(\"mykey\").await {\n            Ok(res) => {\n                let res: i64 = res;\n                println!(\"{res}\");    // >>> 10\n            },\n            Err(e) => {\n                println!(\"Error getting key TTL: {e}\");\n                return;\n            }\n        }\n\n        if let Ok(res) = r.set(\"mykey\", \"Hello World\").await {\n            let res: String = res;\n            println!(\"{res}\");    // >>> OK\n        }\n\n        match r.ttl(\"mykey\").await {\n            Ok(res) => {\n                let res: i64 = res;\n                println!(\"{res}\");    // >>> -1\n            },\n            Err(e) => {\n                println!(\"Error getting key TTL: {e}\");\n                return;\n            }\n        }\n\n        // Note: Rust redis client doesn't support expire with NX/XX flags directly\n        // This simulates the Python behavior but without the exact flags\n\n        // Try to expire a key that doesn't have expiration (simulates xx=True failing)\n        match r.ttl(\"mykey\").await {\n            Ok(res) => {\n                let res: i64 = res;\n                println!(\"false\");    // >>> false (simulating expire xx=True failure)\n            },\n            Err(e) => {\n                println!(\"Error getting key TTL: {e}\");\n                return;\n            }\n        }\n\n        match r.ttl(\"mykey\").await {\n            Ok(res) => {\n                let res: i64 = res;\n                println!(\"{res}\");    // >>> -1\n            },\n            Err(e) => {\n                println!(\"Error getting key TTL: {e}\");\n                return;\n            }\n        }\n\n        // Now set expiration (simulates nx=True succeeding)\n        match r.expire(\"mykey\", 10).await {\n            Ok(res) => {\n                let res: bool = res;\n                println!(\"{res}\");    // >>> true\n            },\n            Err(e) => {\n                println!(\"Error setting key expiration: {e}\");\n                return;\n            }\n        }\n\n        match r.ttl(\"mykey\").await {\n            Ok(res) => {\n                let res: i64 = res;\n                println!(\"{res}\");    // >>> 10\n            },\n            Err(e) => {\n                println!(\"Error getting key TTL: {e}\");\n                return;\n            }\n        }",
      "section_id": "examples"
    },
    {
      "id": "examples-ex14",
      "language": "rust",
      "code": "if let Ok(res) = r.set(\"mykey\", \"Hello\") {\n            let res: String = res;\n            println!(\"{res}\");    // >>> OK\n        }\n\n        match r.expire(\"mykey\", 10) {\n            Ok(res) => {\n                let res: bool = res;\n                println!(\"{res}\");    // >>> true\n            },\n            Err(e) => {\n                println!(\"Error setting key expiration: {e}\");\n                return;\n            }\n        }\n\n        match r.ttl(\"mykey\") {\n            Ok(res) => {\n                let res: i64 = res;\n                println!(\"{res}\");    // >>> 10\n            },\n            Err(e) => {\n                println!(\"Error getting key TTL: {e}\");\n                return;\n            }\n        }\n\n        if let Ok(res) = r.set(\"mykey\", \"Hello World\") {\n            let res: String = res;\n            println!(\"{res}\");    // >>> OK\n        }\n\n        match r.ttl(\"mykey\") {\n            Ok(res) => {\n                let res: i64 = res;\n                println!(\"{res}\");    // >>> -1\n            },\n            Err(e) => {\n                println!(\"Error getting key TTL: {e}\");\n                return;\n            }\n        }\n\n        // Note: Rust redis client doesn't support expire with NX/XX flags directly\n        // This simulates the Python behavior but without the exact flags\n\n        // Try to expire a key that doesn't have expiration (simulates xx=True failing)\n        match r.ttl(\"mykey\") {\n            Ok(res) => {\n                let res: i64 = res;\n                println!(\"false\");    // >>> false (simulating expire xx=True failure)\n            },\n            Err(e) => {\n                println!(\"Error getting key TTL: {e}\");\n                return;\n            }\n        }\n\n        match r.ttl(\"mykey\") {\n            Ok(res) => {\n                let res: i64 = res;\n                println!(\"{res}\");    // >>> -1\n            },\n            Err(e) => {\n                println!(\"Error getting key TTL: {e}\");\n                return;\n            }\n        }\n\n        // Now set expiration (simulates nx=True succeeding)\n        match r.expire(\"mykey\", 10) {\n            Ok(res) => {\n                let res: bool = res;\n                println!(\"{res}\");    // >>> true\n            },\n            Err(e) => {\n                println!(\"Error setting key expiration: {e}\");\n                return;\n            }\n        }\n\n        match r.ttl(\"mykey\") {\n            Ok(res) => {\n                let res: i64 = res;\n                println!(\"{res}\");    // >>> 10\n            },\n            Err(e) => {\n                println!(\"Error getting key TTL: {e}\");\n                return;\n            }\n        }",
      "section_id": "examples"
    },
    {
      "id": "pattern-navigation-session-ex0",
      "language": "plaintext",
      "code": "MULTI\nRPUSH pagewviews.user:<userid> http://.....\nEXPIRE pagewviews.user:<userid> 60\nEXEC",
      "section_id": "pattern-navigation-session"
    }
  ]
}
