It’s 2 AM. You’re staring at a Connection Refused error on port 6379, wondering why your SSH tunnel isn’t holding. Or maybe you just ran KEYS * on a production cluster and watched the CPU spike to 100% because you forgot that Redis is single-threaded for commands. I’ve been there. In my years managing high-throughput in-memory data stores, I’ve learned that the redis-cli tool is far more than a simple terminal shortcut. It is a surgical instrument for debugging latency, a secure bridge to remote instances, and a safety net for data exports.
Most guides treat redis-cli as a static list of syntax. This is different. This is a practical playbook. We will move beyond basic SET and GET to cover secure remote connections via SSH, non-blocking key scanning that won’t hang your server, and advanced monitoring modes that reveal what your application logs miss. By the end, you’ll have a workflow that takes you from installation to advanced diagnostics, ensuring you manipulate key-value pairs with confidence, not chaos.
Setup & Installation Across Operating Systems
The first hurdle is often trivial: getting the binary on your machine. However, the "how to use redis-cli" question usually stems from environment friction, especially when you only need the client, not the full server stack.
Quick Install: Linux, macOS, and Windows Paths
For Linux and macOS users, the path of least resistance is the system package manager. On Ubuntu or Debian, sudo apt install redis-tools will grab just the CLI without the daemon. On macOS, brew install redis does the same. These are stable, but they can lag behind the latest features in the Redis 7.x and 8.x series.
For the bleeding edge, or for minimal-footprint environments, I prefer downloading the standalone static binary. The Redis team provides an installer script that detects your architecture and drops a single, statically linked binary into /usr/local/bin. This is perfect for CI/CD pipelines where you don’t want to install a database server just to run a few diagnostics.
curl -fsSL https://packages.redis.io/redis-cli/install.sh | sh
Windows users face a slightly different reality. Native Windows support for Redis is limited, and the CLI often complains about PATH variables or missing dependencies. My recommendation here is to use WSL2 (Windows Subsystem for Linux). Installing the CLI inside the Ubuntu WSL environment bypasses 90% of the "command not found" headaches. Alternatively, if you are running Kubernetes or Docker, you likely don’t need to install anything on the host at all. You can exec into a Redis container that is already running and use the redis-cli binary included in the image. This is a common gap in documentation, but it’s the most reliable way to ensure version parity between your client and your server.
Connecting Remotely: SSH Tunnels & Authentication
Connecting to a local instance is easy. Connecting to a cloud-hosted Redis where port 6379 is firewalled off? That requires a bit more finesse. Security is non-negotiable here; you never want to expose your in-memory store to the public internet.
SSH Tunneling for Secure Remote Access
When your Redis instance is on an EC2 or Azure VM with a security group that blocks inbound traffic to port 6379, you can’t just point redis-cli at the public IP. You need to create a local port forward that tunnels through your bastion host.
Think of it like a relay race. Your local machine hands the baton to the bastion host, which then hands it to the Redis server. Here is the step-by-step setup:
-
Create the Tunnel: Open your terminal and run the SSH command below. This forwards your local port 6379 to port 6379 on the remote host, via the bastion.
ssh -i your_key.pem -L 6379:localhost:6379 user@bastion-ip -
Keep it Open: Do not close this terminal window. The tunnel is only alive while the SSH session is active.
-
Connect Locally: In a new terminal, run
redis-cli. It will now default to127.0.0.1:6379, which is secretly routed to your remote server.
For cloud providers like AWS, this method is superior to opening a security group rule because it keeps the port closed to the world. I always verify the tunnel by running redis-cli PING. If you get a PONG, you’re in. If you get Connection refused, check your SSH config and ensure the remote Redis is actually listening on 127.0.0.1 (the default). If it’s bound to 0.0.0.0 behind a load balancer, the tunnel target might need to be the internal elastic IP instead.
Authentication & SSL/TLS Configuration
Once you are connected, you’ll likely hit the NOAUTH Authentication required wall. This happens when your server has a requirepass set, but you haven’t provided it. You can pass the password directly with -a, but I strongly advise against it in scripts or shared environments, as it can end up in your shell history.
A safer approach is using the REDISCLI_AUTH environment variable:
export REDISCLI_AUTH="your_secure_password"
redis-cli -h 127.0.0.1 -p 6379
If your deployment uses ACLs (Access Control Lists), you might need to specify a user. You can do this with --user and --pass, or use the URI format which bundles it all together. The URI syntax is particularly clean for piping commands:
redis-cli -u redis://admin:secret@192.168.1.10:6379/2 GET mykey
Note the /2 at the end; that directs you to database number 2. For enterprise setups, you’ll also need to handle SSL. Redis supports TLS to encrypt traffic in transit. To connect securely, you’ll need to point the CLI to your CA certificate bundle and, if using mutual TLS, your client certificate and key.
redis-cli --tls --cacert ca.crt --cert client.crt --key client.key -h secure.redis.example.com
I’ve seen teams struggle for hours here simply because they forgot to check if the --cacert path was absolute or relative to their current working directory. It’s a small detail, but it breaks the chain of trust instantly.
Essential Commands Cheat Sheet for Key-Value Pairs
Now that you’re connected, let’s talk about the core operations. These are the commands you will use daily to manipulate key-value pairs. I’ve compiled the top ten that cover 90% of real-world scenarios, including how to handle TTLs and large payloads.
Core Operations: GET, SET, and TTL Management
The SET command is your bread and butter. But don’t just set a value; think about expiration. In most cache scenarios, data is temporary. Use the EX (seconds) or PX (milliseconds) flag to automatically remove keys when they expire. This prevents your in-memory data store from swelling up with stale entries.
redis-cli SET user:1001:session "abc123" EX 60
When you retrieve data with GET, pay attention to the return type. Redis responses are typed. You’ll see (string) for text, (integer) for numbers, and (nil) if the key doesn’t exist. If you are piping this output into another script, use the --raw flag. Without it, the CLI adds human-readable prefixes like (string), which will break your downstream JSON parsers.
For large data sets, don’t paste megabytes of text into your terminal. Use the -x flag to read the payload from stdin. This is useful for importing files directly into Redis:
redis-cli -x SET large_doc < /path/to/huge_file.txt
Advanced Scanning: Avoiding the KEYS Command Trap
Here is where I lose my temper slightly. I see junior developers run KEYS * on a production instance with 5 million keys every single week. It’s a blocking command. It iterates through the entire keyspace synchronously. On a large dataset, this will freeze your application for several seconds, causing a cascade of timeouts. I’ve watched a 500ms latency SLA breach itself just because someone wanted to count keys.
Stop using KEYS. Use SCAN instead. SCAN is non-blocking; it iterates the keyspace in small chunks, returning a cursor to resume later. In redis-cli, this is wrapped nicely with the --scan flag.
redis-cli --scan
redis-cli --scan --pattern 'user:*'
If you need to export keys to a file safely, pipe the scan output. You can even use grep to filter specific patterns without loading them into memory all at once.
redis-cli --scan --pattern 'session:*' | wc -l
This approach is safe to run against a busy server. It won’t cause the CPU spikes that KEYS does, because it respects the event loop of the Redis server.
Diagnostics & Monitoring via Special Modes
Commands are for data; modes are for insight. redis-cli includes a set of special flags that turn it into a diagnostic tool. This is where you find the answers to "why is my application slow?"
Real-Time Monitoring with MONITOR & --stat
The MONITOR command is your X-ray. It prints every command that hits the server in real-time. It’s noisy, but it’s incredibly useful for spotting unexpected writes or abuse. You can pipe it to grep to filter for specific patterns, which is vital for latency optimization.
redis-cli MONITOR | grep 'orders'
For a broader view, use the --stat mode. This gives you a rolling update of memory usage, client connections, and requests per second. It’s like a lightweight htop for Redis.
redis-cli --stat
If you see the clients column spiking unexpectedly while requests stays flat, you might have a connection leak in your application code. Check your connection pool settings.
Latency Analysis & Big Key Detection
Latency issues in Redis are rarely about the database itself; they’re usually about the system. Is it the network? Is it the kernel scheduler? The --latency flag measures the round-trip time of a PING command, sampling 100 times per second.
redis-cli --latency
If you want to see how latency changes over time, use --latency-history. It prints a new line every 15 seconds, showing the min/max/avg for that window. This helps you correlate latency spikes with other system events, like a garbage collection pause or a backup job.
But the most valuable diagnostic tool for performance tuning is --bigkeys. A single key that holds a list of 500,000 items will block the server when you try to fetch it, because Redis is single-threaded. --bigkeys scans your dataset and tells you which keys are too complex.
redis-cli --bigkeys
The output will show you the biggest key found for each data type. If you see a String with 10MB of data, or a List with 1 million items, that’s your culprit. You need to shard that data. I always recommend keeping individual keys under 10KB if possible. For deeper memory analysis, combine this with --memkeys, which shows actual memory consumption per key type. This helps you decide if your maxmemory setting is too low for your working set.
Troubleshooting: Solving Common Connection Errors
Even with the right tools, things break. When redis-cli auth error handling becomes the focus, it’s usually a misconfiguration. Here is how I approach the three most common connection failures.
Fixing 'Connection Refused' and 'Permission Denied'
1. Connection Refused This error means the TCP handshake failed. The port is not open, or the service is down.
- Check the Service: Is
redis-serveractually running?systemctl status redisorps aux | grep redis. - Check the Host/Port: Are you pointing to
127.0.0.1when the server is on a remote host? Or vice versa? - Firewall: On Linux, check
ufw statusoriptables. On the cloud, check the Security Groups. Port 6379 must be open to your source IP.
2. Authentication Error
If you get (error) ERR AUTH <password> called twice or just NOAUTH, your credentials are wrong.
- Env Var Mismatch: If you set
REDISCLI_AUTHbut also passed-a, the flag might be overriding the env var in unexpected ways. Pick one. - ACL User: If your server uses ACLs, the default user might not have permissions. Use
--userto specify the correct identity.
3. Stale Connections
Sometimes a client hangs on, keeping a connection open. If your maxclients is hit, new connections fail. You can list connected clients with:
redis-cli CLIENT LIST
Look for connections with a high idle time. If you find a zombie connection, you can kill it:
redis-cli CLIENT KILL <id>
This is a last resort, but it’s better than restarting the entire server. Always try to diagnose why the client hung before killing it. A decision tree for diagnosis would be: Can I reach the host? -> Is the port open? -> Do I have the right password? -> Am I authenticated with the right user?
FAQ
How do I connect to a remote Redis instance using redis-cli?
The safest method is to create an SSH tunnel to bypass firewall restrictions on port 6379. Run ssh -L 6379:localhost:6379 user@remote-host to forward the port locally. Then, connect using redis-cli -h 127.0.0.1 -p 6379. For cloud environments where direct access is secured, you can also connect directly using the -h and -p flags if your security groups allow it, always pairing it with -a or REDISCLI_AUTH for authentication.
What is the default port for Redis connections?
The default port is 6379. This is standard for all Redis instances. However, you should always verify this in your server's redis.conf file or by checking the port in your cloud provider’s dashboard, as administrators often change it to a non-standard port for security or load-balancing purposes.
How to list all keys in Redis without crashing the server?
Never use the KEYS * command on a large dataset; it is a blocking operation that can freeze your database. Instead, use the non-blocking SCAN command. In the CLI, this is accessed via the --scan flag. You can filter results by adding --pattern, such as redis-cli --scan --pattern 'user:*'. This iterates through the keyspace safely, allowing the server to continue serving requests.
Can I use redis-cli to export data to JSON?
Native JSON export is not a single flag in older versions, but recent builds support --json for structured output. Alternatively, you can use the --csv flag to export key-value pairs into a structured format, which can then be converted to JSON using tools like jq. For complex exports, piping the raw output of GET or HGETALL into a JSON parser is the most flexible approach.
Conclusion
Mastering redis-cli is about shifting from reactive debugging to proactive operations. The workflow is simple: Install securely, Connect via tunnels or ACLs, Query using non-blocking scans, and Monitor with latency tools.
The most critical lesson I can offer is operational safety. In a production environment, your biggest risk isn’t a syntax error; it’s a blocking command that takes down your cache. By sticking to SCAN over KEYS and using --bigkeys to identify memory hogs, you protect your latency optimization efforts. redis-cli is versatile enough to be a developer’s swiss-army knife, but only if you know which tool to pull out.
If you found this helpful, consider downloading our free printable 'Redis-CLI Command Cheat Sheet' PDF to keep on your desk. And if you’re dealing with enterprise-grade clusters, our support team can help you fine-tune your ACLs and monitoring strategies. What’s the weirdest bug you’ve found using the CLI? Share your story in the comments.






