0
# Server Administration
1
2
Server management commands for Redis administration including configuration management, monitoring, persistence control, replication setup, cluster operations, and performance optimization. These commands enable comprehensive Redis server management and maintenance.
3
4
## Capabilities
5
6
### Server Information and Statistics
7
8
Commands for retrieving server information, statistics, and operational metrics.
9
10
```python { .api }
11
async def info(section: Optional[str] = None) -> Dict[str, Any]:
12
"""
13
Get Redis server information and statistics.
14
15
Args:
16
section: Specific info section ('server', 'memory', 'persistence', etc.)
17
18
Returns:
19
Dictionary of server information
20
"""
21
22
async def dbsize(self) -> int:
23
"""
24
Get current database size (number of keys).
25
26
Returns:
27
Number of keys in current database
28
"""
29
30
async def lastsave(self) -> int:
31
"""
32
Get Unix timestamp of last successful save.
33
34
Returns:
35
Unix timestamp of last BGSAVE
36
"""
37
38
async def time(self) -> Tuple[int, int]:
39
"""
40
Get Redis server time.
41
42
Returns:
43
Tuple of (timestamp_seconds, microseconds)
44
"""
45
46
async def memory_stats(self) -> Dict[str, Any]:
47
"""
48
Get detailed memory usage statistics.
49
50
Returns:
51
Dictionary of memory statistics
52
"""
53
54
async def memory_usage(key: str, samples: Optional[int] = None) -> Optional[int]:
55
"""
56
Get memory usage of specific key.
57
58
Args:
59
key: Key name to analyze
60
samples: Number of samples for estimation
61
62
Returns:
63
Memory usage in bytes
64
"""
65
66
async def memory_purge(self) -> bool:
67
"""
68
Attempt to purge dirty pages for better memory reporting.
69
70
Returns:
71
True if successful
72
"""
73
```
74
75
### Configuration Management
76
77
Server configuration retrieval and modification for runtime parameter tuning.
78
79
```python { .api }
80
async def config_get(pattern: str = "*") -> Dict[str, str]:
81
"""
82
Get Redis server configuration parameters.
83
84
Args:
85
pattern: Pattern to match configuration keys (* wildcards)
86
87
Returns:
88
Dictionary of configuration parameter name-value pairs
89
"""
90
91
async def config_set(name: str, value: str) -> bool:
92
"""
93
Set Redis server configuration parameter.
94
95
Args:
96
name: Configuration parameter name
97
value: New parameter value
98
99
Returns:
100
True if parameter was set successfully
101
"""
102
103
async def config_resetstat(self) -> bool:
104
"""
105
Reset Redis runtime statistics counters.
106
107
Returns:
108
True if statistics were reset
109
"""
110
111
async def config_rewrite(self) -> bool:
112
"""
113
Rewrite Redis configuration file with current settings.
114
115
Returns:
116
True if configuration file was rewritten
117
"""
118
```
119
120
### Persistence Operations
121
122
Commands for managing Redis data persistence and backup operations.
123
124
```python { .api }
125
async def save(self) -> bool:
126
"""
127
Synchronously save dataset to disk (blocks server).
128
129
Returns:
130
True if save completed successfully
131
"""
132
133
async def bgsave(self) -> bool:
134
"""
135
Asynchronously save dataset to disk in background.
136
137
Returns:
138
True if background save started
139
"""
140
141
async def bgrewriteaof(self) -> bool:
142
"""
143
Asynchronously rewrite append-only file in background.
144
145
Returns:
146
True if AOF rewrite started
147
"""
148
```
149
150
### Database Management
151
152
Commands for managing Redis databases, including flushing and database switching.
153
154
```python { .api }
155
async def flushdb(asynchronous: bool = False) -> bool:
156
"""
157
Remove all keys from current database.
158
159
Args:
160
asynchronous: Perform flush asynchronously
161
162
Returns:
163
True if database was flushed
164
"""
165
166
async def flushall(asynchronous: bool = False) -> bool:
167
"""
168
Remove all keys from all databases.
169
170
Args:
171
asynchronous: Perform flush asynchronously
172
173
Returns:
174
True if all databases were flushed
175
"""
176
177
async def swapdb(first: int, second: int) -> bool:
178
"""
179
Swap two Redis databases.
180
181
Args:
182
first: First database number
183
second: Second database number
184
185
Returns:
186
True if databases were swapped
187
"""
188
189
async def select(db: int) -> bool:
190
"""
191
Select Redis database by number.
192
193
Args:
194
db: Database number (0-15 typically)
195
196
Returns:
197
True if database was selected
198
"""
199
```
200
201
### Client Management
202
203
Commands for managing and monitoring Redis client connections.
204
205
```python { .api }
206
async def client_list(_type: Optional[str] = None) -> List[Dict[str, Any]]:
207
"""
208
Get list of connected clients and their information.
209
210
Args:
211
_type: Filter by client type ('normal', 'master', 'replica', 'pubsub')
212
213
Returns:
214
List of client information dictionaries
215
"""
216
217
async def client_id(self) -> int:
218
"""
219
Get current connection ID.
220
221
Returns:
222
Unique client connection ID
223
"""
224
225
async def client_getname(self) -> Optional[str]:
226
"""
227
Get current connection name.
228
229
Returns:
230
Client name or None if not set
231
"""
232
233
async def client_setname(name: str) -> bool:
234
"""
235
Set current connection name.
236
237
Args:
238
name: Name to assign to connection
239
240
Returns:
241
True if name was set
242
"""
243
244
async def client_kill(address: str) -> bool:
245
"""
246
Kill client connection by address.
247
248
Args:
249
address: Client address (ip:port format)
250
251
Returns:
252
True if client was killed
253
"""
254
255
async def client_kill_filter(**kwargs) -> int:
256
"""
257
Kill clients matching filter criteria.
258
259
Args:
260
kwargs: Filter criteria (type, addr, skipme, id, etc.)
261
262
Returns:
263
Number of clients killed
264
"""
265
266
async def client_unblock(client_id: int, error: bool = False) -> bool:
267
"""
268
Unblock client blocked on blocking operation.
269
270
Args:
271
client_id: Client ID to unblock
272
error: Whether to unblock with error
273
274
Returns:
275
True if client was unblocked
276
"""
277
278
async def client_pause(timeout: int) -> bool:
279
"""
280
Pause all clients for specified time.
281
282
Args:
283
timeout: Pause duration in milliseconds
284
285
Returns:
286
True if clients were paused
287
"""
288
```
289
290
### Slowlog Management
291
292
Commands for monitoring and managing the Redis slowlog for performance analysis.
293
294
```python { .api }
295
async def slowlog_get(num: Optional[int] = None) -> List[Dict[str, Any]]:
296
"""
297
Get slowlog entries for performance analysis.
298
299
Args:
300
num: Maximum number of entries to return
301
302
Returns:
303
List of slowlog entry dictionaries
304
"""
305
306
async def slowlog_len(self) -> int:
307
"""
308
Get current slowlog length.
309
310
Returns:
311
Number of entries in slowlog
312
"""
313
314
async def slowlog_reset(self) -> bool:
315
"""
316
Clear all slowlog entries.
317
318
Returns:
319
True if slowlog was cleared
320
"""
321
```
322
323
### Replication Management
324
325
Commands for managing Redis master-slave replication relationships.
326
327
```python { .api }
328
async def slaveof(host: Optional[str] = None, port: Optional[int] = None) -> bool:
329
"""
330
Make server a slave of another Redis server.
331
332
Args:
333
host: Master server hostname (None to stop replication)
334
port: Master server port
335
336
Returns:
337
True if replication was configured
338
"""
339
340
async def wait(num_replicas: int, timeout: int) -> int:
341
"""
342
Wait for specified number of replicas to acknowledge writes.
343
344
Args:
345
num_replicas: Minimum number of replicas to wait for
346
timeout: Timeout in milliseconds
347
348
Returns:
349
Number of replicas that acknowledged
350
"""
351
```
352
353
### Server Control
354
355
Commands for server lifecycle management and emergency operations.
356
357
```python { .api }
358
async def shutdown(save: bool = False, nosave: bool = False) -> None:
359
"""
360
Shutdown Redis server.
361
362
Args:
363
save: Save dataset before shutdown
364
nosave: Don't save dataset before shutdown
365
366
Note:
367
This command doesn't return as server shuts down
368
"""
369
370
async def debug_object(key: str) -> Dict[str, Any]:
371
"""
372
Get debugging information about key.
373
374
Args:
375
key: Key to debug
376
377
Returns:
378
Debug information dictionary
379
"""
380
```
381
382
### ACL (Access Control List) Management
383
384
Commands for managing Redis 6+ access control and user authentication.
385
386
```python { .api }
387
async def acl_list(self) -> List[str]:
388
"""
389
Get list of ACL rules.
390
391
Returns:
392
List of ACL rule strings
393
"""
394
395
async def acl_users(self) -> List[str]:
396
"""
397
Get list of ACL usernames.
398
399
Returns:
400
List of username strings
401
"""
402
403
async def acl_whoami(self) -> str:
404
"""
405
Get current ACL username.
406
407
Returns:
408
Current username
409
"""
410
411
async def acl_getuser(username: str) -> Dict[str, Any]:
412
"""
413
Get ACL information for specific user.
414
415
Args:
416
username: Username to query
417
418
Returns:
419
Dictionary of user ACL information
420
"""
421
422
async def acl_setuser(username: str, **kwargs) -> bool:
423
"""
424
Create or modify ACL user.
425
426
Args:
427
username: Username to modify
428
kwargs: ACL parameters (enabled, passwords, commands, etc.)
429
430
Returns:
431
True if user was modified
432
"""
433
434
async def acl_deluser(username: str) -> int:
435
"""
436
Delete ACL user.
437
438
Args:
439
username: Username to delete
440
441
Returns:
442
Number of users deleted
443
"""
444
445
async def acl_cat(category: Optional[str] = None) -> List[str]:
446
"""
447
List ACL command categories.
448
449
Args:
450
category: Specific category to list commands for
451
452
Returns:
453
List of categories or commands in category
454
"""
455
456
async def acl_genpass(self) -> str:
457
"""
458
Generate secure password for ACL user.
459
460
Returns:
461
Generated password string
462
"""
463
464
async def acl_log(count: Optional[int] = None) -> List[Dict[str, Any]]:
465
"""
466
Get ACL log entries.
467
468
Args:
469
count: Maximum number of entries to return
470
471
Returns:
472
List of ACL log entry dictionaries
473
"""
474
475
async def acl_log_reset(self) -> bool:
476
"""
477
Clear ACL log.
478
479
Returns:
480
True if log was cleared
481
"""
482
483
async def acl_load(self) -> bool:
484
"""
485
Reload ACL from configuration file.
486
487
Returns:
488
True if ACL was reloaded
489
"""
490
491
async def acl_save(self) -> bool:
492
"""
493
Save current ACL to configuration file.
494
495
Returns:
496
True if ACL was saved
497
"""
498
```
499
500
### Module Management
501
502
Commands for managing Redis modules (Redis 4+ feature).
503
504
```python { .api }
505
async def module_list(self) -> List[Dict[str, Any]]:
506
"""
507
Get list of loaded Redis modules.
508
509
Returns:
510
List of module information dictionaries
511
"""
512
513
async def module_load(path: str) -> bool:
514
"""
515
Load Redis module from file.
516
517
Args:
518
path: Path to module file
519
520
Returns:
521
True if module was loaded
522
"""
523
524
async def module_unload(name: str) -> bool:
525
"""
526
Unload Redis module.
527
528
Args:
529
name: Module name to unload
530
531
Returns:
532
True if module was unloaded
533
"""
534
```
535
536
### Cluster Management
537
538
Commands for Redis Cluster operations and management.
539
540
```python { .api }
541
async def cluster(cluster_arg: str, *args: Any) -> Any:
542
"""
543
Execute Redis Cluster command.
544
545
Args:
546
cluster_arg: Cluster subcommand ('nodes', 'info', 'slots', etc.)
547
args: Additional command arguments
548
549
Returns:
550
Cluster command result
551
"""
552
```
553
554
## Usage Examples
555
556
### Server Monitoring and Information
557
558
```python
559
async def server_monitoring_examples():
560
redis = aioredis.Redis(decode_responses=True)
561
562
# Get comprehensive server info
563
info = await redis.info()
564
print(f"Redis version: {info['redis_version']}")
565
print(f"Used memory: {info['used_memory_human']}")
566
print(f"Connected clients: {info['connected_clients']}")
567
print(f"Uptime: {info['uptime_in_seconds']} seconds")
568
569
# Get specific info sections
570
memory_info = await redis.info('memory')
571
stats_info = await redis.info('stats')
572
replication_info = await redis.info('replication')
573
574
# Database size and timing
575
db_size = await redis.dbsize()
576
print(f"Keys in current database: {db_size}")
577
578
server_time = await redis.time()
579
print(f"Server time: {server_time[0]}.{server_time[1]}")
580
581
# Memory analysis
582
memory_stats = await redis.memory_stats()
583
print(f"Peak memory: {memory_stats.get('peak.allocated', 'N/A')}")
584
585
# Analyze specific key memory usage
586
await redis.set('large_key', 'x' * 10000)
587
key_memory = await redis.memory_usage('large_key')
588
print(f"Memory used by large_key: {key_memory} bytes")
589
590
await redis.aclose()
591
```
592
593
### Configuration Management
594
595
```python
596
async def config_management_examples():
597
redis = aioredis.Redis(decode_responses=True)
598
599
# Get all configuration
600
all_config = await redis.config_get('*')
601
print(f"Total config parameters: {len(all_config)}")
602
603
# Get specific configuration patterns
604
memory_config = await redis.config_get('*memory*')
605
timeout_config = await redis.config_get('*timeout*')
606
607
print("Memory-related settings:")
608
for key, value in memory_config.items():
609
print(f" {key}: {value}")
610
611
# Modify configuration (be careful in production!)
612
original_timeout = await redis.config_get('timeout')
613
614
# Set new timeout (example - adjust as needed)
615
await redis.config_set('timeout', '300')
616
617
# Verify change
618
new_timeout = await redis.config_get('timeout')
619
print(f"Timeout changed from {original_timeout} to {new_timeout}")
620
621
# Reset statistics
622
await redis.config_resetstat()
623
print("Runtime statistics reset")
624
625
# Rewrite config file (if permissions allow)
626
try:
627
await redis.config_rewrite()
628
print("Configuration file updated")
629
except Exception as e:
630
print(f"Could not rewrite config: {e}")
631
632
await redis.aclose()
633
```
634
635
### Client Connection Management
636
637
```python
638
async def client_management_examples():
639
redis = aioredis.Redis(decode_responses=True)
640
641
# Set client name for identification
642
await redis.client_setname('monitoring_client')
643
644
# Get current client info
645
client_id = await redis.client_id()
646
client_name = await redis.client_getname()
647
print(f"Client ID: {client_id}, Name: {client_name}")
648
649
# List all connected clients
650
clients = await redis.client_list()
651
print(f"Total connected clients: {len(clients)}")
652
653
for client in clients[:5]: # Show first 5 clients
654
print(f"Client {client.get('id')}: {client.get('addr')} "
655
f"({client.get('cmd', 'idle')})")
656
657
# Filter clients by type
658
normal_clients = await redis.client_list(_type='normal')
659
print(f"Normal clients: {len(normal_clients)}")
660
661
# Create another connection to demonstrate killing
662
redis2 = aioredis.Redis(decode_responses=True)
663
await redis2.client_setname('test_client')
664
665
# Find and kill the test client
666
clients = await redis.client_list()
667
for client in clients:
668
if client.get('name') == 'test_client':
669
killed = await redis.client_kill(client['addr'])
670
print(f"Killed test client: {killed}")
671
break
672
673
# Pause all clients briefly (careful in production!)
674
await redis.client_pause(100) # 100ms pause
675
print("All clients paused briefly")
676
677
await redis.aclose()
678
try:
679
await redis2.aclose()
680
except:
681
pass # Already killed
682
```
683
684
### Performance Monitoring
685
686
```python
687
async def performance_monitoring_examples():
688
redis = aioredis.Redis(decode_responses=True)
689
690
# Generate some slow operations for demo
691
import time
692
693
# Set a large value to potentially trigger slowlog
694
large_value = 'x' * 1000000 # 1MB string
695
await redis.set('large_key', large_value)
696
697
# Check slowlog
698
slowlog_entries = await redis.slowlog_get(10)
699
print(f"Slowlog entries: {len(slowlog_entries)}")
700
701
for entry in slowlog_entries:
702
timestamp = entry[1]
703
duration_microseconds = entry[2]
704
command = ' '.join(str(arg) for arg in entry[3][:3]) # First 3 args
705
print(f"Slow command: {command} - {duration_microseconds}μs at {timestamp}")
706
707
# Get slowlog length
708
slowlog_len = await redis.slowlog_len()
709
print(f"Total slowlog entries: {slowlog_len}")
710
711
# Performance analysis with info
712
info = await redis.info('stats')
713
print(f"Total commands processed: {info.get('total_commands_processed')}")
714
print(f"Instantaneous ops/sec: {info.get('instantaneous_ops_per_sec')}")
715
print(f"Keyspace hits: {info.get('keyspace_hits')}")
716
print(f"Keyspace misses: {info.get('keyspace_misses')}")
717
718
hit_rate = info.get('keyspace_hits', 0) / max(
719
info.get('keyspace_hits', 0) + info.get('keyspace_misses', 0), 1
720
)
721
print(f"Cache hit rate: {hit_rate:.2%}")
722
723
# Memory efficiency
724
memory_info = await redis.info('memory')
725
used_memory = memory_info.get('used_memory', 0)
726
used_memory_peak = memory_info.get('used_memory_peak', 0)
727
print(f"Memory usage: {used_memory_peak - used_memory} bytes below peak")
728
729
await redis.aclose()
730
```
731
732
### Backup and Persistence
733
734
```python
735
async def backup_persistence_examples():
736
redis = aioredis.Redis(decode_responses=True)
737
738
# Add some test data
739
await redis.mset({
740
'backup_test:1': 'value1',
741
'backup_test:2': 'value2',
742
'backup_test:3': 'value3'
743
})
744
745
# Check last save time
746
last_save = await redis.lastsave()
747
print(f"Last save timestamp: {last_save}")
748
749
# Trigger background save
750
bgsave_started = await redis.bgsave()
751
if bgsave_started:
752
print("Background save started")
753
754
# Monitor save progress
755
while True:
756
info = await redis.info('persistence')
757
if info.get('rdb_bgsave_in_progress') == '0':
758
print("Background save completed")
759
break
760
await asyncio.sleep(0.1)
761
762
# Trigger AOF rewrite if AOF is enabled
763
try:
764
aof_rewrite_started = await redis.bgrewriteaof()
765
if aof_rewrite_started:
766
print("AOF rewrite started")
767
except Exception as e:
768
print(f"AOF rewrite not available: {e}")
769
770
# Get persistence info
771
persistence_info = await redis.info('persistence')
772
print("Persistence configuration:")
773
for key, value in persistence_info.items():
774
if 'rdb' in key or 'aof' in key:
775
print(f" {key}: {value}")
776
777
# Synchronous save (blocks server - use carefully!)
778
# await redis.save() # Uncomment only if safe to block
779
780
await redis.aclose()
781
```
782
783
### ACL and Security Management
784
785
```python
786
async def acl_security_examples():
787
redis = aioredis.Redis(decode_responses=True)
788
789
# Check if ACL is supported (Redis 6+)
790
try:
791
current_user = await redis.acl_whoami()
792
print(f"Current user: {current_user}")
793
794
# List all users
795
users = await redis.acl_users()
796
print(f"ACL users: {users}")
797
798
# Get user details
799
for user in users[:3]: # First 3 users
800
user_info = await redis.acl_getuser(user)
801
print(f"User {user}:")
802
print(f" Enabled: {user_info.get('flags', [])}")
803
print(f" Commands: {user_info.get('commands', 'N/A')}")
804
805
# List ACL categories
806
categories = await redis.acl_cat()
807
print(f"ACL categories: {categories}")
808
809
# Generate secure password
810
secure_password = await redis.acl_genpass()
811
print(f"Generated secure password: {secure_password[:8]}...")
812
813
# Create test user (be very careful in production!)
814
# await redis.acl_setuser(
815
# 'testuser',
816
# enabled=True,
817
# passwords=[secure_password],
818
# commands=['+get', '+set'],
819
# keys=['test:*']
820
# )
821
# print("Test user created")
822
823
# Check ACL log
824
acl_log = await redis.acl_log(5)
825
if acl_log:
826
print(f"Recent ACL events: {len(acl_log)}")
827
for event in acl_log:
828
print(f" {event}")
829
830
except Exception as e:
831
print(f"ACL commands not supported: {e}")
832
833
await redis.aclose()
834
```
835
836
### Replication and High Availability
837
838
```python
839
async def replication_examples():
840
redis = aioredis.Redis(decode_responses=True)
841
842
# Get replication information
843
repl_info = await redis.info('replication')
844
print("Replication status:")
845
print(f" Role: {repl_info.get('role')}")
846
print(f" Connected slaves: {repl_info.get('connected_slaves', 0)}")
847
848
if repl_info.get('role') == 'master':
849
print("This is a master server")
850
851
# If there are slaves, wait for replication
852
if int(repl_info.get('connected_slaves', 0)) > 0:
853
# Write test data
854
await redis.set('replication_test', 'test_value')
855
856
# Wait for at least 1 replica to acknowledge
857
replicas_acked = await redis.wait(1, 5000) # 5 second timeout
858
print(f"Replicas that acknowledged write: {replicas_acked}")
859
860
elif repl_info.get('role') == 'slave':
861
print("This is a slave server")
862
master_host = repl_info.get('master_host')
863
master_port = repl_info.get('master_port')
864
print(f" Master: {master_host}:{master_port}")
865
print(f" Link status: {repl_info.get('master_link_status')}")
866
867
# Promote to master (dangerous operation!)
868
# await redis.slaveof() # No arguments = stop being slave
869
# print("Promoted to master")
870
871
else:
872
print("Setting up as master")
873
# This server is not part of replication
874
# To make it a slave: await redis.slaveof('master_host', 6379)
875
876
await redis.aclose()
877
```