diff --git a/.github/workflows/check-links.yml b/.github/workflows/check-links.yml deleted file mode 100644 index e79bc559..00000000 --- a/.github/workflows/check-links.yml +++ /dev/null @@ -1,19 +0,0 @@ -name: Check links - -on: - push: - pull_request: - -permissions: - contents: read - -jobs: - check-links: - runs-on: ubuntu-latest - - steps: - - name: Checkout valkey-doc - uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 # v4.1.6 - - name: Check links - run: | - ./utils/check-links.pl diff --git a/.github/workflows/check-modules-api-ref.yml b/.github/workflows/check-modules-api-ref.yml deleted file mode 100644 index 739667ad..00000000 --- a/.github/workflows/check-modules-api-ref.yml +++ /dev/null @@ -1,116 +0,0 @@ -name: Check Module API Reference - -on: - push: - paths: - - 'topics/modules-api-ref.md' - - '.github/workflows/check-modules-api-ref.yml' - pull_request: - paths: - - 'topics/modules-api-ref.md' - - '.github/workflows/check-modules-api-ref.yml' - workflow_dispatch: - -concurrency: - group: check-modules-api-ref-${{ github.head_ref || github.ref }} - cancel-in-progress: true - -permissions: - contents: read - -jobs: - verify-module-api-doc: - name: Verify Module API Reference - runs-on: ubuntu-latest - - steps: - - name: Checkout valkey-doc - uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 # v4.1.6 - with: - path: valkey-doc - - - name: Determine Valkey release version - id: version - working-directory: valkey-doc - run: | - VERSION=$(grep -E '^VERSION \?=' Makefile | awk '{print $NF}') - echo "version=${VERSION:-unstable}" >> $GITHUB_OUTPUT - - - name: Checkout valkey - uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 # v4.1.6 - with: - repository: valkey-io/valkey - path: valkey - ref: ${{ steps.version.outputs.version }} - fetch-depth: 0 - - - name: Setup Ruby - uses: ruby/setup-ruby@v1 - with: - ruby-version: '3.0' - - - name: Verify topics/modules-api-ref.md matches module.c - working-directory: valkey-doc - run: | - DOC_FILE="topics/modules-api-ref.md" - VALKEY_DIR="../valkey" - GEN_SCRIPT="utils/generate-module-api-doc.rb" - VERSION="${{ steps.version.outputs.version }}" - - if [ ! -f "$VALKEY_DIR/$GEN_SCRIPT" ]; then - echo "::error::Generator script $VALKEY_DIR/$GEN_SCRIPT not found!" - exit 1 - fi - - # Delete revoked tag 8.0.8 (mistakenly tagged on unstable and revoked in 8.0.9) - # so generate-module-api-doc.rb does not attribute APIs to 8.0.8. - git -C "$VALKEY_DIR" tag -d 8.0.8 >/dev/null 2>&1 || true - - TMP_FILE=$(mktemp) - trap 'rm -f "$TMP_FILE"' EXIT - - echo "Verifying $DOC_FILE against valkey release tag/ref $VERSION..." - ruby "$VALKEY_DIR/$GEN_SCRIPT" > "$TMP_FILE" - - if cmp -s "$DOC_FILE" "$TMP_FILE"; then - echo "✓ $DOC_FILE matches generated documentation from release $VERSION." - exit 0 - fi - - # If it doesn't match release tag, also test against unstable - if [ "$VERSION" != "unstable" ]; then - echo "$DOC_FILE did not match $VERSION. Checking against unstable branch..." - git -C "$VALKEY_DIR" checkout unstable >/dev/null 2>&1 || true - git -C "$VALKEY_DIR" tag -d 8.0.8 >/dev/null 2>&1 || true - ruby "$VALKEY_DIR/$GEN_SCRIPT" > "$TMP_FILE" - if cmp -s "$DOC_FILE" "$TMP_FILE"; then - echo "✓ $DOC_FILE matches generated documentation from unstable branch." - exit 0 - fi - fi - - echo "::error file=$DOC_FILE::$DOC_FILE does not match the generated documentation from module.c." - echo "" - echo "========================================================================" - echo "ERROR: $DOC_FILE is auto-generated from doc comments in" - echo "src/module.c in the valkey-io/valkey repository using $GEN_SCRIPT." - echo "" - echo "Direct/manual edits to $DOC_FILE are not accepted." - echo "" - echo "Note: $DOC_FILE is updated automatically during version releases" - echo "to match the release version ($VERSION). Intermediate updates from" - echo "unstable should not be committed ahead of a release." - echo "" - echo "To update the Module API documentation:" - echo " 1. Submit your doc comment updates to src/module.c in the Valkey repository:" - echo " https://github.com/valkey-io/valkey" - echo " 2. The documentation will be automatically regenerated on the next release." - echo "========================================================================" - echo "" - echo "Diff between $DOC_FILE and generated doc (from $VERSION):" - git -C "$VALKEY_DIR" checkout "$VERSION" >/dev/null 2>&1 || true - git -C "$VALKEY_DIR" tag -d 8.0.8 >/dev/null 2>&1 || true - ruby "$VALKEY_DIR/$GEN_SCRIPT" > "$TMP_FILE" - diff -u "$DOC_FILE" "$TMP_FILE" || true - - exit 1 diff --git a/.github/workflows/man-page-build-install.yml b/.github/workflows/man-page-build-install.yml index 8a584eeb..33d30222 100644 --- a/.github/workflows/man-page-build-install.yml +++ b/.github/workflows/man-page-build-install.yml @@ -22,6 +22,7 @@ jobs: with: repository: valkey-io/valkey path: valkey + fetch-depth: 0 - name: Set up Python uses: actions/setup-python@7f4fc3e22c37d6ff65e88745f38bd3157c663f7c # v4.9.1 @@ -31,7 +32,7 @@ jobs: - name: Install dependencies run: | sudo apt-get update - sudo apt-get install -y make pandoc python3-pip + sudo apt-get install -y make pandoc python3-pip ruby pip3 install pyyaml - name: Build and install man pages @@ -74,6 +75,7 @@ jobs: with: repository: valkey-io/valkey path: valkey + fetch-depth: 0 - name: Checkout valkey-bloom uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 # v4.1.6 @@ -93,6 +95,12 @@ jobs: repository: valkey-io/valkey-large-object path: valkey-large-object + - name: Checkout valkey-ldap + uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 # v4.1.6 + with: + repository: valkey-io/valkey-ldap + path: valkey-ldap + - name: Checkout valkey-json uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 # v4.1.6 with: @@ -107,7 +115,7 @@ jobs: - name: Install dependencies run: | sudo apt-get update - sudo apt-get install -y make pandoc python3-pip + sudo apt-get install -y make pandoc python3-pip ruby pip3 install pyyaml - name: Build and install man pages @@ -118,6 +126,7 @@ jobs: VALKEY_JSON_ROOT=$GITHUB_WORKSPACE/valkey-json \ VALKEY_SEARCH_ROOT=$GITHUB_WORKSPACE/valkey-search \ VALKEY_LARGE_OBJECT_ROOT=$GITHUB_WORKSPACE/valkey-large-object \ + VALKEY_LDAP_ROOT=$GITHUB_WORKSPACE/valkey-ldap \ -j; - name: Verify man pages build diff --git a/.github/workflows/spellcheck.yml b/.github/workflows/spellcheck.yml deleted file mode 100644 index fd890554..00000000 --- a/.github/workflows/spellcheck.yml +++ /dev/null @@ -1,13 +0,0 @@ -on: [push, pull_request] -permissions: - contents: read -jobs: - spellcheck: - runs-on: ubuntu-latest - name: Spellcheck - steps: - - uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 # v4.1.6 - - uses: tbroadley/spellchecker-cli-action@v1 - with: - files: "commands/*.md topics/*.md !topics/modules-api-ref.md" - config: .spellcheckerrc.yml diff --git a/.spellcheckerrc.yml b/.spellcheckerrc.yml deleted file mode 100644 index f214ca90..00000000 --- a/.spellcheckerrc.yml +++ /dev/null @@ -1,11 +0,0 @@ -files: - - 'topics/*.md' - - 'commands/*.md' - - '!topics/modules-api-ref.md' -dictionaries: - - wordlist -noSuggestions: true -quiet: true -plugins: - - spell - - frontmatter diff --git a/Makefile b/Makefile index 38e9af51..6c729a2d 100644 --- a/Makefile +++ b/Makefile @@ -6,12 +6,13 @@ VERSION ?= 9.2.0 DATE ?= 2026-11-19 -# Path to the code repo. +# Paths to the code repos. Each one has its pages in docs/commands/ and docs/topics/. VALKEY_ROOT ?= ../valkey VALKEY_BLOOM_ROOT ?= ../valkey-bloom VALKEY_JSON_ROOT ?= ../valkey-json VALKEY_SEARCH_ROOT ?= ../valkey-search VALKEY_LARGE_OBJECT_ROOT ?= ../valkey-large-object +VALKEY_LDAP_ROOT ?= ../valkey-ldap # Where to install man pages INSTALL_MAN_DIR ?= /usr/local/share/man @@ -34,20 +35,32 @@ ifeq ("$(wildcard $(VALKEY_ROOT))","") $(error Please provide the VALKEY_ROOT variable pointing to the Valkey source code) endif +ifeq ("$(wildcard $(VALKEY_ROOT)/docs/topics)","") + $(error $(VALKEY_ROOT)/docs/topics not found: VALKEY_ROOT must be a Valkey version that has its docs in docs/) +endif + ifeq ("$(wildcard $(VALKEY_BLOOM_ROOT))","") - $(info Valkey bloom variable pointed to nothing, skipping bloom filter commands) + $(info Valkey bloom variable pointed to nothing, skipping bloom filter commands and topics) endif ifeq ("$(wildcard $(VALKEY_JSON_ROOT))","") - $(info Valkey JSON variable pointed to nothing, skipping valkey-json commands) + $(info Valkey JSON variable pointed to nothing, skipping valkey-json commands and topics) endif ifeq ("$(wildcard $(VALKEY_SEARCH_ROOT))","") - $(info Valkey Search variable pointed to nothing, skipping valkey-search commands) + $(info Valkey Search variable pointed to nothing, skipping valkey-search commands and topics) endif ifeq ("$(wildcard $(VALKEY_LARGE_OBJECT_ROOT))","") - $(info Valkey Large Object variable pointed to nothing, skipping valkey-large-object commands) + $(info Valkey Large Object variable pointed to nothing, skipping valkey-large-object commands and topics) +endif + +ifeq ("$(wildcard $(VALKEY_LDAP_ROOT))","") + $(info Valkey LDAP variable pointed to nothing, skipping valkey-ldap topics) +endif + +ifeq ("$(shell which ruby)","") + $(info Ruby not found, skipping the module API reference) endif ifeq ("$(shell which pandoc)","") @@ -72,7 +85,21 @@ endif # ---- Source files ---- -documented_commands = $(wildcard commands/*.md) +doc_roots = $(VALKEY_ROOT) $(VALKEY_BLOOM_ROOT) $(VALKEY_JSON_ROOT) $(VALKEY_SEARCH_ROOT) \ + $(VALKEY_LARGE_OBJECT_ROOT) $(VALKEY_LDAP_ROOT) + +# The files in every repo's docs/$(1)/ and in this repo's $(1)/, named $(1)/. +docs_in = $(sort $(foreach root,$(doc_roots),$(patsubst $(root)/docs/%,%,$(wildcard $(root)/docs/$(1)/*))) $(wildcard $(1)/*)) +# The file for $(1), e.g. topics/index.md: the first repo's docs/$(1), else this repo's $(1), +# else the generated $(BUILD_DIR)/$(1). +doc_path = $(firstword $(wildcard $(doc_roots:%=%/docs/$(1)) $(1)) $(BUILD_DIR)/$(1)) + +# The module API reference is generated from valkey's src/module.c. +ifneq ("$(shell which ruby)","") + generated_topics = topics/modules-api-ref.md +endif + +documented_commands = $(filter %.md,$(call docs_in,commands)) commands_json_files = $(wildcard $(VALKEY_ROOT)/src/commands/*.json) bloom_commands_json_files = $(wildcard $(VALKEY_BLOOM_ROOT)/src/commands/*.json) @@ -85,7 +112,7 @@ existing_commands = $(commands_json_files:$(VALKEY_ROOT)/src/commands/%.json=com $(valkey_search_commands_json_files:$(VALKEY_SEARCH_ROOT)/src/commands/%.json=commands/%.md) \ $(valkey_large_object_commands_json_files:$(VALKEY_LARGE_OBJECT_ROOT)/src/commands/%.json=commands/%.md) -topics = $(wildcard topics/*) +topics = $(call docs_in,topics) $(generated_topics) commands = $(filter $(existing_commands),$(documented_commands)) topics_md = $(filter %.md,$(topics)) @@ -107,6 +134,14 @@ $(BUILD_DIR)/.commands-per-group.json: $(VALKEY_ROOT)/src/commands/. utils/build $(BUILD_DIR): mkdir -p $@ +$(BUILD_DIR)/topics/modules-api-ref.md: $(VALKEY_ROOT)/src/module.c $(VALKEY_ROOT)/utils/generate-module-api-doc.rb + mkdir -p $(@D) + cd $(VALKEY_ROOT) && ruby utils/generate-module-api-doc.rb > $(abspath $@~~) + mv $@~~ $@ + +# The rules below find their sources with doc_path. +.SECONDEXPANSION: + # ---- Pre-processed markdown files (make md) ---- md_topics_dir = $(MD_DIR)/topics @@ -122,19 +157,19 @@ md_targets = $(md_topics) $(md_commands) $(md_commands_dir)/index.md $(md_topics_dir) $(md_commands_dir): mkdir -p $@ -$(md_topics_dir)/%.md: topics/%.md utils/preprocess-markdown.py | $(md_topics_dir) +$(md_topics_dir)/%.md: $$(call doc_path,topics/$$*.md) utils/preprocess-markdown.py | $(md_topics_dir) utils/preprocess-markdown.py $< > $@ -$(md_topics_dir)/%.png: topics/%.png | $(md_topics_dir) +$(md_topics_dir)/%.png: $$(call doc_path,topics/$$*.png) | $(md_topics_dir) cp $< $@ -$(md_topics_dir)/%.gif: topics/%.gif | $(md_topics_dir) +$(md_topics_dir)/%.gif: $$(call doc_path,topics/$$*.gif) | $(md_topics_dir) cp $< $@ -$(md_commands_dir)/index.md: $(BUILD_DIR)/.commands-per-group.json groups.json utils/build-command-index.py | $(md_commands_dir) +$(md_commands_dir)/index.md: $(BUILD_DIR)/.commands-per-group.json $(VALKEY_ROOT)/docs/groups.json utils/build-command-index.py | $(md_commands_dir) utils/build-command-index.py --suffix .md \ - --groups-json groups.json \ + --groups-json $(VALKEY_ROOT)/docs/groups.json \ --commands-per-group-json $(BUILD_DIR)/.commands-per-group.json > $@ -$(md_commands_dir)/%.md: commands/%.md $(VALKEY_ROOT)/src/commands/%.json $(BUILD_DIR)/.commands-per-group.json \ +$(md_commands_dir)/%.md: $$(call doc_path,commands/$$*.md) $(VALKEY_ROOT)/src/commands/%.json $(BUILD_DIR)/.commands-per-group.json \ utils/preprocess-markdown.py utils/command_syntax.py utils/preprocess-markdown.py --page-type command \ --commands-per-group-json $(BUILD_DIR)/.commands-per-group.json \ @@ -156,19 +191,19 @@ html_targets = $(html_topics) $(html_topics_pics) $(html_commands) $(html_comman $(html_topics_dir) $(html_commands_dir): mkdir -p $@ -$(html_topics_dir)/%.html: topics/%.md utils/preprocess-markdown.py | $(html_topics_dir) +$(html_topics_dir)/%.html: $$(call doc_path,topics/$$*.md) utils/preprocess-markdown.py | $(html_topics_dir) utils/preprocess-markdown.py --suffix .html $< | pandoc -s --to html -o $@ - -$(html_topics_dir)/%.png: topics/%.png | $(html_topics_dir) +$(html_topics_dir)/%.png: $$(call doc_path,topics/$$*.png) | $(html_topics_dir) cp $< $@ -$(html_topics_dir)/%.gif: topics/%.gif | $(html_topics_dir) +$(html_topics_dir)/%.gif: $$(call doc_path,topics/$$*.gif) | $(html_topics_dir) cp $< $@ -$(html_commands_dir)/index.html: $(BUILD_DIR)/.commands-per-group.json groups.json utils/build-command-index.py | $(html_commands_dir) +$(html_commands_dir)/index.html: $(BUILD_DIR)/.commands-per-group.json $(VALKEY_ROOT)/docs/groups.json utils/build-command-index.py | $(html_commands_dir) utils/build-command-index.py --suffix .html \ - --groups-json groups.json \ + --groups-json $(VALKEY_ROOT)/docs/groups.json \ --commands-per-group-json $(BUILD_DIR)/.commands-per-group.json \ | pandoc -s --to html -o $@ - -$(html_commands_dir)/%.html: commands/%.md $(VALKEY_ROOT)/src/commands/%.json $(BUILD_DIR)/.commands-per-group.json \ +$(html_commands_dir)/%.html: $$(call doc_path,commands/$$*.md) $(VALKEY_ROOT)/src/commands/%.json $(BUILD_DIR)/.commands-per-group.json \ utils/preprocess-markdown.py utils/command_syntax.py utils/preprocess-markdown.py --suffix .html --page-type command \ --commands-per-group-json $(BUILD_DIR)/.commands-per-group.json \ @@ -208,11 +243,11 @@ $(MAN_DIR)/man1 $(MAN_DIR)/man3 $(MAN_DIR)/man5 $(MAN_DIR)/man7: man_scripts = utils/preprocess-markdown.py utils/command_syntax.py utils/links-to-man.py to_man = pandoc -s --to man - | gzip - -$(MAN_DIR)/man1/valkey-%.1.gz: topics/%.md $(man_scripts) +$(MAN_DIR)/man1/valkey-%.1.gz: $$(call doc_path,topics/$$*.md) $(man_scripts) utils/preprocess-markdown.py --man --page-type program \ --version $(VERSION) --date $(DATE) \$< \ | utils/links-to-man.py - | $(to_man) > $@ -$(MAN_DIR)/man3/%.3valkey.gz: commands/%.md $(BUILD_DIR)/.commands-per-group.json $(man_scripts) +$(MAN_DIR)/man3/%.3valkey.gz: $$(call doc_path,commands/$$*.md) $(BUILD_DIR)/.commands-per-group.json $(man_scripts) $(eval VALKEY_ROOTS := $(VALKEY_ROOT) $(VALKEY_JSON_ROOT) $(VALKEY_BLOOM_ROOT) $(VALKEY_SEARCH_ROOT) $(VALKEY_LARGE_OBJECT_ROOT)) $(eval FINAL_ROOT := $(firstword $(foreach root,$(VALKEY_ROOTS),$(if $(wildcard $(root)/src/commands/$*.json),$(root))))) $(if $(FINAL_ROOT),,$(eval FINAL_ROOT := $(lastword $(VALKEY_ROOTS)))) @@ -221,22 +256,22 @@ $(MAN_DIR)/man3/%.3valkey.gz: commands/%.md $(BUILD_DIR)/.commands-per-group.jso --commands-per-group-json $(BUILD_DIR)/.commands-per-group.json \ --valkey-root $(FINAL_ROOT) $< \ | utils/links-to-man.py --is-command-page - | $(to_man) > $@ -$(MAN_DIR)/man5/%.5.gz: topics/%.md $(man_scripts) +$(MAN_DIR)/man5/%.5.gz: $$(call doc_path,topics/$$*.md) $(man_scripts) utils/preprocess-markdown.py --man --page-type config \ --version $(VERSION) --date $(DATE) $< \ | utils/links-to-man.py - | $(to_man) > $@ -$(MAN_DIR)/man7/valkey-%.7.gz: topics/%.md $(man_scripts) +$(MAN_DIR)/man7/valkey-%.7.gz: $$(call doc_path,topics/$$*.md) $(man_scripts) utils/preprocess-markdown.py --man --page-type topic \ --version $(VERSION) --date $(DATE) $< \ | utils/links-to-man.py - | $(to_man) > $@ -$(MAN_DIR)/man7/valkey.7.gz: topics/index.md $(man_scripts) +$(MAN_DIR)/man7/valkey.7.gz: $$(call doc_path,topics/index.md) $(man_scripts) utils/preprocess-markdown.py --man --page-type topic \ --version $(VERSION) --date $(DATE) $< \ | utils/links-to-man.py - | $(to_man) > $@ -$(MAN_DIR)/man7/valkey-commands.7.gz: $(BUILD_DIR)/.commands-per-group.json groups.json utils/build-command-index.py +$(MAN_DIR)/man7/valkey-commands.7.gz: $(BUILD_DIR)/.commands-per-group.json $(VALKEY_ROOT)/docs/groups.json utils/build-command-index.py utils/build-command-index.py --man \ --version $(VERSION) --date $(DATE) \ - --groups-json groups.json \ + --groups-json $(VALKEY_ROOT)/docs/groups.json \ --commands-per-group-json $(BUILD_DIR)/.commands-per-group.json \ | $(to_man) > $@ @@ -276,23 +311,3 @@ distclean: install: install-man uninstall: uninstall-man - -# ---- Modules API Reference ---- - -.PHONY: generate-modules-api-ref verify-modules-api-ref - -generate-modules-api-ref: - @git -C $(VALKEY_ROOT) tag -d 8.0.8 2>/dev/null || true - ruby $(VALKEY_ROOT)/utils/generate-module-api-doc.rb > topics/modules-api-ref.md - -verify-modules-api-ref: - @git -C $(VALKEY_ROOT) tag -d 8.0.8 2>/dev/null || true - @ruby $(VALKEY_ROOT)/utils/generate-module-api-doc.rb > topics/modules-api-ref.md.tmp - @if ! cmp -s topics/modules-api-ref.md topics/modules-api-ref.md.tmp; then \ - echo "ERROR: topics/modules-api-ref.md does not match generated output from $(VALKEY_ROOT)/src/module.c"; \ - diff -u topics/modules-api-ref.md topics/modules-api-ref.md.tmp; \ - rm -f topics/modules-api-ref.md.tmp; \ - exit 1; \ - fi - @rm -f topics/modules-api-ref.md.tmp - @echo "topics/modules-api-ref.md matches $(VALKEY_ROOT)/src/module.c" diff --git a/README.md b/README.md index 79132394..18bc8ba5 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,15 @@ # Valkey documentation -This repo contains the Valkey documentation in Markdown format, which is used -for generating content for the website and man pages. +The command pages and topics live next to the code now. +Valkey's are in [`docs/`](https://github.com/valkey-io/valkey/tree/unstable/docs) +in [valkey-io/valkey](https://github.com/valkey-io/valkey), which also explains +how to write them. +Each module's are in `docs/` in the module's repository. +The [Valkey Bundle](topics/valkey-bundle.md) page stays here, in `topics/`, +with its menu entry in `modules-nav/valkey-bundle.yml`. + +This repo builds the man pages from those repositories, and holds data for the +website: the clients, modules, libraries and tools listed below. ## Installing man pages @@ -11,13 +19,17 @@ This repo comes with a Makefile to build and install man pages. make VALKEY_ROOT=path/to/valkey VALKEY_BLOOM_ROOT=path/to/valkey-bloom \ VALKEY_JSON_ROOT=path/to/valkey-json VALKEY_SEARCH_ROOT=path/to/valkey-search \ VALKEY_LARGE_OBJECT_ROOT=path/to/valkey-large-object \ + VALKEY_LDAP_ROOT=path/to/valkey-ldap sudo make install INSTALL_MAN_DIR=/usr/local/share/man ``` Prerequisites: GNU Make, Python 3, Python 3 YAML (pyyaml), Pandoc. -Additionally, the scripts need access to the valkey code repo, -where metadata files about the commands are stored. Additionally, -access to `valkey-bloom`, `valkey-json`, `valkey-search` and `valkey-large-object` repos is optional. +The scripts need the valkey code repo, at a version that has its docs in +`docs/`, for the pages and the command metadata in `src/commands/`. +The module repos are optional; without one, its commands and topics are skipped. +The module API reference is generated from valkey's `src/module.c`, which needs +Ruby and valkey's git tags (for the "Available since" versions); without Ruby, +it's skipped. The pages are generated under `_build/man/` by default. The default install location is `/usr/local/share/man` (in the appropriate subdirectories). @@ -28,54 +40,7 @@ It's also possible to build local HTML files for local usage, using `make html`. These HTML files are generated under `_build/html/` by default. The starting point of the documentation is `topics/index.html`. -## Writing docs - -The content of this doc repo is backing the documentation on the website, man -pages and potentially other formats. Links between pages are *relative* and -point directly to the `.md` files as they are stored in this repo. Don't start -links with `/`. This makes sure the links point to existing files regardless of -where in the file system the docs are located, which makes it easier to find -broken links. In text editors and in the GitHub user inteface, it's possible to -click on the links to open the corresponding Markdown page. - -Examples: `../commands/get.md` or `replication.md`. - -A few exceptions are links to the `topics/`, `commands/`, `clients/` and -`modules/` directories, which end with a slash. These pages are generated (with -the exception of `topics/` which is in `topics/index.md`). - -Examples: `../commands/#sorted-set`, `../topics/`, `./`. - -### Topics - -The files under `topics/` are generic documentation pages. The `index.md` page is a starting point. -When adding a topic, also add it to the menu (see [Menu](#menu)). - -In the top of these files, there's a frontmatter metadata section, between two -lines of three dashes (`---`). These are YAML fields of which we use only the -`title` field (and possibly `linkTitle`). The title field is used instead of an -H1 heading in each of the pages. - -#### Module API Reference - -The Module API reference page (`topics/modules-api-ref.md`) is **auto-generated** from doc comments in `src/module.c` in the [Valkey core repository](https://github.com/valkey-io/valkey) using `utils/generate-module-api-doc.rb`. - -**Do not edit `topics/modules-api-ref.md` directly.** Any modifications to the Module API documentation must be made to the doc comments in `src/module.c` in `valkey-io/valkey`. - -**Release-only updates**: This file is updated automatically as part of the release process when a new Valkey version is published (matching `VERSION` in `Makefile`). Do not open PRs to sync `topics/modules-api-ref.md` from `unstable` ahead of a release, as intermediate `unstable` changes will cause CI verification to fail when subsequent commits land on `unstable`. - -To regenerate or verify the documentation against a local Valkey checkout: - -```bash -# Regenerate topics/modules-api-ref.md -make generate-modules-api-ref VALKEY_ROOT=path/to/valkey - -# Verify topics/modules-api-ref.md matches src/module.c -make verify-modules-api-ref VALKEY_ROOT=path/to/valkey -``` - - -### Clients, modules, libraries, tools +## Clients, modules, libraries, tools We maintain links to clients, modules, libraries and tools in various languages in JSON files stored under `clients/`, `modules/`, `libraries/` and `tools/` @@ -103,95 +68,3 @@ For example [clients/go/valkey-go.json](./clients/go/valkey-go.json): ``` Modules, libraries and tools follow a similar structure under their respective directories. - -### Commands - -The command pages under `commands/` in this repo are not complete without some -metadata from the Valkey repo, namely the JSON files in the `src/commands/` -folder. The content of these JSON files is combined with the Markdown files in -this repo when the documentation is rendered. - -See: https://github.com/valkey-io/valkey/tree/unstable/src/commands/ - -For each command there's a Markdown file with a complete, human-readable -description. -We process these files to provide a better experience. - -* Inside text, all commands should be written in all caps, in between - backticks. - For example: `INCR`. - -Each command page has a `## Reply` section. -It's placed before the `## Notes` and `## Examples` sections, or at the end of -the page if there are none. -It describes the reply in both RESP2 and RESP3. -It uses the RESP3 types, written as plain words: "array", "string", -"integer", "double", "map", "set", "verbatim string" and "null". -The [protocol specification](topics/protocol.md) explains how each type is -represented in RESP2. -A value in backticks, such as `OK`, is a simple string. -Other simple strings are written as "Simple string". -Here's an example: - -```markdown -## Reply - -One of the following: - -* String: the value of the key. -* Null: if the key does not exist. -``` - -### Menu - -The documentation menu on the website is defined in [`nav.yml`](nav.yml). -It groups the topics into sections and relates commands to the topic that -explains them. -The website uses this for the menu in the left column, for breadcrumbs, and to -list a topic's commands in the menu. - -When adding a topic, add it to a section in `nav.yml`. -When adding a command, check that a menu entry covers it. -Commands can be covered by their command group (e.g. `list`), their container -command (e.g. `ACL` for all `ACL` subcommands) or their name (e.g. `BGSAVE`). -The format is described in the comments at the top of `nav.yml`. - -Topics and commands provided by modules are listed in the module's own file in -[`modules-nav/`](modules-nav/), which the website merges into the menu. -A module file can add topics to a section in `nav.yml` or add a section of its -own. - -Pages that aren't in the menu are still published and listed in the alphabetical -index on the website's topics page and in the command reference, but they're -harder to find, so please keep the menu up to date. - -### Styling guidelines - -Please use the following formatting rules (aiming for smaller diffs that are easier to review): - -* Please avoid writing lines that are too long. - That makes the diff harder to review when only one word is changed. -* Single linebreaks are not significant in Markdown, so when editing an existing - sentence or paragraph, don't change the existing linebreaks. That just makes - reviewing harder. -* Start every sentence on a new line. - -### Checking your work - -After making changes to the documentation, you can use the [spellchecker-cli package](https://www.npmjs.com/package/spellchecker-cli) -to validate your spelling as well as some minor grammatical errors. You can install the spellchecker locally by running: - -```bash -npm install --global spellchecker-cli -``` - -You can than validate your spelling by running the following - -``` -spellchecker -``` - -Any exceptions you need for spelling can be added to the `wordlist` file. -Text within backticks is not checked, so using backticks for command names, -parameter values and similar is a good idea to avoid getting spelling errors for -things like that. diff --git a/commands/acl-cat.md b/commands/acl-cat.md deleted file mode 100644 index 8bee22c2..00000000 --- a/commands/acl-cat.md +++ /dev/null @@ -1,85 +0,0 @@ -The command shows the available ACL categories if called without arguments. -If a category name is given, the command shows all the Valkey commands in -the specified category. - -ACL categories are very useful in order to create ACL rules that include or -exclude a large set of commands at once, without specifying every single -command. For instance, the following rule will let the user `karin` perform -everything but the most dangerous operations that may affect the server -stability: - - ACL SETUSER karin on +@all -@dangerous - -We first add all the commands to the set of commands that `karin` is able -to execute, but then we remove all the dangerous commands. - -Checking for all the available categories is as simple as: - -``` -> ACL CAT - 1) "keyspace" - 2) "read" - 3) "write" - 4) "set" - 5) "sortedset" - 6) "list" - 7) "hash" - 8) "string" - 9) "bitmap" -10) "hyperloglog" -11) "geo" -12) "stream" -13) "pubsub" -14) "admin" -15) "fast" -16) "slow" -17) "blocking" -18) "dangerous" -19) "connection" -20) "transaction" -21) "scripting" -``` - -Then we may want to know what commands are part of a given category: - -``` -> ACL CAT dangerous - 1) "flushdb" - 2) "acl" - 3) "slowlog" - 4) "debug" - 5) "role" - 6) "keys" - 7) "pfselftest" - 8) "client" - 9) "bgrewriteaof" -10) "replicaof" -11) "monitor" -12) "restore-asking" -13) "latency" -14) "replconf" -15) "pfdebug" -16) "bgsave" -17) "sync" -18) "config" -19) "flushall" -20) "cluster" -21) "info" -22) "lastsave" -23) "slaveof" -24) "swapdb" -25) "module" -26) "restore" -27) "migrate" -28) "save" -29) "shutdown" -30) "psync" -31) "sort" -``` - -## Reply - -One of the following: - -* Array of strings representing ACL categories or commands in a given category. -* Error: the command returns an error if an invalid category name is given. diff --git a/commands/acl-delrole.md b/commands/acl-delrole.md deleted file mode 100644 index 2fc6f8f9..00000000 --- a/commands/acl-delrole.md +++ /dev/null @@ -1,17 +0,0 @@ -Delete all the specified ACL roles. -A role cannot be deleted while it is assigned to a user: if any of the specified roles is still held by a user, the command returns an error and no role is deleted. -Use the `resetroles` or `role=` rules of [`ACL SETUSER`](acl-setuser.md) to remove the role from its users first. -The users holding a role are listed by [`ACL GETROLE`](acl-getrole.md). - -The list of roles may include role names that do not exist, in such case no operation is performed for the non existing roles. - -## Examples - -``` -127.0.0.1:6379> ACL DELROLE reader -(error) ERR Role 'reader' is assigned to one or more users. Remove it from them first. -127.0.0.1:6379> ACL SETUSER alice resetroles -OK -127.0.0.1:6379> ACL DELROLE reader nosuchrole -(integer) 1 -``` diff --git a/commands/acl-deluser.md b/commands/acl-deluser.md deleted file mode 100644 index 7678731e..00000000 --- a/commands/acl-deluser.md +++ /dev/null @@ -1,16 +0,0 @@ -Delete all the specified ACL users and terminate all the connections that are -authenticated with such users. Note: the special `default` user cannot be -removed from the system, this is the default user that every new connection -is authenticated with. The list of users may include usernames that do not -exist, in such case no operation is performed for the non existing users. - -## Reply - -Integer: the number of users that were deleted. This number will not always match the number of arguments since certain users may not exist. - -## Examples - -``` -127.0.0.1:6379> ACL DELUSER antirez -(integer) 1 -``` diff --git a/commands/acl-digest.md b/commands/acl-digest.md deleted file mode 100644 index 3caa1b4e..00000000 --- a/commands/acl-digest.md +++ /dev/null @@ -1,52 +0,0 @@ -Return a fingerprint of the ACL rules currently in effect, as a hexadecimal string. -The digest depends only on the rules in effect and not on the order the users and roles -were created in, so two servers configured alike report the same digest. - -The digest covers everything [`ACL LIST`](acl-list.md) reports: the user names, their -flags, their password hashes, and their command, key and channel rules, and the -[roles](../topics/acl.md#roles) with their rules. -Any change to any user or role changes the digest. -Changing a role's rules with [`ACL SETROLE`](acl-setrole.md) changes it too, even though -the lines of the users that hold the role stay the same. -The reply is the same size however many users and roles are configured. - -This is meant for confirming which revision of an ACL a server is running. -A client that manages users through an ACL file can read the digest before and after an -[`ACL LOAD`](acl-load.md) to tell whether the file it wrote is the one now in effect. -Comparing the rules themselves is impractical, because the server reports them in its -own normalized form rather than the form they were written in, so a client would need its -own copy of the rule parser to compare them. - -## Reply - -String: the digest of the ACL rules currently in effect, as a hexadecimal string. - -## Examples - -``` -127.0.0.1:6379> ACL DIGEST -"19566a9119379147926cb177af97ea4c8cc6cd5ef252ae6e6a0c587ae174e731" -127.0.0.1:6379> ACL SETUSER alice on >alice ~key:* +get -OK -127.0.0.1:6379> ACL DIGEST -"b7fe19e1064127c9739f0a9cb0efaac7a2e7e7e788ef2f9ff55bf68806ebd43b" -127.0.0.1:6379> ACL DELUSER alice -(integer) 1 -127.0.0.1:6379> ACL DIGEST -"19566a9119379147926cb177af97ea4c8cc6cd5ef252ae6e6a0c587ae174e731" -``` - -Editing a role changes the digest, although the line of the user that holds it does not change: - -``` -127.0.0.1:6379> ACL SETROLE reader ~data:* +get -OK -127.0.0.1:6379> ACL SETUSER bob on >bob role=reader -OK -127.0.0.1:6379> ACL DIGEST -"fae16b1655b7c98804f3c98b6e7521bd425bc42dd7fedd8d2490d593609ece3f" -127.0.0.1:6379> ACL SETROLE reader +set -OK -127.0.0.1:6379> ACL DIGEST -"6ea056a39eb57b0bc9a85f0c640913946216f6b44563dba043ab489f81c9d47f" -``` diff --git a/commands/acl-dryrun.md b/commands/acl-dryrun.md deleted file mode 100644 index 2bc455ac..00000000 --- a/commands/acl-dryrun.md +++ /dev/null @@ -1,20 +0,0 @@ -Simulate the execution of a given command by a given user. -This command can be used to test the permissions of a given user without having to enable the user or cause the side effects of running the command. - -## Reply - -Any of the following: - -* `OK` on success. -* String: an error describing why the user can't execute the command. - -## Examples - -``` -127.0.0.1:6379> ACL SETUSER VIRGINIA +SET ~* -OK -127.0.0.1:6379> ACL DRYRUN VIRGINIA SET foo bar -OK -127.0.0.1:6379> ACL DRYRUN VIRGINIA GET foo -"User VIRGINIA has no permissions to run the 'get' command" -``` diff --git a/commands/acl-genpass.md b/commands/acl-genpass.md deleted file mode 100644 index ee18ccda..00000000 --- a/commands/acl-genpass.md +++ /dev/null @@ -1,41 +0,0 @@ -ACL users need a solid password in order to authenticate to the server without -security risks. Such password does not need to be remembered by humans, but -only by computers, so it can be very long and strong (unguessable by an -external attacker). The `ACL GENPASS` command generates a password starting -from /dev/urandom if available, otherwise (in systems without /dev/urandom) it -uses a weaker system that is likely still better than picking a weak password -by hand. - -By default (if /dev/urandom is available) the password is strong and -can be used for other uses in the context of an application, for -instance in order to create unique session identifiers or other kind of -unguessable and not colliding IDs. The password generation is also very cheap -because we don't really ask /dev/urandom for bits at every execution. At -startup Valkey creates a seed using /dev/urandom, then it will use SHA256 -in counter mode, with HMAC-SHA256(seed,counter) as primitive, in order to -create more random bytes as needed. This means that the application developer -should be feel free to abuse `ACL GENPASS` to create as many secure -pseudorandom strings as needed. - -The command output is a hexadecimal representation of a binary string. -By default it emits 256 bits (so 64 hex characters). The user can provide -an argument in form of number of bits to emit from 1 to 1024 to change -the output length. Note that the number of bits provided is always -rounded to the next multiple of 4. So for instance asking for just 1 -bit password will result in 4 bits to be emitted, in the form of a single -hex character. - -## Reply - -String: pseudorandom data. By default it contains 64 bytes, representing 256 bits of data. If `bits` was given, the output string length is the number of specified bits (rounded to the next multiple of 4) divided by 4. - -## Examples - -``` -127.0.0.1:6379> ACL GENPASS -"dd721260bfe1b3d9601e7fbab36de6d04e2e67b0ef1c53de59d45950db0dd3cc" -127.0.0.1:6379> ACL GENPASS 32 -"355ef3dd" -127.0.0.1:6379> ACL GENPASS 5 -"90" -``` diff --git a/commands/acl-getrole.md b/commands/acl-getrole.md deleted file mode 100644 index 4abc60b1..00000000 --- a/commands/acl-getrole.md +++ /dev/null @@ -1,35 +0,0 @@ -The command returns all the rules defined for an existing ACL role, and the users that hold it. -The command returns a null reply if the role does not exist. - -Specifically, it lists the role's commands, key patterns, channel patterns, databases and selectors, with rules returned in the same format as the one used in the [`ACL SETROLE`](acl-setrole.md) command, followed by the names of the users the role is assigned to. - -## Examples - -``` -127.0.0.1:6379> ACL SETROLE reader ~app:* +@read (+info) -OK -127.0.0.1:6379> ACL SETUSER alice on >alicepass role=reader -OK -127.0.0.1:6379> ACL GETROLE reader - 1) "commands" - 2) "-@all +@read" - 3) "keys" - 4) "~app:*" - 5) "channels" - 6) "" - 7) "databases" - 8) "alldbs" - 9) "selectors" -10) 1) 1) "commands" - 2) "-@all +info" - 3) "keys" - 4) "" - 5) "channels" - 6) "" - 7) "databases" - 8) "alldbs" -11) "users" -12) 1) "alice" -127.0.0.1:6379> ACL GETROLE nosuchrole -(nil) -``` diff --git a/commands/acl-getuser.md b/commands/acl-getuser.md deleted file mode 100644 index b8cc6585..00000000 --- a/commands/acl-getuser.md +++ /dev/null @@ -1,55 +0,0 @@ -The command returns all the rules defined for an existing ACL user. - -Specifically, it lists the user's ACL flags, password hashes, commands, key patterns, channel patterns (Added in version 6.2), selectors (Added in version 7.0), databases (Added in version 9.1) and roles (Added in version 9.2). -Additional information may be returned in the future if more metadata is added to the user. - -Command rules are always returned in the same format as the one used in the [`ACL SETUSER`](acl-setuser.md) command. -Before version 7.0, keys and channels were returned as an array of patterns, however in version 7.0 later they are now also returned in same format as the one used in the `ACL SETUSER` command. -Note: This description of command rules reflects the user's effective permissions, so while it may not be identical to the set of rules used to configure the user, it is still functionally identical. - -Selectors are listed in the order they were applied to the user, and include information about commands, key patterns, channel patterns, and database permissions. - -Roles are listed in the order they were assigned to the user. -The commands, keys, channels, databases and selectors fields only describe the user's own rules, not the permissions the user gets from its roles. -Use [`ACL GETROLE`](acl-getrole.md) to inspect the rules of a role, and [`ACL DRYRUN`](acl-dryrun.md) to check the effective permissions of a user. - -## Reply - -One of the following: - -* Map of ACL rule definitions for the user. -* Null: if user does not exist. - -## Examples - -Here's an example configuration for a user - -``` -127.0.0.1:6379> ACL SETUSER sample on nopass +GET allkeys &* (+SET ~key2) -OK -127.0.0.1:6379> ACL GETUSER sample -1) "flags" -2) 1) "on" - 2) "nopass" -3) "passwords" -4) (empty array) -5) "commands" -6) "-@all +get" -7) "keys" -8) "~*" -9) "channels" -10) "&*" -11) "databases" -12) "alldbs" -13) "selectors" -14) 1) 1) "commands" - 2) "-@all +set" - 3) "keys" - 4) "~key2" - 5) "channels" - 6) "" - 7) "databases" - 8) "alldbs" -15) "roles" -16) (empty array) -``` diff --git a/commands/acl-help.md b/commands/acl-help.md deleted file mode 100644 index 4f1d57c2..00000000 --- a/commands/acl-help.md +++ /dev/null @@ -1,5 +0,0 @@ -The `ACL HELP` command returns a helpful text describing the different subcommands. - -## Reply - -Array of subcommands and their descriptions. diff --git a/commands/acl-list.md b/commands/acl-list.md deleted file mode 100644 index d6dac1d7..00000000 --- a/commands/acl-list.md +++ /dev/null @@ -1,23 +0,0 @@ -The command shows the currently active ACL rules in the Valkey server. Each -line in the returned array defines a different role or user. Lines starting -with `role` describe [roles](../topics/acl.md#roles) and are listed first, -followed by the lines starting with `user`. The format is the -same used in the valkey.conf file or the external ACL file, so you can -cut and paste what is returned by the ACL LIST command directly inside a -configuration file if you wish (but make sure to check [`ACL SAVE`](acl-save.md)). -Implicit defaults may be omitted: for example, access to all databases (`alldbs`) -is not shown, while explicit `db=` and `resetdbs` rules are shown. - -## Reply - -Array of strings. - -## Examples - -``` -127.0.0.1:6379> ACL LIST -1) "role reader ~app:* resetchannels -@all +@read" -2) "user alice on #13dc8554575637802eec3c0117f41591a990e1a2d37160018c48c9125063838a resetchannels -@all role=reader" -3) "user antirez on #9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 ~objects:* &* +@all -@admin -@dangerous" -4) "user default on nopass ~* &* +@all" -``` diff --git a/commands/acl-load.md b/commands/acl-load.md deleted file mode 100644 index 81d1eea7..00000000 --- a/commands/acl-load.md +++ /dev/null @@ -1,27 +0,0 @@ -When Valkey is configured to use an ACL file (with the `aclfile` configuration -option), this command will reload the ACLs from the file, replacing all -the current ACL rules with the ones defined in the file. The command makes -sure to have an *all or nothing* behavior, that is: - -* If every line in the file is valid, all the ACLs are loaded. -* If one or more line in the file is not valid, nothing is loaded, and the old ACL rules defined in the server memory continue to be used. - -## Reply - -`OK` on success. - -The command may fail with an error for several reasons: if the file is not readable, if there is an error inside the file, and in such cases, the error will be reported to the user in the error. - -Finally, the command will fail if the server is not configured to use an external ACL file. - -## Examples - -``` -127.0.0.1:6379> ACL LOAD -OK -``` - -``` -127.0.0.1:6379> ACL LOAD -(error) ERR /tmp/foo:1: Unknown command or category name in ACL... -``` diff --git a/commands/acl-log.md b/commands/acl-log.md deleted file mode 100644 index ab3a42ab..00000000 --- a/commands/acl-log.md +++ /dev/null @@ -1,75 +0,0 @@ -The command shows a list of recent ACL security events: - -1. Failures to authenticate their connections with [`AUTH`](auth.md) or [`HELLO`](hello.md). -2. Commands denied because against the current ACL rules. -3. Commands denied because accessing keys not allowed in the current ACL rules. -4. Commands denied because accessing Pub/Sub channels not allowed in the current ACL rules. -5. Commands denied because accessing a database not allowed in the current ACL rules. -6. TLS clients failing automatic authentication via certificate field because no matching user exists. - -The optional argument specifies how many entries to show. By default -up to ten failures are returned. The special `RESET` argument clears the log. -Entries are displayed starting from the most recent. - -## Reply - -When called to show security events: - -* Array of strings representing ACL security events. - -When called with `RESET`: - -* `OK` if the security log was cleared. - -## Examples - -``` -127.0.0.1:6379> AUTH someuser wrongpassword -(error) WRONGPASS invalid username-password pair or user is disabled. -127.0.0.1:6379> ACL LOG 1 -1) 1) "count" - 2) (integer) 1 - 3) "reason" - 4) "auth" - 5) "context" - 6) "toplevel" - 7) "object" - 8) "AUTH" - 9) "username" - 10) "someuser" - 11) "age-seconds" - 12) "8.038" - 13) "client-info" - 14) "id=3 addr=127.0.0.1:57275 laddr=127.0.0.1:6379 fd=8 name= age=16 idle=0 flags=N capa= db=0 sub=0 psub=0 ssub=0 multi=-1 watch=0 qbuf=48 qbuf-free=16842 argv-mem=25 multi-mem=0 rbs=1024 rbp=0 obl=0 oll=0 omem=0 tot-mem=18737 events=r cmd=auth user=default redir=-1 resp=2 lib-name= lib-ver= tot-net-in=48 tot-net-out=0 tot-cmds=0" - 15) "entry-id" - 16) (integer) 0 - 17) "timestamp-created" - 18) (integer) 1675361492408 - 19) "timestamp-last-updated" - 20) (integer) 1675361492408 -``` - -Each log entry is composed of the following fields: - -1. `count`: The number of security events detected within a 60 second period that are represented by this entry. -2. `reason`: The reason that the security events were logged. One of the following: - * `command`: the user has no permission to run the command. - * `key`: the user has no permission to access one of the keys used by the command. - * `channel`: the user has no permission to access one of the Pub/Sub channels used by the command. - * `database`: the user has no permission to access one of the databases referenced by the command. - * `auth`: authentication failed for the connection. - * `tls-cert`: automatic authentication from a TLS certificate failed because no matching user exists. -3. `context`: The context that the security events were detected in. Either `toplevel`, `multi`, `lua`, `script`, or `module`. -4. `object`: The resource that the user had insufficient permissions to access. The value depends on `reason`: - * `command`: the command name. - * `key`: the key pattern. - * `channel`: the Pub/Sub channel. - * `database`: the database id, or the command name when the command implicitly accesses every database (such as [`FLUSHALL`](flushall.md)). - * `auth`: the literal string `AUTH`. - * `tls-cert`: the certificate that did not match any existing user. -5. `username`: The username that executed the command that caused the security events or the username that had a failed authentication attempt. -6. `age-seconds`: Age of the log entry in seconds. -7. `client-info`: Displays the client info of a client which caused one of the security events. -8. `entry-id`: The sequence number of the entry (starting at 0) since the server process started. Can also be used to check if items were “lost”, if they fell between periods. -9. `timestamp-created`: A UNIX timestamp in `milliseconds` at the time the entry was first created. -10. `timestamp-last-updated`: A UNIX timestamp in `milliseconds` at the time the entry was last updated. diff --git a/commands/acl-roles.md b/commands/acl-roles.md deleted file mode 100644 index 65c727df..00000000 --- a/commands/acl-roles.md +++ /dev/null @@ -1,10 +0,0 @@ -The command shows a list of all the names of the currently configured roles in the Valkey ACL system. - -## Examples - -``` -127.0.0.1:6379> ACL ROLES -1) "ops" -2) "reader" -3) "writer" -``` diff --git a/commands/acl-save.md b/commands/acl-save.md deleted file mode 100644 index c7a98d6e..00000000 --- a/commands/acl-save.md +++ /dev/null @@ -1,17 +0,0 @@ -When Valkey is configured to use an ACL file (with the `aclfile` configuration -option), this command will save the currently defined ACLs from the server memory to the ACL file. - -## Reply - -`OK`. - -The command may fail with an error for several reasons: if the file cannot be written or if the server is not configured to use an external ACL file. - -## Examples - -``` -127.0.0.1:6379> ACL SAVE -OK -127.0.0.1:6379> ACL SAVE -(error) ERR There was an error trying to save the ACLs. Please check the server logs for more information -``` diff --git a/commands/acl-setrole.md b/commands/acl-setrole.md deleted file mode 100644 index e553aa21..00000000 --- a/commands/acl-setrole.md +++ /dev/null @@ -1,35 +0,0 @@ -Create an ACL role with the specified rules or modify the rules of an existing role. - -A role is a named, reusable set of permissions that can be assigned to any number of users with the `role=` rule of [`ACL SETUSER`](acl-setuser.md), so a policy is written once instead of being repeated in every user. -See [roles](../topics/acl.md#roles) for more information. - -If the role does not exist, the command creates it without any privilege. -It then reads from left to right all the rules provided as successive arguments, setting the role ACL rules as specified. -If the role already exists, the provided ACL rules are applied *in addition* to the rules already set, exactly as `ACL SETUSER` does for users. -The rules are applied atomically: if any rule is invalid, the role is left unchanged. - -A role accepts the [command rules](acl-setuser.md#command-rules) of `ACL SETUSER`, as well as selectors (`()`) and `clearselectors`. -The rules that only make sense for a user are rejected with an error: `on`, `off`, `reset`, the password rules (`>`, `<`, `#`, `!`, `nopass`, `resetpass`), `role=` and `resetroles`. -Roles cannot be nested. - -Changes to a role take effect immediately for every user holding it. -If the change removes access to Pub/Sub channels, the clients of those users that are subscribed to channels they can no longer access are disconnected. - -Role names are case sensitive and may contain any printable ASCII character except for spaces, commas, quotes (`"` and `'`) and backslashes. -Roles live in a namespace of their own, so a role may have the same name as a user, a command, or a category. - -Note: a new role starts with access to all databases (`alldbs`), and to all Pub/Sub channels if `acl-pubsub-default` is set to `allchannels`, just like a new user. -Since a user's own permissions and those of its roles are combined with OR logic, such a role grants those databases and channels to its users even if the user itself is restricted with `resetdbs`, `db=` or `resetchannels`. -Use `db=` (or `resetdbs`) and `resetchannels` in the role rules to restrict the role itself. -See [database permissions](../topics/acl.md#database-permissions). - -## Examples - -``` -127.0.0.1:6379> ACL SETROLE reader ~app:* +@read -OK -127.0.0.1:6379> ACL SETROLE ops ~* +info (+config|get) -OK -127.0.0.1:6379> ACL SETROLE reader on -(error) ERR Error in ACL SETROLE modifier 'on': Syntax error -``` diff --git a/commands/acl-setuser.md b/commands/acl-setuser.md deleted file mode 100644 index c787997e..00000000 --- a/commands/acl-setuser.md +++ /dev/null @@ -1,152 +0,0 @@ -Create an ACL user with the specified rules or modify the rules of an -existing user. - -Manipulate Valkey ACL users interactively. -If the username does not exist, the command creates the username without any privilege. -It then reads from left to right all the [rules](#acl-rules) provided as successive arguments, setting the user ACL rules as specified. -If the user already exists, the provided ACL rules are simply applied -*in addition* to the rules already set. For example: - - ACL SETUSER virginia on allkeys +set - -The above command creates a user called `virginia` who is active(the _on_ rule), can access any key (_allkeys_ rule), and can call the set command (_+set_ rule). -Then, you can use another `ACL SETUSER` call to modify the user rules: - - ACL SETUSER virginia +get - -The above rule applies the new rule to the user `virginia`, so other than [`SET`](set.md), the user `virginia` can now also use the [`GET`](get.md) command. - -ACL rules can also be grouped into multiple distinct sets of rules, called _selectors_. -Selectors are added by wrapping the rules in parentheses and providing them just like any other rule. -In order to execute a command, either the root permissions (rules defined outside of parenthesis) or any of the selectors (rules defined inside parenthesis) must match the given command. -For example: - - ACL SETUSER virginia on +GET allkeys (+SET ~app1*) - -This sets a user with two sets of permissions, one defined on the user and one defined with a selector. -The root user permissions only allow executing the get command, but can be executed on any keys. -The selector then grants a secondary set of permissions: access to the [`SET`](set.md) command to be executed on any key that starts with `app1`. -Using multiple selectors allows you to grant permissions that are different depending on what keys are being accessed. - -Permissions can also be defined once in a named _role_, created with [`ACL SETROLE`](acl-setrole.md), and assigned to any number of users with the `role=` rule: - - ACL SETROLE reader ~app:* +@read - ACL SETUSER virginia on >password role=reader - -A user's own permissions are combined with those of its roles, so a user can add permissions on top of a role but cannot take away what a role grants. - -When we want to be sure to define a user from scratch, without caring if -it had previously defined rules associated, we can use the special rule -`reset` as first rule, in order to flush all the other existing rules: - - ACL SETUSER antirez reset [... other rules ...] - -After resetting a user, its ACL rules revert to the default: inactive, passwordless, can't execute any command nor access any key or channel: - -``` -127.0.0.1:6379> ACL SETUSER antirez reset -OK -127.0.0.1:6379> ACL LIST -1) "user antirez off -@all" -``` - -ACL rules are either words like "on", "off", "reset", "allkeys", or are -special rules that start with a special character, and are followed by -another string (without any space in between), like "+SET". - -The following documentation is a reference manual about the capabilities of this command, however our [ACL tutorial](../topics/acl.md) may be a more gentle introduction to how the ACL system works in general. - -## ACL rules - -Valkey ACL rules are split into two categories: rules that define command permissions or _command rules_, and rules that define the user state or _user management rules_. -This is a list of all the supported Valkey ACL rules: - -### Command rules - -* `~`: Adds the specified key pattern (glob style pattern, like in the [`KEYS`](keys.md) command), to the list of key patterns accessible by the user. This grants both read and write permissions to keys that match the pattern. You can add multiple key patterns to the same user. Example: `~objects:*` -* `%R~`: Adds the specified read key pattern. This behaves similar to the regular key pattern but only grants permission to read from keys that match the given pattern. See [key permissions](../topics/acl.md#key-permissions) for more information. -* `%W~`: Adds the specified write key pattern. This behaves similar to the regular key pattern but only grants permission to write to keys that match the given pattern. See [key permissions](../topics/acl.md#key-permissions) for more information. -* `%RW~`: Alias for `~`. -* `allkeys`: Alias for `~*`, it allows the user to access all the keys. -* `resetkeys`: Removes all the key patterns from the list of key patterns the user can access. -* `&`: Adds the specified glob style pattern to the list of Pub/Sub channel patterns accessible by the user. You can add multiple channel patterns to the same user. Example: `&chatroom:*` -* `allchannels`: Alias for `&*`, it allows the user to access all Pub/Sub channels. -* `resetchannels`: Removes all channel patterns from the list of Pub/Sub channel patterns the user can access. -* `+`: Adds the command to the list of commands the user can call. Can be used with `|` for allowing subcommands (e.g "+config|get"). -* `+@`: Adds all the commands in the specified category to the list of commands the user is able to execute. Example: `+@string` (adds all the string commands). For a list of categories, check the [`ACL CAT`](acl-cat.md) command. -* `+|first-arg`: Allows a specific first argument of an otherwise disabled command. It is only supported on commands with no sub-commands, and is not allowed as negative form like -SELECT|1, only additive starting with "+". This feature is deprecated and may be removed in the future. -* `allcommands`: Alias of `+@all`. Adds all the commands there are in the server, including *future commands* loaded via module, to be executed by this user. -* `-`: Remove the command to the list of commands the user can call. It can be used with `|` for blocking subcommands (e.g., "-config|set"). -* `-@`: Like `+@` but removes all the commands in the category instead of adding them. -* `nocommands`: Alias for `-@all`. Removes all the commands, and the user is no longer able to execute anything. -* `db=[,...]`: Sets the specified database id(s) as the databases the selector is allowed to access. - Multiple ids are separated by commas, e.g. `db=0,1,2`; at least one id is required. - Clears the `alldbs` flag and any previously configured database ids on the selector. - See [database permissions](../topics/acl.md#database-permissions) for more information. -* `alldbs`: Allows the selector to access all databases. This is the default for new selectors and is omitted from generated ACL strings. -* `resetdbs`: Removes all databases from the list of allowed databases and clears the `alldbs` flag. - -### User management rules - -* `on`: Set the user as active, it will be possible to authenticate as this user using [`AUTH`](auth.md) ` `. -* `off`: Set user as not active, it will be impossible to log as this user. Please note that if a user gets disabled (set to off) after there are connections already authenticated with such a user, the connections will continue to work as expected. To also kill the old connections you can use [`CLIENT KILL`](client-kill.md) with the user option. An alternative is to delete the user with [`ACL DELUSER`](acl-deluser.md), that will result in all the connections authenticated as the deleted user to be disconnected. -* `nopass`: The user is set as a _no password_ user. It means that it will be possible to authenticate as such user with any password. By default, the `default` special user is set as "nopass". The `nopass` rule will also reset all the configured passwords for the user. -* `>password`: Adds the specified clear text password as a hashed password in the list of the users passwords. Every user can have many active passwords, so that password rotation will be simpler. The specified password is not stored as clear text inside the server. Example: `>mypassword`. -* `#`: Adds the specified hashed password to the list of user passwords. A hashed password is hashed with SHA256 and translated into a hexadecimal string. Example: `#c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2`. -* `password` but removes the password instead of adding it. -* `!`: Like `#` but removes the password instead of adding it. -* `()`: Creates a new selector to match rules against. Selectors are evaluated after the user permissions, and are evaluated according to the order they are defined. If a command matches either the user permissions or any selector, it is allowed. See [selectors](../topics/acl.md#selectors) for more information. -* `clearselectors`: Deletes all of the selectors attached to the user. -* `role=[, ...]`: Assigns the named roles to the user, replacing any role the user already had. At least one role has to be named, and every named role must already exist (see [`ACL SETROLE`](acl-setrole.md)). The permissions of each role are combined with those of the user using OR logic, the same way selectors are. See [roles](../topics/acl.md#roles) for more information. Example: `role=reader,writer`. (Added in version 9.2) -* `resetroles`: Removes every role from the user. (Added in version 9.2) -* `reset`: Removes any capability from the user. They are set to off, without passwords, without roles, unable to execute any command, unable to access any key. - -## Reply - -`OK`. - -If the rules contain errors, the error is returned. - -## Examples - -``` -127.0.0.1:6379> ACL SETUSER alan allkeys +@string +@set -SADD >alanpassword -OK -127.0.0.1:6379> ACL SETUSER antirez heeyyyy -(error) ERR Error in ACL SETUSER modifier 'heeyyyy': Syntax error -``` - -Restrict a user to a subset of databases: - -``` -127.0.0.1:6379> ACL SETUSER alice on +@all ~* db=0,1 nopass -OK -127.0.0.1:6379> ACL LIST -1) "user alice on nopass ~* resetchannels db=0,1 +@all" -2) "user default on nopass ~* &* +@all" -``` - -A later `db=` rule replaces the previous database list: - -``` -127.0.0.1:6379> ACL SETUSER alice db=2,3 -OK -127.0.0.1:6379> ACL LIST -1) "user alice on nopass ~* resetchannels db=2,3 +@all" -2) "user default on nopass ~* &* +@all" -``` - -Different selectors can grant access on different databases: - -``` -127.0.0.1:6379> ACL SETUSER bob on nopass (db=0,1 +@write +select ~*) (db=2,3 +@read +select ~*) -OK -127.0.0.1:6379> ACL LIST -1) "user bob on nopass resetchannels -@all (~* resetchannels db=0,1 -@all +@write +select) (~* resetchannels db=2,3 -@all +@read +select)" -2) "user default on nopass ~* &* +@all" -``` - -The `ACL LIST` output shows three sets of permissions for `bob`: the root -permissions (`-@all`, with implicit `alldbs`) and two selectors, one for each -parenthesized rule set. A command is allowed when the root permissions or any selector matches it. -See [selectors](../topics/acl.md#selectors) for more information. diff --git a/commands/acl-users.md b/commands/acl-users.md deleted file mode 100644 index fbb50023..00000000 --- a/commands/acl-users.md +++ /dev/null @@ -1,16 +0,0 @@ -The command shows a list of all the usernames of the currently configured -users in the Valkey ACL system. Roles are not included, use -[`ACL ROLES`](acl-roles.md) to list them. - -## Reply - -Array of existing ACL users. - -## Examples - -``` -127.0.0.1:6379> ACL USERS -1) "anna" -2) "antirez" -3) "default" -``` diff --git a/commands/acl-whoami.md b/commands/acl-whoami.md deleted file mode 100644 index 80f93374..00000000 --- a/commands/acl-whoami.md +++ /dev/null @@ -1,14 +0,0 @@ -Return the username the current connection is authenticated with. -New connections are authenticated with the "default" user. They -can change user using [`AUTH`](auth.md). - -## Reply - -String: the username of the current connection. - -## Examples - -``` -127.0.0.1:6379> ACL WHOAMI -"default" -``` diff --git a/commands/acl.md b/commands/acl.md deleted file mode 100644 index 834eeaea..00000000 --- a/commands/acl.md +++ /dev/null @@ -1,3 +0,0 @@ -This is a container command for [Access Control List](../topics/acl.md) commands. - -To see the list of available commands you can call [`ACL HELP`](acl-help.md). diff --git a/commands/append.md b/commands/append.md deleted file mode 100644 index d9a497f7..00000000 --- a/commands/append.md +++ /dev/null @@ -1,64 +0,0 @@ -If `key` already exists and is a string, this command appends the `value` at the -end of the string. -If `key` does not exist it is created and set as an empty string, so `APPEND` -will be similar to `SET` in this special case. - -## Reply - -Integer: the length of the string after the append operation. - -## Examples - -``` -127.0.0.1:6379> EXISTS mykey -(integer) 0 -127.0.0.1:6379> APPEND mykey "Hello" -(integer) 5 -127.0.0.1:6379> APPEND mykey " World" -(integer) 11 -127.0.0.1:6379> GET mykey -"Hello World" -``` - -## Pattern: Time series - -The `APPEND` command can be used to create a very compact representation of a -list of fixed-size samples, usually referred as _time series_. -Every time a new sample arrives we can store it using the command - -``` -APPEND timeseries "fixed-size sample" -``` - -Accessing individual elements in the time series is not hard: - -* `STRLEN` can be used in order to obtain the number of samples. -* `GETRANGE` allows for random access of elements. - If our time series have associated time information we can easily implement - a binary search to get range combining `GETRANGE` with the Lua scripting - engine. -* `SETRANGE` can be used to overwrite an existing time series. - -The limitation of this pattern is that we are forced into an append-only mode -of operation, there is no way to cut the time series to a given size easily -because Valkey currently lacks a command able to trim string objects. -However the space efficiency of time series stored in this way is remarkable. - -Hint: it is possible to switch to a different key based on the current Unix -time, in this way it is possible to have just a relatively small amount of -samples per key, to avoid dealing with very big keys, and to make this pattern -more friendly to be distributed across many Valkey instances. - -An example sampling the temperature of a sensor using fixed-size strings (using -a binary format is better in real implementations). - -``` -127.0.0.1:6379> APPEND ts "0043" -(integer) 4 -127.0.0.1:6379> APPEND ts "0035" -(integer) 8 -127.0.0.1:6379> GETRANGE ts 0 3 -"0043" -127.0.0.1:6379> GETRANGE ts 4 7 -"0035" -``` diff --git a/commands/asking.md b/commands/asking.md deleted file mode 100644 index 0eeed9e1..00000000 --- a/commands/asking.md +++ /dev/null @@ -1,10 +0,0 @@ -When a cluster client receives an `-ASK` redirect, the `ASKING` command is sent to the target node followed by the command which was redirected. -This is normally done automatically by cluster clients. - -If an `-ASK` redirect is received during a transaction, only one ASKING command needs to be sent to the target node before sending the complete transaction to the target node. - -See [ASK redirection in the Valkey Cluster Specification](../topics/cluster-spec.md#ask-redirection) for details. - -## Reply - -`OK`. diff --git a/commands/auth.md b/commands/auth.md deleted file mode 100644 index f19206f0..00000000 --- a/commands/auth.md +++ /dev/null @@ -1,29 +0,0 @@ -The AUTH command authenticates the current connection using the [Valkey ACL system](../topics/acl.md). - -The standard way to `AUTH` is the two-argument form: - - AUTH - -This authenticates the current connection with one of the users -defined in the ACL list (see [`ACL SETUSER`](acl-setuser.md) and the official [ACL guide](../topics/acl.md) for more information). - -When the single argument form of the command is used, where only the password is specified, -it is assumed that the implicit username is "default". - - AUTH - -This form authenticates against the "default" user's password set with `requirepass`. - -If the password provided via AUTH matches the password in the configuration file, the server replies with the `OK` status code and starts accepting commands. -Otherwise, an error is returned and the clients needs to try a new password. - -## Security notice - -Because of the high performance nature of Valkey, it is possible to try -a lot of passwords in parallel in very short time, so make sure to generate a -strong and very long password so that this attack is infeasible. -A good way to generate strong passwords is via the [`ACL GENPASS`](acl-genpass.md) command. - -## Reply - -`OK`, or an error if the password, or username/password pair, is invalid. diff --git a/commands/bf.add.md b/commands/bf.add.md deleted file mode 100644 index 0bc629d5..00000000 --- a/commands/bf.add.md +++ /dev/null @@ -1,23 +0,0 @@ -Adds a single item to a bloom filter. If the specified bloom filter does not exist, a bloom filter is created with the provided name with default properties. - -To add multiple items to a bloom filter, you can use the [`BF.MADD`](bf.madd.md) or [`BF.INSERT`](bf.insert.md) commands. - -To create a bloom filter with non-default properties, use the [`BF.INSERT`](bf.insert.md) or [`BF.RESERVE`](bf.reserve.md) command. - -## Reply - -One of the following: - -* Integer: `1` if the item was successfully added -* Integer: `0` if the item already existed in the bloom filter - -An error will occur if input is invalid, if a non bloom filter key with the same name already exists, if the bloom filter creation / scale out exceeds limits, or if an item is being added to a full non scaling filter. - -## Examples - -``` -127.0.0.1:6379> BF.ADD key val -(integer) 1 -127.0.0.1:6379> BF.ADD key val -(integer) 0 -``` diff --git a/commands/bf.card.md b/commands/bf.card.md deleted file mode 100644 index 4b17bec8..00000000 --- a/commands/bf.card.md +++ /dev/null @@ -1,16 +0,0 @@ -Returns the cardinality of a bloom filter which is the number of items that have been successfully added to it. - -## Reply - -Integer: The number of items successfully added to the bloom filter, or 0 if the key does not exist - -## Examples - -``` -127.0.0.1:6379> BF.ADD key val -(integer) 1 -127.0.0.1:6379> BF.CARD key -(integer) 1 -127.0.0.1:6379> BF.CARD nonexistentkey -(integer) 0 -``` diff --git a/commands/bf.exists.md b/commands/bf.exists.md deleted file mode 100644 index 88c7864f..00000000 --- a/commands/bf.exists.md +++ /dev/null @@ -1,25 +0,0 @@ -Determines if an item has been added to the bloom filter previously. - -A bloom filter has two possible responses when you check if an item exists: - -* 0 - The item definitely does not exist since with bloom filters, false negatives are not possible. - -* 1 - The item exists with a given false positive (`fp`) percentage. There is an `fp` rate % chance that the item does not exist. You can create bloom filters with a more strict false positive rate as needed. - -## Reply - -One of the following: - -* Integer: `1` if the item exists in the bloom filter -* Integer: `0` if the bloom filter does not exist or the item has not been added to the bloom filter - -## Examples - -``` -127.0.0.1:6379> BF.ADD key val -(integer) 1 -127.0.0.1:6379> BF.EXISTS key val -(integer) 1 -127.0.0.1:6379> BF.EXISTS key nonexistent -(integer) 0 -``` diff --git a/commands/bf.info.md b/commands/bf.info.md deleted file mode 100644 index 7cbf1a50..00000000 --- a/commands/bf.info.md +++ /dev/null @@ -1,55 +0,0 @@ -Returns usage information and properties of a specific bloom filter. - -## Info Fields - -* CAPACITY - The number of unique items that would need to be added before a scale out occurs or (non scaling) before it rejects addition of unique items. -* SIZE - The number of bytes allocated by this bloom filter. -* FILTERS - Returns the number of sub filters contained within the bloom filter. -* ITEMS - The number of unique items that have been added to the bloom filter. -* ERROR - The false positive rate of the bloom filter. -* EXPANSION - The expansion rate of the bloom filter. Non scaling filters will have an expansion rate of nil. -* TIGHTENING - The tightening ratio of the bloom filter. -* MAXSCALEDCAPACITY - The [maximum capacity](../topics/bloomfilters.md) that a scalable bloom filter can be expand to and reach before a subsequent scale out will fail. - -For non-scaling filters, the `TIGHTENING` and `MAXSCALEDCAPACITY` fields are not applicable and will not be returned. -When no optional fields are specified, all available fields for the given filter type are returned. - -## Reply - -When no optional arguments are provided: - -* Array of information about the bloom filter. - -When an optional argument excluding ERROR is provided: - -* Integer: argument value - -When ERROR is provided as an optional argument: - -* Double: argument value - -## Examples - -``` -127.0.0.1:6379> BF.ADD key val -(integer) 1 -127.0.0.1:6379> BF.INFO key - 1) Capacity - 2) (integer) 100 - 3) Size - 4) (integer) 384 - 5) Number of filters - 6) (integer) 1 - 7) Number of items inserted - 8) (integer) 2 - 9) Error rate -10) "0.01" -11) Expansion rate -12) (integer) 2 -13) Tightening ratio -14) "0.5" -15) Max scaled capacity -16) (integer) 26214300 -127.0.0.1:6379> BF.INFO key CAPACITY -(integer) 100 -``` \ No newline at end of file diff --git a/commands/bf.insert.md b/commands/bf.insert.md deleted file mode 100644 index 939fa086..00000000 --- a/commands/bf.insert.md +++ /dev/null @@ -1,50 +0,0 @@ -If the bloom filter does not exist under the specified name, a bloom filter is created with the specified parameters. Default properties will be used if the options below are not specified. - -When the `ITEMS` option is provided, all items provided will be attempted to be added. - -## Insert Fields - -* CAPACITY *capacity* - The number of unique items that would need to be added before a scale out occurs or (non scaling) before it rejects addition of unique items. -* ERROR *fp_error* - The false positive rate of the bloom filter. -* EXPANSION *expansion* - This option will specify the bloom filter as scaling and controls the size of the sub filter that will be created upon scale out / expansion of the bloom filter. -* NOCREATE - Will not create the bloom filter and add items if the filter does not exist already. -* TIGHTENING *tightening_ratio* - The tightening ratio for the bloom filter. -* SEED *seed* - The 32 byte seed the bloom filter's hash functions will use. -* NONSCALING - This option will configure the bloom filter as non scaling; it cannot expand / scale beyond its specified capacity. -* VALIDATESCALETO *validatescaleto* - Validates if the filter can scale out and reach to this capacity based on limits and if not, return an error without creating the bloom filter. -* ITEMS *item* - One or more items to be added to the bloom filter. - -Due to the nature of `NONSCALING` and `VALIDATESCALETO` arguments, specifying `NONSCALING` and `VALIDATESCALETO` together is not allowed. - -## Reply - -Array of integers (`1` or `0`) - if filter already exists or if creation was successful. An empty array if no items are provided - -An error will occur if input is invalid, if a non bloom filter key with the same name already exists, if the bloom filter creation / scale out exceeds limits, or if an item is being added to a full non scaling filter. - -## Examples - -``` -127.0.0.1:6379> BF.INSERT key ITEMS item1 item2 -1) (integer) 1 -2) (integer) 1 -# This does not update the capacity since the filter already exists. It only adds the provided items. -127.0.0.1:6379> BF.INSERT key CAPACITY 1000 ITEMS item2 item3 -1) (integer) 0 -2) (integer) 1 -127.0.0.1:6379> BF.INSERT key_new CAPACITY 1000 -[] -``` - -``` -127.0.0.1:6379> BF.INSERT key NONSCALING VALIDATESCALETO 100 -(error) ERR cannot use NONSCALING and VALIDATESCALETO options together -127.0.0.1:6379> BF.INSERT key CAPACITY 1000 VALIDATESCALETO 999999999999999999 ITEMS item2 item3 -(error) ERR provided VALIDATESCALETO causes bloom object to exceed memory limit -127.0.0.1:6379> BF.INSERT key VALIDATESCALETO 999999999999999999 EXPANSION 1 ITEMS item2 item3 -(error) ERR provided VALIDATESCALETO causes false positive to degrade to 0 -``` -``` -127.0.0.1:6379> BF.INSERT key NOCREATE ITEMS item1 item2 -(error) ERR not found -``` \ No newline at end of file diff --git a/commands/bf.load.md b/commands/bf.load.md deleted file mode 100644 index fab45654..00000000 --- a/commands/bf.load.md +++ /dev/null @@ -1 +0,0 @@ -Restores a bloom filter from a dump of an existing bloom filter with all of its specific the properties and bit vector dump of sub filter/s. This command is only generated during AOF rewrite to restore a bloom filter in the future. diff --git a/commands/bf.madd.md b/commands/bf.madd.md deleted file mode 100644 index fd514f5d..00000000 --- a/commands/bf.madd.md +++ /dev/null @@ -1,22 +0,0 @@ -Adds one or more items to a bloom filter. If the specified bloom filter does not exist, a bloom filter is created with the provided name with default properties. - -If you want to create a bloom filter with non-default properties, use the [`BF.INSERT`](bf.insert.md) or [`BF.RESERVE`](bf.reserve.md) command. - -## Reply - -Array of integers (`1` or `0`) - -An error will occur if input is invalid, if a non bloom filter key with the same name already exists, if the bloom filter creation / scale out exceeds limits, or if an item is being added to a full non scaling filter. - -## Examples - -``` -127.0.0.1:6379> BF.MADD key item1 item2 -1) (integer) 1 -2) (integer) 1 -127.0.0.1:6379> BF.MADD key item2 item3 -1) (integer) 0 -2) (integer) 1 -127.0.0.1:6379> BF.MADD key_new item1 -1) (integer) 1 -``` diff --git a/commands/bf.mexists.md b/commands/bf.mexists.md deleted file mode 100644 index 7a11fa51..00000000 --- a/commands/bf.mexists.md +++ /dev/null @@ -1,25 +0,0 @@ -Determines if the provided item/s have been added to a bloom filter previously. - -A Bloom filter has two possible responses when you check if an item exists: - -* 0 - The item definitely does not exist since with bloom filters, false negatives are not possible. - -* 1 - The item exists with a given false positive (`fp`) percentage. There is an `fp` rate % chance that the item does not exist. You can create bloom filters with a more strict false positive rate as needed. - -## Reply - -Array of integers (`1` or `0`) - -## Examples - -``` -127.0.0.1:6379> BF.MADD key item1 item2 -1) (integer) 1 -2) (integer) 1 -127.0.0.1:6379> BF.MEXISTS key item1 item2 item3 -1) (integer) 1 -2) (integer) 1 -3) (integer) 0 -127.0.0.1:6379> BF.MEXISTS key item1 -1) (integer) 1 -``` \ No newline at end of file diff --git a/commands/bf.reserve.md b/commands/bf.reserve.md deleted file mode 100644 index 56036ac4..00000000 --- a/commands/bf.reserve.md +++ /dev/null @@ -1,33 +0,0 @@ -Creates an empty bloom filter with the specified capacity and false positive rate. By default, a scaling filter is created with the default expansion rate. - -To specify the scaling / non scaling nature of the bloom filter, use the options: `NONSCALING` or `SCALING `. It is invalid to provide both options together. - -## Reserve fields - -* error_rate - The false positive rate of the bloom filter -* capacity - The number of unique items that would need to be added before a scale out occurs or (non scaling) before it rejects addition of unique items. -* EXPANSION expansion - This option will specify the bloom filter as scaling and controls the size of the sub filter that will be created upon scale out / expansion of the bloom filter. -* NONSCALING - This option will configure the bloom filter as non scaling; it cannot expand / scale beyond its specified capacity. - -## Reply - -`OK`. - -An error will occur if input is invalid, if a key with the same name already exists, or if the bloom filter creation exceeds limits. - -## Examples - -``` -127.0.0.1:6379> BF.RESERVE key 0.01 1000 -OK -127.0.0.1:6379> BF.RESERVE key 0.1 1000000 -(error) ERR item exists -``` -``` -127.0.0.1:6379> BF.RESERVE bf_expansion 0.0001 5000 EXPANSION 3 -OK -``` -``` -127.0.0.1:6379> BF.RESERVE bf_nonscaling 0.0001 5000 NONSCALING -OK -``` diff --git a/commands/bgrewriteaof.md b/commands/bgrewriteaof.md deleted file mode 100644 index 1c305767..00000000 --- a/commands/bgrewriteaof.md +++ /dev/null @@ -1,30 +0,0 @@ -Instruct Valkey to start an [Append Only File][tpaof] rewrite process. -The rewrite will create a small optimized version of the current Append Only -File. - -[tpaof]: ../topics/persistence.md#append-only-file - -If `BGREWRITEAOF` fails, no data gets lost as the old AOF will be untouched. - -The rewrite will be only triggered by Valkey if there is not already a background -process doing persistence. - -Specifically: - -* If a Valkey child is creating a snapshot on disk, the AOF rewrite is _scheduled_ but not started until the saving child producing the RDB file terminates. In this case the `BGREWRITEAOF` will still return a positive status reply, but with an appropriate message. You can check if an AOF rewrite is scheduled looking at the [`INFO`](info.md) command. -* If an AOF rewrite is already in progress the command returns an error and no - AOF rewrite will be scheduled for a later time. -* If the AOF rewrite could start, but the attempt at starting it fails (for instance because of an error in creating the child process), an error is returned to the caller. - -The AOF rewrite is automatically triggered by Valkey, however the -`BGREWRITEAOF` command can be used to trigger a rewrite at any time. - -Please refer to the [persistence documentation][tp] for detailed information. - -[tp]: ../topics/persistence.md - -## Reply - -Simple string indicating that the rewriting started or is about to start ASAP when the call is executed with success. - -The command may reply with an error in certain cases, as documented above. diff --git a/commands/bgsave.md b/commands/bgsave.md deleted file mode 100644 index f594d122..00000000 --- a/commands/bgsave.md +++ /dev/null @@ -1,31 +0,0 @@ -Save the DB in background. - -Normally the OK code is immediately returned. -Valkey forks, the parent continues to serve the clients, the child saves the DB -on disk then exits. - -An error is returned if there is already a background save running or if there -is another non-background-save process running, specifically an in-progress AOF -rewrite. - -If `BGSAVE SCHEDULE` is used, the command will immediately return `OK` when an -AOF rewrite is in progress and schedule the background save to run at the next -opportunity. - -If `BGSAVE CANCEL` is used, it will immediately terminate any in-progress RDB save or replication full sync process. -In case a background save is scheduled to run (e.g. using `BGSAVE SCHEDULE` command) the scheduled execution will be -cancelled as well. - -A client may be able to check if the operation succeeded using the [`LASTSAVE`](lastsave.md) -command. - -Please refer to the [persistence documentation][tp] for detailed information. - -[tp]: ../topics/persistence.md - -## Reply - -One of the following: - -* `Background saving started`. -* `Background saving scheduled`. diff --git a/commands/bitcount.md b/commands/bitcount.md deleted file mode 100644 index 8da04d1d..00000000 --- a/commands/bitcount.md +++ /dev/null @@ -1,78 +0,0 @@ -Count the number of set bits (population counting) in a string. - -By default all the bytes contained in the string are examined. -It is possible to specify the counting operation only in an interval passing the -additional arguments _start_ and _end_. - -Similar to the [`GETRANGE`](getrange.md) command, `start` and `end` can contain negative values in -order to index bytes starting from the end of the string, where -1 is the last -byte, -2 is the penultimate, and so forth. - -Non-existent keys are treated as empty strings, so the command will return zero. - -By default, the additional arguments `start` and `end` specify a byte index. -We can use an additional argument `BIT` to specify a bit index. -So 0 is the first bit, 1 is the second bit, and so forth. -For negative values, -1 is the last bit, -2 is the penultimate, and so forth. - -## Reply - -Integer: the number of bits set to 1. - -## Examples - -``` -127.0.0.1:6379> SET mykey "foobar" -OK -127.0.0.1:6379> BITCOUNT mykey -(integer) 26 -127.0.0.1:6379> BITCOUNT mykey 0 0 -(integer) 4 -127.0.0.1:6379> BITCOUNT mykey 1 1 -(integer) 6 -127.0.0.1:6379> BITCOUNT mykey 1 1 BYTE -(integer) 6 -127.0.0.1:6379> BITCOUNT mykey 5 30 BIT -(integer) 17 -``` - -## Pattern: real-time metrics using bitmaps - -Bitmaps are a very space-efficient representation of certain kinds of -information. -One example is a Web application that needs the history of user visits, so that -for instance it is possible to determine what users are good targets of beta -features. - -Using the [`SETBIT`](setbit.md) command, this is trivial to accomplish, identifying every day -with a small progressive integer. -For instance day 0 is the first day the application was put online, day 1 the -next day, and so forth. - -Every time a user performs a page view, the application can register that in -the current day the user visited the web site using the `SETBIT` command setting -the bit corresponding to the current day. - -Later it will be trivial to know the number of single days the user visited the -web site simply calling the `BITCOUNT` command against the bitmap. - -A similar pattern where user IDs are used instead of days is described -in the article called "[Fast easy real-time metrics using Redis bitmaps][hbgc212fermurb]". - -[hbgc212fermurb]: http://blog.getspool.com/2011/11/29/fast-easy-realtime-metrics-using-redis-bitmaps - -## Performance considerations - -In the above example of counting days, even after 10 years the application is -online we still have just `365*10` bits of data per user, that is just 456 bytes -per user. -With this amount of data `BITCOUNT` is still as fast as any other O(1) Valkey -command like [`GET`](get.md) or [`INCR`](incr.md). - -When the bitmap is big, there are two alternatives: - -* Taking a separated key that is incremented every time the bitmap is modified. - This can be very efficient and atomic using a small Lua script. -* Running the bitmap incrementally using the `BITCOUNT` `start` and `end` - optional parameters, accumulating the results client-side, and optionally - caching the result into a key. diff --git a/commands/bitfield.md b/commands/bitfield.md deleted file mode 100644 index 24a135d2..00000000 --- a/commands/bitfield.md +++ /dev/null @@ -1,117 +0,0 @@ -The command treats a string as an array of bits, and is capable of addressing specific integer fields of varying bit widths and arbitrary non (necessary) aligned offset. In practical terms using this command you can set, for example, a signed 5 bits integer at bit offset 1234 to a specific value, retrieve a 31 bit unsigned integer from offset 4567. Similarly the command handles increments and decrements of the specified integers, providing guaranteed and well specified overflow and underflow behavior that the user can configure. - -`BITFIELD` is able to operate with multiple bit fields in the same command call. It takes a list of operations to perform, and returns an array of replies, where each array matches the corresponding operation in the list of arguments. - -For example the following command increments a 5 bit signed integer at bit offset 100, and gets the value of the 4 bit unsigned integer at bit offset 0: - - > BITFIELD mykey INCRBY i5 100 1 GET u4 0 - 1) (integer) 1 - 2) (integer) 0 - -Note that: - -1. Addressing with `!GET` bits outside the current string length (including the case the key does not exist at all), results in the operation to be performed like the missing part all consists of bits set to 0. -2. Addressing with `!SET` or `!INCRBY` bits outside the current string length will enlarge the string, zero-padding it, as needed, for the minimal length needed, according to the most far bit touched. - -## Supported subcommands and integer encoding - -The following is the list of supported commands. - -* **GET** `` `` -- Returns the specified bit field. -* **SET** `` `` `` -- Set the specified bit field and returns its old value. -* **INCRBY** `` `` `` -- Increments or decrements (if a negative increment is given) the specified bit field and returns the new value. - -There is another subcommand that only changes the behavior of successive -`!INCRBY` and `!SET` subcommands calls by setting the overflow behavior: - -* **OVERFLOW** `[WRAP|SAT|FAIL]` - -Where an integer encoding is expected, it can be composed by prefixing with `i` for signed integers and `u` for unsigned integers with the number of bits of our integer encoding. So for example `u8` is an unsigned integer of 8 bits and `i16` is a -signed integer of 16 bits. - -The supported encodings are up to 64 bits for signed integers, and up to 63 bits for -unsigned integers. This limitation with unsigned integers is due to the fact -that currently the Valkey protocol is unable to return 64 bit unsigned integers -as replies. - -## Bits and positional offsets - -There are two ways in order to specify offsets in the bitfield command. -If a number without any prefix is specified, it is used just as a zero based -bit offset inside the string. - -However if the offset is prefixed with a `#` character, the specified offset -is multiplied by the integer encoding's width, so for example: - - BITFIELD mystring SET i8 #0 100 SET i8 #1 200 - -Will set the first i8 integer at offset 0 and the second at offset 8. -This way you don't have to do the math yourself inside your client if what -you want is a plain array of integers of a given size. - -## Overflow control - -Using the `OVERFLOW` command the user is able to fine-tune the behavior of -the increment or decrement overflow (or underflow) by specifying one of -the following behaviors: - -* **WRAP**: wrap around, both with signed and unsigned integers. In the case of unsigned integers, wrapping is like performing the operation modulo the maximum value the integer can contain (the C standard behavior). With signed integers instead wrapping means that overflows restart towards the most negative value and underflows towards the most positive ones, so for example if an `i8` integer is set to the value 127, incrementing it by 1 will yield `-128`. -* **SAT**: uses saturation arithmetic, that is, on underflows the value is set to the minimum integer value, and on overflows to the maximum integer value. For example incrementing an `i8` integer starting from value 120 with an increment of 10, will result into the value 127, and further increments will always keep the value at 127. The same happens on underflows, but towards the value is blocked at the most negative value. -* **FAIL**: in this mode no operation is performed on overflows or underflows detected. The corresponding return value is set to NULL to signal the condition to the caller. - -Note that each `OVERFLOW` statement only affects the `!INCRBY` and `!SET` -commands that follow it in the list of subcommands, up to the next `OVERFLOW` -statement. - -By default, **WRAP** is used if not otherwise specified. - - > BITFIELD mykey incrby u2 100 1 OVERFLOW SAT incrby u2 102 1 - 1) (integer) 1 - 2) (integer) 1 - > BITFIELD mykey incrby u2 100 1 OVERFLOW SAT incrby u2 102 1 - 1) (integer) 2 - 2) (integer) 2 - > BITFIELD mykey incrby u2 100 1 OVERFLOW SAT incrby u2 102 1 - 1) (integer) 3 - 2) (integer) 3 - > BITFIELD mykey incrby u2 100 1 OVERFLOW SAT incrby u2 102 1 - 1) (integer) 0 - 2) (integer) 3 - -The following is an example of `OVERFLOW FAIL` returning NULL. - - > BITFIELD mykey OVERFLOW FAIL incrby u2 102 1 - 1) (nil) - -## Motivations - -The motivation for this command is that the ability to store many small integers -as a single large bitmap (or segmented over a few keys to avoid having huge keys) is extremely memory efficient, and opens new use cases for Valkey to be applied, especially in the field of real time analytics. This use cases are supported by the ability to specify the overflow in a controlled way. - -Fun fact: Reddit's 2017 April fools' project [r/place](https://reddit.com/r/place) was [built using the BITFIELD command](https://redditblog.com/2017/04/13/how-we-built-rplace/) in order to take an in-memory representation of the collaborative canvas. - -## Performance considerations - -Usually `BITFIELD` is a fast command, however note that addressing far bits of currently short strings will trigger an allocation that may be more costly than executing the command on bits already existing. - -## Orders of bits - -The representation used by `BITFIELD` considers the bitmap as having the -bit number 0 to be the most significant bit of the first byte, and so forth, so -for example setting a 5 bits unsigned integer to value 23 at offset 7 into a -bitmap previously set to all zeroes, will produce the following representation: - - +--------+--------+ - |00000001|01110000| - +--------+--------+ - -When offsets and integer sizes are aligned to bytes boundaries, this is the -same as big endian, however when such alignment does not exist, its important -to also understand how the bits inside a byte are ordered. - -## Reply - -One of the following: - -* Array: each entry being the corresponding result of the sub-command given at the same position. -* Null: if OVERFLOW FAIL was given and overflows or underflows are detected. diff --git a/commands/bitfield_ro.md b/commands/bitfield_ro.md deleted file mode 100644 index 084fe5c2..00000000 --- a/commands/bitfield_ro.md +++ /dev/null @@ -1,15 +0,0 @@ -Read-only variant of the [`BITFIELD`](bitfield.md) command. -It is similar to the original `BITFIELD` but only accepts `GET` subcommand and can safely be used in read-only replicas. - -Since the original `BITFIELD` has `SET` and `INCRBY` options, it is technically flagged as a writing command in the Valkey command table. -For this reason, read-only replicas in a Valkey Cluster will redirect it to the master instance even if the connection is in read-only mode (see the [`READONLY`](readonly.md) command of Valkey Cluster). - -See original `BITFIELD` for more details. - -``` -BITFIELD_RO hello GET i8 16 -``` - -## Reply - -Array: each entry being the corresponding result of the sub-command given at the same position. diff --git a/commands/bitop.md b/commands/bitop.md deleted file mode 100644 index 5c0921af..00000000 --- a/commands/bitop.md +++ /dev/null @@ -1,62 +0,0 @@ -Perform a bitwise operation between multiple keys (containing string values) and -store the result in the destination key. - -The `BITOP` command supports four bitwise operations: **AND**, **OR**, **XOR** -and **NOT**, thus the valid forms to call the command are: - -* `BITOP AND destkey srckey1 srckey2 srckey3 ... srckeyN` -* `BITOP OR destkey srckey1 srckey2 srckey3 ... srckeyN` -* `BITOP XOR destkey srckey1 srckey2 srckey3 ... srckeyN` -* `BITOP NOT destkey srckey` - -As you can see **NOT** is special as it only takes an input key, because it -performs inversion of bits so it only makes sense as a unary operator. - -The result of the operation is always stored at `destkey`. - -## Handling of strings with different lengths - -When an operation is performed between strings having different lengths, all the -strings shorter than the longest string in the set are treated as if they were -zero-padded up to the length of the longest string. - -The same holds true for non-existent keys, that are considered as a stream of -zero bytes up to the length of the longest string. - -## Reply - -Integer: the size of the string stored in the destination key is equal to the size of the longest input string. - -## Examples - -``` -127.0.0.1:6379> SET key1 "foobar" -OK -127.0.0.1:6379> SET key2 "abcdef" -OK -127.0.0.1:6379> BITOP AND dest key1 key2 -(integer) 6 -127.0.0.1:6379> GET dest -"`bc`ab" -``` - -## Pattern: real time metrics using bitmaps - -`BITOP` is a good complement to the pattern documented in the [`BITCOUNT`](bitcount.md) command -documentation. -Different bitmaps can be combined in order to obtain a target bitmap where -the population counting operation is performed. - -See the article called "[Fast easy real-time metrics using Valkey -bitmaps][hbgc212fermurb]" for an interesting use cases. - -[hbgc212fermurb]: http://blog.getspool.com/2011/11/29/fast-easy-realtime-metrics-using-redis-bitmaps - -## Performance considerations - -`BITOP` is a potentially slow command as it runs in O(N) time. -Care should be taken when running it against long input strings. - -For real-time metrics and statistics involving large inputs a good approach is -to use a replica (with replica-read-only option enabled) where the bit-wise -operations are performed to avoid blocking the primary instance. diff --git a/commands/bitpos.md b/commands/bitpos.md deleted file mode 100644 index b8f51ffc..00000000 --- a/commands/bitpos.md +++ /dev/null @@ -1,65 +0,0 @@ -Return the position of the first bit set to 1 or 0 in a string. - -The position is returned, thinking of the string as an array of bits from left to -right, where the first byte's most significant bit is at position 0, the second -byte's most significant bit is at position 8, and so forth. - -The same bit position convention is followed by [`GETBIT`](getbit.md) and [`SETBIT`](setbit.md). - -By default, all the bytes contained in the string are examined. -It is possible to look for bits only in a specified interval by passing the additional arguments `start` and `end`. You can also just pass `start`, the operation will assume that the end is the last byte of the string. However there are semantic differences as explained later. -By default, the range is interpreted as a range of bytes and not a range of bits, so `start=0` and `end=2` means to look at the first three bytes. - -You can use the optional `BIT` modifier to specify that the range should be interpreted as a range of bits. -So `start=0` and `end=2` means to look at the first three bits. - -Note that bit positions are returned always as absolute values starting from bit zero even when `start` and `end` are used to specify a range. - -Similar to the [`GETRANGE`](getrange.md) command, `start` and `end` can contain negative values in -order to index bytes starting from the end of the string, where -1 is the last -byte, -2 is the penultimate, and so forth. When `BIT` is specified, -1 is the last -bit, -2 is the penultimate, and so forth. - -Non-existent keys are treated as empty strings. - -## Reply - -One of the following: - -* Integer: the position of the first bit set to 1 or 0 according to the request -* Integer: `-1`. In case the `bit` argument is 1 and the string is empty or composed of just zero bytes - -If we look for set bits (the bit argument is 1) and the string is empty or composed of just zero bytes, -1 is returned. - -If we look for clear bits (the bit argument is 0) and the string only contains bits set to 1, the function returns the first bit not part of the string on the right. So if the string is three bytes set to the value `0xff` the command `BITPOS key 0` will return 24, since up to bit 23 all the bits are 1. - -The function considers the right of the string as padded with zeros if you look for clear bits and specify no range or the _start_ argument **only**. - -However, this behavior changes if you are looking for clear bits and specify a range with both _start_ and _end_. - -If a clear bit isn't found in the specified range, the function returns -1 as the user specified a clear range and there are no 0 bits in that range. - -## Examples - -``` -127.0.0.1:6379> SET mykey "\xff\xf0\x00" -OK -127.0.0.1:6379> BITPOS mykey 0 -(integer) 12 -127.0.0.1:6379> SET mykey "\x00\xff\xf0" -OK -127.0.0.1:6379> BITPOS mykey 1 0 -(integer) 8 -127.0.0.1:6379> BITPOS mykey 1 2 -(integer) 16 -127.0.0.1:6379> BITPOS mykey 1 2 -1 BYTE -(integer) 16 -127.0.0.1:6379> BITPOS mykey 1 7 15 BIT -(integer) 8 -127.0.0.1:6379> set mykey "\x00\x00\x00" -OK -127.0.0.1:6379> BITPOS mykey 1 -(integer) -1 -127.0.0.1:6379> BITPOS mykey 1 7 -3 BIT -(integer) -1 -``` diff --git a/commands/blmove.md b/commands/blmove.md deleted file mode 100644 index c3957389..00000000 --- a/commands/blmove.md +++ /dev/null @@ -1,26 +0,0 @@ -`BLMOVE` is the blocking variant of [`LMOVE`](lmove.md). -When `source` contains elements, this command behaves exactly like `LMOVE`. -When used inside a [`MULTI`](multi.md)/[`EXEC`](exec.md) block, this command behaves exactly like `LMOVE`. -When `source` is empty, Valkey will block the connection until another client -pushes to it or until `timeout` (a double value specifying the maximum number of seconds to block) is reached. -A `timeout` of zero can be used to block indefinitely. - -This command comes in place of the now deprecated [`BRPOPLPUSH`](brpoplpush.md). Doing -`BLMOVE RIGHT LEFT` is equivalent. - -See [`LMOVE`](lmove.md) for more information. - -## Pattern: Reliable queue - -Please see the pattern description in the `LMOVE` documentation. - -## Pattern: Circular list - -Please see the pattern description in the `LMOVE` documentation. - -## Reply - -One of the following: - -* String: the element being popped from the _source_ and pushed to the _destination_. -* Null: the operation timed-out diff --git a/commands/blmpop.md b/commands/blmpop.md deleted file mode 100644 index 232255e6..00000000 --- a/commands/blmpop.md +++ /dev/null @@ -1,15 +0,0 @@ -`BLMPOP` is the blocking variant of [`LMPOP`](lmpop.md). - -When any of the lists contains elements, this command behaves exactly like `LMPOP`. -When used inside a [`MULTI`](multi.md)/[`EXEC`](exec.md) block, this command behaves exactly like `LMPOP`. -When all lists are empty, Valkey will block the connection until another client pushes to it or until the `timeout` (a double value specifying the maximum number of seconds to block) elapses. -A `timeout` of zero can be used to block indefinitely. - -See [`LMPOP`](lmpop.md) for more information. - -## Reply - -One of the following: - -* Null: when no element could be popped and the _timeout_ is reached. -* Two-element array with the first element being the name of the key from which elements were popped, and the second element being an array of the popped elements. diff --git a/commands/blob.info.md b/commands/blob.info.md deleted file mode 100644 index ca3afd77..00000000 --- a/commands/blob.info.md +++ /dev/null @@ -1,59 +0,0 @@ -Returns metadata about the large object stored at `key`. -The command does not transfer the payload. - -If you do not give a field, the command returns all the fields as a flat array of field names and values. -If you give one field, the command returns only the value of that field. -The field name is not case-sensitive. - -The fields are: - -* `LEN` - The length of the object, in bytes, as the client stored it. - It does not include DRAM allocation overhead (`Dram` mode) or file system overhead (`Tiered` mode). -* `CRC` - The CRC32C (Castagnoli) checksum of the payload, as an unsigned 32-bit integer. - The server calculates this value when it stores the object. -* `TIER` - The storage tier of the object: `dram` or `disk`. - -In the `Dram` operating mode, `TIER` is always `dram`. -In the `Tiered` operating mode, `TIER` is `dram` only when a cached copy of the object is ready in DRAM. -Otherwise, `TIER` is `disk`. -For more information about the operating modes, see [Valkey Large Object - Overview](../topics/large-object.md). - -If `key` does not exist, the command returns nil. -If `key` holds a value of a different type, the command returns a `WRONGTYPE` error. - -Clients can compare `LEN` and `CRC` with the values that [`BLOB.RDMA_GET`](blob.rdma_get.md) returns, or with a checksum that they calculate after [`BLOB.TCP_GET`](blob.tcp_get.md). - -## Reply - -One of the following: - -* Array: when no field is given, a flat array of field names and values: `len` and the object length as an integer, `crc` and the CRC32C checksum as an integer, and `tier` and the storage tier (`dram` or `disk`). -* Integer: the object length in bytes when `LEN` is given, or the CRC32C checksum when `CRC` is given. -* `dram` or `disk`: the storage tier when `TIER` is given. -* Null: if the key does not exist. - -An error occurs if the field is not valid, if `largeobj.enabled` is `no`, or if the key holds a value of a different type. - -## Examples - -``` -127.0.0.1:6379> BLOB.TCP_SET mykey "hello world" -OK -127.0.0.1:6379> BLOB.INFO mykey -1) len -2) (integer) 11 -3) crc -4) (integer) 3381945770 -5) tier -6) dram -127.0.0.1:6379> BLOB.INFO mykey LEN -(integer) 11 -127.0.0.1:6379> BLOB.INFO mykey crc -(integer) 3381945770 -127.0.0.1:6379> BLOB.INFO mykey TIER -dram -127.0.0.1:6379> BLOB.INFO mykey SIZE -(error) ERR invalid information field -127.0.0.1:6379> BLOB.INFO nosuchkey -(nil) -``` diff --git a/commands/blob.rdma_get.md b/commands/blob.rdma_get.md deleted file mode 100644 index ff6a3ad0..00000000 --- a/commands/blob.rdma_get.md +++ /dev/null @@ -1,81 +0,0 @@ -Writes the payload of the large object stored at `key` directly into client memory with RDMA. -The payload does not go through the Valkey connection. - -The connection must have an RDMA session. -To start a session, use [`BLOB.RDMA_HELLO`](blob.rdma_hello.md). - -Each `region` is a triple that identifies a client memory region that the client registered with its libfabric endpoint: - -* `rkey` - The remote key of the registered memory region. -* `addr` - The start address in the region. - This is a virtual address, or an offset into the registered memory when the fabric provider does not use virtual addresses. - `0` is a valid value. -* `len` - The number of bytes that the server can write into the region. - The value must be more than `0`. - -All values are unsigned decimal integers. -You can give up to 256 regions. -The server writes the object bytes into the regions in the order that you give them, and fills each region before it continues to the next one. - -The total length of all the regions must be equal to or more than the object length. -The regions can be larger than the object. -The reply gives the object length, so that the client knows where the valid data ends. - -The server replies only after all the RDMA writes are complete. -The reply is a two-element array: the object length in bytes, and the CRC32C (Castagnoli) checksum that the server stored for the object. -The client can calculate the checksum of the received bytes and compare it with this value. - -If `key` does not exist, the command returns nil. -The server looks up the key before it parses the regions and before it checks the session. -Thus, a missing key returns nil even when the connection has no RDMA session. -In `Tiered` mode, if too many disk operations run at the same time for the disk staging buffers, the command returns `ERR disk staging buffer pool exhausted; retry later`. -The error is temporary: a retry later can succeed, after operations in progress finish. -If `key` holds a value of a different type, the command returns a `WRONGTYPE` error. - -This is a blocking command, so it cannot run in transactions, scripts, functions, or module calls (see [Limitations](../topics/large-object.md#limitations)). - -To read the payload over TCP instead, use [`BLOB.TCP_GET`](blob.tcp_get.md). -To get only the length and checksum, use [`BLOB.INFO`](blob.info.md). -If the server cannot post the transfer for 1 second (for example, because the client endpoint is gone), the command fails with `ERR RDMA write failed`. -There is no other server-side timeout for the transfer. -To stop a transfer, close the connection. -For more information, see [Valkey Large Object - RDMA Transfers](../topics/large-object-rdma.md). - -## Reply - -One of the following: - -* Array: a two-element array, after all the RDMA writes are complete: the object length in bytes as an integer, and the CRC32C checksum of the object as an integer. -* Null: if the key does not exist. - -An error occurs if the memory regions are not valid or are too small for the object, if the connection has no RDMA session, if the RDMA write or a disk read fails, or if the key holds a value of a different type. See [Errors](../topics/large-object-rdma.md#errors) for all errors. - -## Examples - -You cannot do the transfer from `valkey-cli`. -The command needs a client that has a libfabric endpoint and registered memory, and that has an RDMA session on the connection. -The example shows the command shape and the reply. -In this example, the key holds a 1MB (1048576 bytes) object of zero bytes. -The first command writes the object into one region. -The second command writes the object into two regions of 512KB each. - -``` -127.0.0.1:6379> BLOB.RDMA_GET mykey 4242 140237318455296 1048576 -1) (integer) 1048576 -2) (integer) 338267154 -127.0.0.1:6379> BLOB.RDMA_GET mykey 4242 140237318455296 524288 4243 140237320552448 524288 -1) (integer) 1048576 -2) (integer) 338267154 -127.0.0.1:6379> BLOB.RDMA_GET mykey 4242 140237318455296 4096 -(error) ERR client memory address length 4096 smaller than object length 1048576 -127.0.0.1:6379> BLOB.RDMA_GET nosuchkey 4242 140237318455296 1048576 -(nil) -``` - -On a connection without an RDMA session, an existing key with regions that are large enough returns the session error. -The server checks the regions before the session: - -``` -127.0.0.1:6379> BLOB.RDMA_GET mykey 999 0 1048576 -(error) ERR no RDMA session (call BLOB.RDMA_HELLO first) -``` diff --git a/commands/blob.rdma_hello.md b/commands/blob.rdma_hello.md deleted file mode 100644 index 089b1c5f..00000000 --- a/commands/blob.rdma_hello.md +++ /dev/null @@ -1,67 +0,0 @@ -Establishes an RDMA session for the current connection. -A client must send this command once on a connection before it can use [`BLOB.RDMA_SET`](blob.rdma_set.md) or [`BLOB.RDMA_GET`](blob.rdma_get.md) on that connection. - -`client-rdma-address` is the fabric address of the client endpoint, encoded as hexadecimal text. -The client gets this address from its libfabric endpoint. -When `largeobj.fabric-provider` is `EfaDirect`, the address must be exactly 32 bytes (64 hexadecimal characters). -When `largeobj.fabric-provider` is `Emulated`, the address must be a socket address: 16 bytes for IPv4 (`sockaddr_in`) or 28 bytes for IPv6 (`sockaddr_in6`). -The command takes exactly one argument. -With no argument or more than one argument, it returns an error. - -The server adds the client address to each of its fabric services. -The reply is an array with one hexadecimal fabric address for each server fabric service. -The client must add all the returned addresses to its own address vector before the first transfer. - -The session belongs to the connection. -The server removes the session when the connection closes. -A connection can have only one session: a second `BLOB.RDMA_HELLO` on the same connection returns an error. -To use a new client endpoint, open a new connection. - -If the RDMA fabric did not start on the server, the command returns an error. -In that case, only the TCP commands, [`BLOB.TCP_SET`](blob.tcp_set.md) and [`BLOB.TCP_GET`](blob.tcp_get.md), are available. - -For the full RDMA flow and the fabric configuration, see [Valkey Large Object - RDMA Transfers](../topics/large-object-rdma.md). - -## Reply - -Array of strings: one string for each server fabric service, with the hexadecimal fabric address of that service. - -An error occurs if RDMA is not available on the server, if the client address is not valid for the fabric provider, or if the connection already has an RDMA session. See [Errors](../topics/large-object-rdma.md#errors) for all errors. - -## Examples - -A useful `BLOB.RDMA_HELLO` needs a client that has a libfabric endpoint. -`valkey-cli` can send the command, but it cannot do the RDMA transfers that follow. -The example shows the command shape and the reply, with example addresses. - -``` -127.0.0.1:6379> BLOB.RDMA_HELLO 0a1b2c3d4e5f60718293a4b5c6d7e8f900112233445566778899aabbccddeeff -1) "fe80000000000000049a1ffffe2b3c4d0b000000c5a3d1e20000000000000000" -2) "fe80000000000000049a1ffffe2b3c4e0c000000d7b4e2f30000000000000000" -127.0.0.1:6379> BLOB.RDMA_HELLO 0a1b2c3d4e5f60718293a4b5c6d7e8f900112233445566778899aabbccddeeff -(error) ERR RDMA session already established -``` - -These errors do not need an RDMA client. -The server in this example uses the `EfaDirect` fabric provider: - -``` -127.0.0.1:6379> BLOB.RDMA_HELLO zz -(error) ERR invalid rdma address hex -127.0.0.1:6379> BLOB.RDMA_HELLO 0a1b -(error) ERR rdma address must be 32 bytes -127.0.0.1:6379> BLOB.RDMA_HELLO 0a1b extra -(error) ERR wrong number of arguments for 'BLOB.RDMA_HELLO' command -``` - -With the `Emulated` fabric provider, `valkey-cli` can open a session. -The reply has one address for each server fabric service, here one: - -``` -127.0.0.1:6379> BLOB.RDMA_HELLO 0a1b -(error) ERR rdma address is not a valid sockaddr -127.0.0.1:6379> BLOB.RDMA_HELLO 02001f907f0000010000000000000000 -1) "020098ff7f0000010000000000000000" -127.0.0.1:6379> BLOB.RDMA_HELLO 02001f907f0000010000000000000000 -(error) ERR RDMA session already established -``` diff --git a/commands/blob.rdma_set.md b/commands/blob.rdma_set.md deleted file mode 100644 index f28eeb75..00000000 --- a/commands/blob.rdma_set.md +++ /dev/null @@ -1,77 +0,0 @@ -Stores a large object at `key`. -The server reads the payload directly from client memory with RDMA. -The payload does not go through the Valkey connection. - -The connection must have an RDMA session. -To start a session, use [`BLOB.RDMA_HELLO`](blob.rdma_hello.md). - -`total-len` is the length of the object in bytes. -The object must contain at least 1 byte. -The object length must not be more than the `largeobj.max-object-size` configuration (default 512MB). - -The optional `CRC` argument gives the CRC32C (Castagnoli) checksum of the payload, as an unsigned 32-bit decimal integer. -`CRC` must come directly after `total-len`. -When you give `CRC`, the server compares it with the checksum that it calculates after the transfer. -If the two values are different, the command returns an error and does not store the object. -The server always calculates the checksum and stores it with the object. - -Each `region` is a triple that identifies a client memory region that the client registered with its libfabric endpoint: - -* `rkey` - The remote key of the registered memory region. -* `addr` - The start address in the region. - This is a virtual address, or an offset into the registered memory when the fabric provider does not use virtual addresses. - `0` is a valid value. -* `len` - The number of bytes in the region. - The value must be more than `0`. - -All values are unsigned decimal integers. -You can give up to 256 regions. -The server reads `total-len` bytes from the regions in the order that you give them. -The total length of all the regions must be equal to or more than `total-len`. - -The server replies `OK` only after it reads all the bytes and stores the object. -In the `Tiered` operating mode, the server replies only after the disk write is complete. - -The overwrite, write-order, keyspace event, and eviction behavior is the same as for [`BLOB.TCP_SET`](blob.tcp_set.md). -If `key` holds a value of a different type, the command returns a `WRONGTYPE` error, and the server does not start a transfer. -The module does not replicate large objects or save their data to RDB or AOF. -This is a blocking command, so it cannot run in transactions, scripts, functions, or module calls. -For more information, see [Limitations](../topics/large-object.md#limitations). - -To read the object with RDMA, use [`BLOB.RDMA_GET`](blob.rdma_get.md). -For more information, see [Valkey Large Object - RDMA Transfers](../topics/large-object-rdma.md) and [Valkey Large Object - Configuration and Monitoring](../topics/large-object-configuration.md). - -## Reply - -`OK` after the server reads all the bytes and stores the object. - -An error occurs if an argument is not valid, if the connection has no RDMA session, if the RDMA read fails or the checksum is different from the `CRC` value, if there is not sufficient memory or disk space, or if the key holds a value of a different type. See [Errors](../topics/large-object-rdma.md#errors) for all errors. - -## Examples - -You cannot do the transfer from `valkey-cli`. -The command needs a client that has a libfabric endpoint and registered memory, and that has an RDMA session on the connection. -The example shows the command shape and the reply. -In this example, the client buffer holds 1MB (1048576 bytes) of zero bytes, with the CRC32C checksum `338267154`. - -``` -127.0.0.1:6379> BLOB.RDMA_SET mykey 1048576 4242 140237318455296 1048576 -OK -127.0.0.1:6379> BLOB.RDMA_SET mykey 1048576 CRC 338267154 4242 140237318455296 524288 4243 140237320552448 524288 -OK -127.0.0.1:6379> BLOB.INFO mykey -1) len -2) (integer) 1048576 -3) crc -4) (integer) 338267154 -5) tier -6) dram -127.0.0.1:6379> BLOB.RDMA_SET mykey 1048576 CRC 12345 4242 140237318455296 1048576 -(error) ERR CRC mismatch after transfer -127.0.0.1:6379> BLOB.RDMA_SET mykey 1048576 4242 140237318455296 1048576 4243 -(error) ERR memory address args must be rkey, addr, len triples -127.0.0.1:6379> BLOB.RDMA_SET mykey abc 4242 140237318455296 1048576 -(error) ERR invalid len -127.0.0.1:6379> BLOB.RDMA_SET mykey 1048576 CRC 4294967296 4242 140237318455296 1048576 -(error) ERR invalid CRC value -``` diff --git a/commands/blob.tcp_get.md b/commands/blob.tcp_get.md deleted file mode 100644 index cba5b5e9..00000000 --- a/commands/blob.tcp_get.md +++ /dev/null @@ -1,41 +0,0 @@ -Returns the payload of the large object stored at `key`. -The server sends the payload inline in the reply, over the normal Valkey connection. - -If `key` does not exist, the command returns nil. -If `key` holds a value of a different type, the command returns a `WRONGTYPE` error. - -The reply does not include the checksum. -To get the length and the CRC32C checksum of the object, use [`BLOB.INFO`](blob.info.md). - -In the `Dram` operating mode, the server reads the object from DRAM. -In the `Tiered` operating mode, the server reads the object from the DRAM cache if a cached copy is ready. -Otherwise, the server reads the object from disk. -If too many disk operations run at the same time for the disk staging buffers, the command returns `ERR disk staging buffer pool exhausted; retry later`. -The error is temporary: a retry later can succeed, after operations in progress finish. -When an object gets sufficient reads, the server can copy it into the DRAM cache. -For the cache configuration, see [Valkey Large Object - Configuration and Monitoring](../topics/large-object-configuration.md). - -This is a blocking command, so it cannot run in transactions, scripts, functions, or module calls (see [Limitations](../topics/large-object.md#limitations)). - -To store an object over TCP, use [`BLOB.TCP_SET`](blob.tcp_set.md). -To write the payload directly into client memory with RDMA, use [`BLOB.RDMA_GET`](blob.rdma_get.md). - -## Reply - -One of the following: - -* String: the payload of the object. -* Null: if the key does not exist. - -An error occurs if a disk read fails, if `Tiered` mode has no free disk staging buffers, if the command runs in a transaction or a script, or if the key holds a value of a different type. See [Errors at run time](../topics/large-object-getting-started.md#errors-at-run-time) for all errors. - -## Examples - -``` -127.0.0.1:6379> BLOB.TCP_SET mykey "Hello, large object!" -OK -127.0.0.1:6379> BLOB.TCP_GET mykey -"Hello, large object!" -127.0.0.1:6379> BLOB.TCP_GET nosuchkey -(nil) -``` diff --git a/commands/blob.tcp_set.md b/commands/blob.tcp_set.md deleted file mode 100644 index 59e47b68..00000000 --- a/commands/blob.tcp_set.md +++ /dev/null @@ -1,62 +0,0 @@ -Stores a large object at `key`. -The client sends the payload inline in the command, over the normal Valkey connection. -The object length is the byte length of `value`. - -If `key` does not exist, the command creates it. -If `key` already holds a large object, the command replaces it, and the server frees the storage of the old object. -If `key` holds a value of a different type, the command returns a `WRONGTYPE` error and does not change the key. - -The object must contain at least 1 byte. -The object length must not be more than the `largeobj.max-object-size` configuration (default 512MB). -The object length is also limited by the core `proto-max-bulk-len` configuration (default 512MB). -For a larger value, the server replies `ERR Protocol error: invalid bulk length` and closes the connection. -For the size limits and the memory configuration, see [Valkey Large Object - Configuration and Monitoring](../topics/large-object-configuration.md). - -The server calculates a CRC32C (Castagnoli) checksum of the payload and stores it with the object. -Use [`BLOB.INFO`](blob.info.md) to read the length and the checksum. - -In the `Dram` operating mode, the server stores the object in DRAM and then replies. -In the `Tiered` operating mode, the server writes the object to a file in `largeobj.disk-dir`, and replies only after the disk write is complete. -If too many disk operations run at the same time for the disk staging buffers, the command returns `ERR disk staging buffer pool exhausted; retry later`. -This is a limit on concurrent disk operations, not a lack of DRAM for data. -The error is temporary: a retry later can succeed, after operations in progress finish. -Raise `largeobj.disk-staging-size` (needs a restart), lower `largeobj.max-buffers-per-op`, or send fewer concurrent disk operations. -When there is not sufficient space, the server can evict other large objects to make room, if the eviction configuration permits it. - -When two writes to the same key run at the same time, the write that the server received last is kept. -The server also replies `OK` to the write that it discards. - -After a successful write, the server publishes the keyspace event `largeobj.create` (new key) or `largeobj.update` (replaced key), of type module, when `notify-keyspace-events` includes module key type events (`d`). -The server does not publish an event when the write fails. - -The module does not replicate large objects or save their data to RDB or AOF. -This is a blocking command, so it cannot run in transactions, scripts, functions, or module calls. -For more information, see [Limitations](../topics/large-object.md#limitations). - -To read the object back over TCP, use [`BLOB.TCP_GET`](blob.tcp_get.md). -To send the payload with RDMA instead of inline in the command, use [`BLOB.RDMA_SET`](blob.rdma_set.md). - -## Reply - -`OK` after the server stores the object. - -An error occurs if the value is empty or larger than `largeobj.max-object-size`, if there is not sufficient memory or disk space, if a disk write fails, if the command runs in a transaction or a script, or if the key holds a value of a different type. See [Errors at run time](../topics/large-object-getting-started.md#errors-at-run-time) for all errors. - -## Examples - -``` -127.0.0.1:6379> BLOB.TCP_SET mykey "hello world" -OK -127.0.0.1:6379> BLOB.TCP_GET mykey -"hello world" -127.0.0.1:6379> BLOB.TCP_SET mykey "123456789" -OK -127.0.0.1:6379> BLOB.INFO mykey LEN -(integer) 9 -127.0.0.1:6379> BLOB.TCP_SET mykey "" -(error) ERR object length must be > 0 -127.0.0.1:6379> SET mystring "abc" -OK -127.0.0.1:6379> BLOB.TCP_SET mystring "hello world" -(error) WRONGTYPE Operation against a key holding the wrong kind of value -``` diff --git a/commands/blpop.md b/commands/blpop.md deleted file mode 100644 index 4e6ad024..00000000 --- a/commands/blpop.md +++ /dev/null @@ -1,132 +0,0 @@ -`BLPOP` is a blocking list pop primitive. -It is the blocking version of [`LPOP`](lpop.md) because it blocks the connection when there -are no elements to pop from any of the given lists. -An element is popped from the head of the first list that is non-empty, with the -given keys being checked in the order that they are given. - -## Non-blocking behavior - -When `BLPOP` is called, if at least one of the specified keys contains a -non-empty list, an element is popped from the head of the list and returned to -the caller together with the `key` it was popped from. - -Keys are checked in the order that they are given. -Let's say that the key `list1` doesn't exist and `list2` and `list3` hold -non-empty lists. -Consider the following command: - -``` -BLPOP list1 list2 list3 0 -``` - -`BLPOP` guarantees to return an element from the list stored at `list2` (since -it is the first non empty list when checking `list1`, `list2` and `list3` in -that order). - -## Blocking behavior - -If none of the specified keys exist, `BLPOP` blocks the connection until another -client performs an [`LPUSH`](lpush.md) or [`RPUSH`](rpush.md) operation against one of the keys. - -Once new data is present on one of the lists, the client returns with the name -of the key unblocking it and the popped value. - -When `BLPOP` causes a client to block and a non-zero timeout is specified, -the client will unblock returning a `nil` multi-bulk value when the specified -timeout has expired without a push operation against at least one of the -specified keys. - -**The timeout argument is interpreted as a double value specifying the maximum number of seconds to block**. A timeout of zero can be used to block indefinitely. - -## What key is served first? What client? What element? Priority ordering details. - -* If the client tries to blocks for multiple keys, but at least one key contains elements, the returned key / element pair is the first key from left to right that has one or more elements. In this case the client is not blocked. So for instance `BLPOP key1 key2 key3 key4 0`, assuming that both `key2` and `key4` are non-empty, will always return an element from `key2`. -* If multiple clients are blocked for the same key, the first client to be served is the one that was waiting for more time (the first that blocked for the key). Once a client is unblocked it does not retain any priority, when it blocks again with the next call to `BLPOP` it will be served accordingly to the number of clients already blocked for the same key, that will all be served before it (from the first to the last that blocked). -* When a client is blocking for multiple keys at the same time, and elements are available at the same time in multiple keys (because of a transaction or a Lua script added elements to multiple lists), the client will be unblocked using the first key that received a push operation (assuming it has enough elements to serve our client, as there may be other clients as well waiting for this key). Basically after the execution of every command Valkey will run a list of all the keys that received data AND that have at least a client blocked. The list is ordered by new element arrival time, from the first key that received data to the last. For every key processed, Valkey will serve all the clients waiting for that key in a FIFO fashion, as long as there are elements in this key. When the key is empty or there are no longer clients waiting for this key, the next key that received new data in the previous command / transaction / script is processed, and so forth. - -## Behavior of `BLPOP` when multiple elements are pushed inside a list. - -There are times when a list can receive multiple elements in the context of the same conceptual command: - -* Variadic push operations such as `LPUSH mylist a b c`. -* After an [`EXEC`](exec.md) of a [`MULTI`](multi.md) block with multiple push operations against the same list. -* Executing a Lua Script. - -What happens is that the command performing multiple pushes is executed, and *only after* the execution of the command the blocked clients are served. Consider this sequence of commands. - - Client A: BLPOP foo 0 - Client B: LPUSH foo a b c - -If the above condition happens using a Redis OSS 2.6 server or greater, Client **A** will be served with the `c` element, because after the `LPUSH` command the list contains `c,b,a`, so taking an element from the left means to return `c`. - -Note that for the same reason a Lua script or a `MULTI/EXEC` block may push elements into a list and afterward **delete the list**. In this case the blocked clients will not be served at all and will continue to be blocked as long as no data is present on the list after the execution of a single command, transaction, or script. - -## `BLPOP` inside a `MULTI` / `EXEC` transaction - -`BLPOP` can be used with pipelining (sending multiple commands and -reading the replies in batch), however this setup makes sense almost solely -when it is the last command of the pipeline. - -Using `BLPOP` inside a `MULTI`/`EXEC` block does not make a lot of sense -as it would require blocking the entire server in order to execute the block -atomically, which in turn does not allow other clients to perform a push -operation. For this reason the behavior of `BLPOP` inside `MULTI` / `EXEC` when the list is empty is to return a `nil` multi-bulk reply, which is the same -thing that happens when the timeout is reached. - -If you like science fiction, think of time flowing at infinite speed inside a -`MULTI` / `EXEC` block... - -## Reply - -One of the following: - -* Null: no element could be popped and the timeout expired -* Array: the key from which the element was popped and the value of the popped element. - -## Examples - -``` -127.0.0.1:6379> DEL list1 list2 -(integer) 0 -127.0.0.1:6379> RPUSH list1 a b c -(integer) 3 -127.0.0.1:6379> BLPOP list1 list2 0 -1) "list1" -2) "a" -``` - -## Reliable queues - -When `BLPOP` returns an element to the client, it also removes the element from the list. This means that the element only exists in the context of the client: if the client crashes while processing the returned element, it is lost forever. - -This can be a problem with some application where we want a more reliable messaging system. When this is the case, please check the [`BRPOPLPUSH`](brpoplpush.md) command, that is a variant of `BLPOP` that adds the returned element to a target list before returning it to the client. - -## Pattern: Event notification - -Using blocking list operations it is possible to mount different blocking -primitives. -For instance for some application you may need to block waiting for elements -into a Set, so that as far as a new element is added to the Set, it is -possible to retrieve it without resort to polling. -This would require a blocking version of [`SPOP`](spop.md) that is not available, but using -blocking list operations we can easily accomplish this task. - -The consumer will do: - -``` -LOOP forever - WHILE SPOP(key) returns elements - ... process elements ... - END - BRPOP helper_key -END -``` - -While in the producer side we'll use simply: - -``` -MULTI -SADD key element -LPUSH helper_key x -EXEC -``` diff --git a/commands/brpop.md b/commands/brpop.md deleted file mode 100644 index dd319284..00000000 --- a/commands/brpop.md +++ /dev/null @@ -1,30 +0,0 @@ -`BRPOP` is a blocking list pop primitive. -It is the blocking version of [`RPOP`](rpop.md) because it blocks the connection when there -are no elements to pop from any of the given lists. -An element is popped from the tail of the first list that is non-empty, with the -given keys being checked in the order that they are given. - -See the [BLPOP documentation][cb] for the exact semantics, since `BRPOP` is -identical to `BLPOP` with the only difference being that it pops elements from -the tail of a list instead of popping from the head. - -[cb]: blpop.md - -## Reply - -One of the following: - -* Null: no element could be popped and the timeout expired. -* Array: the key from which the element was popped and the value of the popped element - -## Examples - -``` -127.0.0.1:6379> DEL list1 list2 -(integer) 0 -127.0.0.1:6379> RPUSH list1 a b c -(integer) 3 -127.0.0.1:6379> BRPOP list1 list2 0 -1) "list1" -2) "c" -``` diff --git a/commands/brpoplpush.md b/commands/brpoplpush.md deleted file mode 100644 index 51f28f72..00000000 --- a/commands/brpoplpush.md +++ /dev/null @@ -1,27 +0,0 @@ -`BRPOPLPUSH` is the blocking variant of `RPOPLPUSH`. -When `source` contains elements, this command behaves exactly like `RPOPLPUSH`. -When used inside a `MULTI`/`EXEC` block, this command behaves exactly like `RPOPLPUSH`. -When `source` is empty, Valkey will block the connection until another client -pushes to it or until `timeout` is reached. -A `timeout` of zero can be used to block indefinitely. - -See `RPOPLPUSH` for more information. - -## Pattern: Reliable queue - -Please see the pattern description in the `RPOPLPUSH` documentation. - -## Pattern: Circular list - -Please see the pattern description in the `RPOPLPUSH` documentation. - -## Alternative - -`BLMOVE` with the `RIGHT` and `LEFT` arguments. - -## Reply - -One of the following: - -* String: the element being popped from _source_ and pushed to _destination_. -* Null: the timeout is reached. diff --git a/commands/bzmpop.md b/commands/bzmpop.md deleted file mode 100644 index cef8d730..00000000 --- a/commands/bzmpop.md +++ /dev/null @@ -1,15 +0,0 @@ -`BZMPOP` is the blocking variant of `ZMPOP`. - -When any of the sorted sets contains elements, this command behaves exactly like `ZMPOP`. -When used inside a `MULTI`/`EXEC` block, this command behaves exactly like `ZMPOP`. -When all sorted sets are empty, Valkey will block the connection until another client adds members to one of the keys or until the `timeout` (a double value specifying the maximum number of seconds to block) elapses. -A `timeout` of zero can be used to block indefinitely. - -See `ZMPOP` for more information. - -## Reply - -One of the following: - -* Null: when no element could be popped. -* Two-element array with the first element being the name of the key from which elements were popped, and the second element is an array of the popped elements. Every entry in the elements array is also an array that contains the member and its score. diff --git a/commands/bzpopmax.md b/commands/bzpopmax.md deleted file mode 100644 index 61e7bfe9..00000000 --- a/commands/bzpopmax.md +++ /dev/null @@ -1,35 +0,0 @@ -`BZPOPMAX` is the blocking variant of the sorted set `ZPOPMAX` primitive. - -It is the blocking version because it blocks the connection when there are no -members to pop from any of the given sorted sets. -A member with the highest score is popped from first sorted set that is -non-empty, with the given keys being checked in the order that they are given. - -The `timeout` argument is interpreted as a double value specifying the maximum -number of seconds to block. A timeout of zero can be used to block indefinitely. - -See the [BZPOPMIN documentation][cb] for the exact semantics, since `BZPOPMAX` -is identical to `BZPOPMIN` with the only difference being that it pops members -with the highest scores instead of popping the ones with the lowest scores. - -[cb]: bzpopmin.md - -## Reply - -One of the following: - -* Null: when no element could be popped and the _timeout_ expired. -* Array: the keyname, popped member, and its score. - -## Examples - -``` -127.0.0.1:6379> DEL zset1 zset2 -(integer) 0 -127.0.0.1:6379> ZADD zset1 0 a 1 b 2 c -(integer) 3 -127.0.0.1:6379> BZPOPMAX zset1 zset2 0 -1) "zset1" -2) "c" -3) "2" -``` diff --git a/commands/bzpopmin.md b/commands/bzpopmin.md deleted file mode 100644 index c7542008..00000000 --- a/commands/bzpopmin.md +++ /dev/null @@ -1,35 +0,0 @@ -`BZPOPMIN` is the blocking variant of the sorted set `ZPOPMIN` primitive. - -It is the blocking version because it blocks the connection when there are no -members to pop from any of the given sorted sets. -A member with the lowest score is popped from first sorted set that is -non-empty, with the given keys being checked in the order that they are given. - -The `timeout` argument is interpreted as a double value specifying the maximum -number of seconds to block. A timeout of zero can be used to block indefinitely. - -See the [BLPOP documentation][cl] for the exact semantics, since `BZPOPMIN` is -identical to `BLPOP` with the only difference being the data structure being -popped from. - -[cl]: blpop.md - -## Reply - -One of the following: - -* Null: when no element could be popped and the _timeout_ expired. -* Array: the keyname, popped member, and its score. - -## Examples - -``` -127.0.0.1:6379> DEL zset1 zset2 -(integer) 0 -127.0.0.1:6379> ZADD zset1 0 a 1 b 2 c -(integer) 3 -127.0.0.1:6379> BZPOPMIN zset1 zset2 0 -1) "zset1" -2) "a" -3) "0" -``` diff --git a/commands/client-caching.md b/commands/client-caching.md deleted file mode 100644 index 8529b9f2..00000000 --- a/commands/client-caching.md +++ /dev/null @@ -1,22 +0,0 @@ -This command controls the tracking of the keys in the next command executed -by the connection, when tracking is enabled in `OPTIN` or `OPTOUT` mode. -Please check the -[client side caching documentation](../topics/client-side-caching.md) for -background information. - -When tracking is enabled Valkey, using the [`CLIENT TRACKING`](client-tracking.md) command, it is -possible to specify the `OPTIN` or `OPTOUT` options, so that keys -in read only commands are not automatically remembered by the server to -be invalidated later. When we are in `OPTIN` mode, we can enable the -tracking of the keys in the next command by calling `CLIENT CACHING yes` -immediately before it. Similarly when we are in `OPTOUT` mode, and keys -are normally tracked, we can avoid the keys in the next command to be -tracked using `CLIENT CACHING no`. - -Basically the command sets a state in the connection, that is valid only -for the next command execution, that will modify the behavior of client -tracking. - -## Reply - -`OK` or an error if the argument is not "yes" or "no". diff --git a/commands/client-capa.md b/commands/client-capa.md deleted file mode 100644 index 7e4630ea..00000000 --- a/commands/client-capa.md +++ /dev/null @@ -1,18 +0,0 @@ -Clients can declare their capabilities to Valkey using the `CLIENT CAPA` command, and Valkey -will adjust the corresponding features for the current connection based on the declared client capabilities. - -Multiple capabilities can be declared in the command. If any capabilities are unrecognized, -Valkey will ignore them instead of returning an error. - -The capabilities currently supported are: - -* `redirect` - This indicates that the client is capable of handling redirect messages. - When accessing a replica node in standalone mode, if a data operation is performed (read or write commands), - Valkey will return `-REDIRECT primary-ip:port` to this connection. - Since Valkey 9.2, the same applies in cluster mode to read or write commands with no key arguments, such as `SCAN` or `FLUSHDB`. - Note that the `primary-ip` can be an IPv6 which itself contains colons, so to properly parse ip and port, a client needs to locate the *last* colon. - Using the [`READONLY`](readonly.md) command can enable this connection to execute read commands on the replica node. - -## Reply - -`OK`. diff --git a/commands/client-getname.md b/commands/client-getname.md deleted file mode 100644 index d7af58a5..00000000 --- a/commands/client-getname.md +++ /dev/null @@ -1,8 +0,0 @@ -The `CLIENT GETNAME` returns the name of the current connection as set by [`CLIENT SETNAME`](client-setname.md). Since every new connection starts without an associated name, if no name was assigned a null bulk reply is returned. - -## Reply - -One of the following: - -* String: the connection name of the current connection. -* Null: the connection name was not set. diff --git a/commands/client-getredir.md b/commands/client-getredir.md deleted file mode 100644 index a0aae0c4..00000000 --- a/commands/client-getredir.md +++ /dev/null @@ -1,15 +0,0 @@ -This command returns the client ID we are redirecting our -[tracking](../topics/client-side-caching.md) notifications to. We set a client -to redirect to when using [`CLIENT TRACKING`](client-tracking.md) to enable tracking. However in -order to avoid forcing client libraries implementations to remember the -ID notifications are redirected to, this command exists in order to improve -introspection and allow clients to check later if redirection is active -and towards which client ID. - -## Reply - -One of the following: - -* Integer: `0` when not redirecting notifications to any client. -* Integer: `-1` if client tracking is not enabled. -* Integer: the ID of the client to which notification are being redirected. diff --git a/commands/client-help.md b/commands/client-help.md deleted file mode 100644 index 426698e3..00000000 --- a/commands/client-help.md +++ /dev/null @@ -1,5 +0,0 @@ -The `CLIENT HELP` command returns a helpful text describing the different subcommands. - -## Reply - -Array of subcommands and their descriptions. diff --git a/commands/client-id.md b/commands/client-id.md deleted file mode 100644 index dd55fa47..00000000 --- a/commands/client-id.md +++ /dev/null @@ -1,19 +0,0 @@ -The command just returns the ID of the current connection. Every connection -ID has certain guarantees: - -1. It is never repeated, so if `CLIENT ID` returns the same number, the caller can be sure that the underlying client did not disconnect and reconnect the connection, but it is still the same connection. -2. The ID is monotonically incremental. If the ID of a connection is greater than the ID of another connection, it is guaranteed that the second connection was established with the server at a later time. - -This command is especially useful together with [`CLIENT UNBLOCK`](client-unblock.md). -Check the `CLIENT UNBLOCK` command page for a pattern involving the two commands. - -## Reply - -Integer: the ID of the client. - -## Examples - -``` -127.0.0.1:6379> CLIENT ID -(integer) 2873 -``` diff --git a/commands/client-import-source.md b/commands/client-import-source.md deleted file mode 100644 index 5c83c885..00000000 --- a/commands/client-import-source.md +++ /dev/null @@ -1,14 +0,0 @@ -When the client sync data from a Redis-like server to Valkey using some sync tools like [RedisShake](https://github.com/tair-opensource/RedisShake), Valkey performs expiration and eviction as usual because it's a primary, which may cause data corruption. For example, the client calls `set key 1 ex 1` on the source server and this command is transferred to the destination server. Then the client calls `incr key` on the source server before the key expired, there will be a key on the source server with the value of 2. But when the command arrived at the destination server, the key may be expired and has deleted. So there will be a key on the destination server with the value of 1, which is inconsistent with the source server. Sync tools can solve this problem by setting `import-mode` config to `yes` and declaring their connections as `IMPORT-SOURCE`. - -The `CLIENT IMPORT-SOURCE` command mark this client as an import source if import-mode is enabled and can visit expired keys. The following modes are available: - -* `ON`. In this mode the client can visit expired keys. -* `OFF`. This is the default mode in which the client works as a normal client. - -## Reply - -`OK`. - -## Notes - -The server needs to be configured with `import-mode yes` before marking a client connection as an import source. diff --git a/commands/client-info.md b/commands/client-info.md deleted file mode 100644 index fb44af99..00000000 --- a/commands/client-info.md +++ /dev/null @@ -1,14 +0,0 @@ -The command returns information and statistics about the current client connection in a mostly human readable format. - -The reply format is identical to that of [`CLIENT LIST`](client-list.md), and the content consists only of information about the current client. - -## Reply - -Verbatim string: a unique string for the current client, as described at the `CLIENT LIST` page. - -## Examples - -``` -127.0.0.1:6379> CLIENT INFO -id=2875 addr=127.0.0.1:38610 laddr=127.0.0.1:6379 fd=10 name= age=0 idle=0 flags=N capa= db=0 sub=0 psub=0 ssub=0 multi=-1 watch=0 qbuf=26 qbuf-free=20448 argv-mem=10 multi-mem=0 rbs=16384 rbp=16384 obl=0 oll=0 omem=0 tot-mem=37786 events=r cmd=client|info user=default redir=-1 resp=2 lib-name= lib-ver= tot-net-in=26 tot-net-out=0 tot-cmds=0 -``` diff --git a/commands/client-kill.md b/commands/client-kill.md deleted file mode 100644 index 0cda0460..00000000 --- a/commands/client-kill.md +++ /dev/null @@ -1,69 +0,0 @@ -The `CLIENT KILL` command closes a given client connection. This command support two formats, the old format: - - CLIENT KILL addr:port - -The `ip:port` should match a line returned by the `CLIENT LIST` command (`addr` field). - -The new format: - - CLIENT KILL ... ... - -With the new form it is possible to kill clients by different attributes -instead of killing just by address. The following filters are available: - -* `CLIENT KILL ADDR ip:port`. This is exactly the same as the old three-arguments behavior. -* `CLIENT KILL LADDR ip:port`. Kill all clients connected to specified local (bind) address. -* `CLIENT KILL ID client-id [client-id ...]`. Allows to kill a client by its unique `ID` field. Client `ID`'s can be retrieved using the `CLIENT LIST` command. The filter supports one or more `client-id` arguments. -* `CLIENT KILL TYPE type`, where *type* is one of `normal`, `master`, `replica` and `pubsub`. This closes the connections of **all the clients** in the specified class. Note that clients blocked into the `MONITOR` command are considered to belong to the `normal` class. -* `CLIENT KILL USER username`. Closes all the connections that are authenticated with the specified [ACL](../topics/acl.md) username, however it returns an error if the username does not map to an existing ACL user. -* `CLIENT KILL SKIPME yes/no`. By default this option is set to `yes`, that is, the client calling the command will not get killed, however setting this option to `no` will have the effect of also killing the client calling the command. -* `CLIENT KILL MAXAGE maxage`. Closes all the connections that are older than the specified age, in seconds. -* `CLIENT KILL FLAGS flags`. Kill only clients whose flag string includes the specified characters. Returns an error if valid flags are not used. -* `CLIENT KILL NAME name`. Kill clients with the specified name. -* `CLIENT KILL IDLE idle`. Kill only clients that have been idle for at least the specified time. -* `CLIENT KILL LIB-NAME lib-name`. Kill clients using the specified library name. -* `CLIENT KILL LIB-VER lib-version`. Kill clients running the specified library version. -* `CLIENT KILL DB db`. Kill clients operating on the specified database id. -* `CLIENT KILL IP ip`. Kill clients with the specified originating IP address. -* `CLIENT KILL CAPA capa`. Kill clients that have the specified capabilities. -* `CLIENT KILL NOT-ID client-id [client-id ...]`. Kill clients are not in the IDs set. -* `CLIENT KILL NOT-TYPE type`. Kill clients are not in the specified type. -* `CLIENT KILL NOT-ADDR ip:port`. Kill clients except the specified ip and port. -* `CLIENT KILL NOT-LADDR ip:port`. Kill all clients not connected to specified local (bind) address. -* `CLIENT KILL NOT-USER username`. Closes all the connections that are not authenticated with the specified [ACL](../topics/acl.md) username. -* `CLIENT KILL NOT-FLAGS flags`. Kill clients not with the specified flag string. -* `CLIENT KILL NOT-NAME name`. Kill clients not with the specified name. -* `CLIENT KILL NOT-LIB-NAME lib-name`. Kill clients not using the specified library name. -* `CLIENT KILL NOT-LIB-VER lib-version`. Kill clients not with the specified library version. -* `CLIENT KILL NOT-DB db`. Kill clients not with the specified database ID. -* `CLIENT KILL NOT-CAPA capa`. Kill clients not with the specified capabilities. -* `CLIENT KILL NOT-IP ip`. Kill clients not with the specified IP address. - -It is possible to provide multiple filters at the same time. The command will handle multiple filters via logical AND. For example: - - CLIENT KILL addr 127.0.0.1:12345 type pubsub - -is valid and will kill only a pubsub client with the specified address. This format containing multiple filters is rarely useful currently. - -When the new form is used the command no longer returns `OK` or an error, but instead the number of killed clients, that may be zero. - -## CLIENT KILL and Valkey Sentinel - -Valkey Sentinel uses CLIENT KILL to terminate client connections when an instance is reconfigured. -This mechanism ensures that clients re-establish a connection with a Sentinel, refreshing their configurations. - -## Reply - -One of the following: - -* `OK` when called in 3 argument format and the connection has been closed. -* Integer: when called in filter/value format, the number of clients killed. - -## Notes - -Due to the single-threaded nature of Valkey, it is not possible to -kill a client connection while it is executing a command. From -the client point of view, the connection can never be closed -in the middle of the execution of a command. However, the client -will notice the connection has been closed only when the -next command is sent (and results in network error). diff --git a/commands/client-list.md b/commands/client-list.md deleted file mode 100644 index 193ca1df..00000000 --- a/commands/client-list.md +++ /dev/null @@ -1,158 +0,0 @@ -The `CLIENT LIST` command returns information and statistics about the client -connections server in a mostly human readable format. - -You can use one or more optional arguments to filter the list: - -- **`TYPE type`**: Filters the list by clients' type, where *type* is one of `normal`, `master`, `replica`, and `pubsub`. - > Note: Clients blocked by the `MONITOR` command belong to the `normal` class. - -- **`ID client-id [client-id ...]`**: Returns entries for clients with IDs matching one or more `client-id` arguments. - -- **`USER user`**: Filters the list to include only clients authenticated as the specified user. - -- **`ADDR ip:port`**: Filters the list to include only clients connected from the specified address and port. - -- **`LADDR ip:port`**: Filters the list to include only clients connected to the specified local address and port. - -- **`SKIPME yes|no`**: Filters whether the list should skip the client making the request. - - `yes`: Skips the client making the request. - - `no`: Includes the client making the request. - -- **`MAXAGE milliseconds`**: Filters the list to include only clients whose connection age (time since the client was created) is greater than or equal to the specified number of milliseconds. - > Note: This is actually a minimum age, not a maximum age. This filter was first added to CLIENT KILL, where the intention was to keep clients of a maximum age and kill the ones newer than the max age. - -- **`FLAGS flags`**: Filters the list by the client's flag string. - -- **`NAME name`**: Filters the list to include only clients with the specified name. - -- **`IDLE idle`**: Includes only clients that have been idle for at least the specified time. - -- **`LIB-NAME lib-name`**: Filters the list to include only clients using the specified library name. - -- **`LIB-VER lib-ver`**: Filters the list to include only clients with the specified library version. - -- **`DB db`**: Filters the list to include only clients with the specified database ID. - -- **`IP ip`**: Filters the list to include only clients with the specified IP address. - -- **`CAPA capa`**: Filters the list to include only clients with the specified capabilities. - -- **`NOT-ID client-id [client-id ...]`**: Excludes clients in the IDs set. - -- **`NOT-TYPE type`**: Excludes clients of the specified type. - -- **`NOT-ADDR ip:port`**: Excludes clients of the specified address and port. - -- **`NOT-LADDR ip:port`**: Excludes clients connected to the specified local address and port. - -- **`NOT-USER user`**: Excludes clients of the specified user. - -- **`NOT-FLAGS flags`**: Excludes clients with the specified flag string. - -- **`NOT-NAME name`**: Excludes clients with the specified name. - -- **`NOT-LIB-NAME lib-name`**: Excludes clients using the specified library name. - -- **`NOT-LIB-VER lib-ver`**: Excludes clients with the specified library version. - -- **`NOT-DB db`**: Excludes clients with the specified database ID. - -- **`NOT-CAPA capa`**: Excludes clients with the specified capabilities. - -- **`NOT-IP ip`**: Excludes clients with the specified IP address. - -Filters can be combined to perform more precise searches. The command will handle multiple filters via logical AND. - -Here is the meaning of the fields: - -* `id`: a unique 64-bit client ID -* `addr`: address/port of the client -* `laddr`: address/port of local address client connected to (bind address) -* `fd`: file descriptor corresponding to the socket -* `name`: the name set by the client with [`CLIENT SETNAME`](client-setname.md) -* `age`: total duration of the connection in seconds -* `idle`: idle time of the connection in seconds -* `flags`: client flags (see below) -* `capa`: client capabilities (see below). Added in Valkey 8.1 -* `db`: current database ID -* `sub`: number of channel subscriptions -* `psub`: number of pattern matching subscriptions -* `ssub`: number of shard channel subscriptions. -* `multi`: number of commands in a MULTI/EXEC context -* `watch`: number of keys this client is currently watching. Added in Valkey 8.0 -* `qbuf`: query buffer length (0 means no query pending) -* `qbuf-free`: free space of the query buffer (0 means the buffer is full) -* `argv-mem`: incomplete arguments for the next command (already extracted from query buffer) -* `multi-mem`: memory is used up by buffered multi commands. -* `obl`: output buffer length -* `oll`: output list length (replies are queued in this list when the buffer is full) -* `omem`: output buffer memory usage -* `tot-mem`: total memory consumed by this client in its various buffers -* `events`: file descriptor events (see below) -* `cmd`: last command played -* `user`: the authenticated username of the client -* `redir`: client id of current client tracking redirection -* `resp`: client RESP protocol version. -* `lib-name`: The client library name as set by [`CLIENT SETINFO`](client-setinfo.md) -* `lib-version`: The client library version as set by `CLIENT SETINFO` -* `tot-net-in`: Total network input bytes read from this client. Added in Valkey 8.0 -* `tot-net-out`: Total network output bytes sent to this client. Added in Valkey 8.0 -* `tot-cmds`: Total count of commands this client executed. Added in Valkey 8.0 - -The client flags can be a combination of: - -``` -A: connection to be closed ASAP -b: the client is waiting in a blocking operation -c: connection to be closed after writing entire reply -d: a watched keys has been modified - EXEC will fail -e: the client is excluded from the client eviction mechanism -i: the client is waiting for a VM I/O (deprecated) -M: the client is a primary -N: no specific flag set -O: the client is a client in MONITOR mode -P: the client is a Pub/Sub subscriber -r: the client is in readonly mode against a cluster node -S: the client is a replica node connection to this instance -u: the client is unblocked -U: the client is connected via a Unix domain socket -x: the client is in a MULTI/EXEC context -t: the client enabled keys tracking in order to perform client side caching -T: the client will not touch the LRU/LFU of the keys it accesses -R: the client tracking target client is invalid -B: the client enabled broadcast tracking mode -I: the client is an import source -h: the client is being throttled -``` - -Client's capabilities can be: - -``` -r: the client can handle redirect messages -``` - -The file descriptor events can be: - -``` -r: the client socket is readable (event loop) -w: the client socket is writable (event loop) -``` - -## Reply - -Verbatim string: information and statistics about client connections. - -## Examples - -```bash -CLIENT LIST TYPE normal USER admin MAXAGE 5000 ID 1234 5678 -id=1234 addr=127.0.0.1:64000 laddr=127.0.0.1:6379 fd=5 name= age=600 idle=300 flags= db=0 sub=0 psub=0 ssub=0 multi=-1 watch=0 qbuf=0 qbuf-free=32768 obl=0 oll=0 omem=0 tot-mem=1024 events=r cmd=client|list user=default redir=-1 resp=2 lib-name= lib-ver= -id=5678 addr=127.0.0.1:64001 laddr=127.0.0.1:6379 fd=6 name= age=900 idle=450 flags= db=0 sub=0 psub=0 ssub=0 multi=-1 watch=0 qbuf=0 qbuf-free=32768 obl=0 oll=0 omem=0 tot-mem=2048 events=r cmd=client|list user=default redir=-1 resp=2 lib-name= lib-ver= -``` - -## Notes - -New fields are regularly added for debugging purpose. Some could be removed -in the future. A version safe Valkey client using this command should parse -the output accordingly (i.e. handling gracefully missing fields, skipping -unknown fields). diff --git a/commands/client-no-evict.md b/commands/client-no-evict.md deleted file mode 100644 index 064842de..00000000 --- a/commands/client-no-evict.md +++ /dev/null @@ -1,11 +0,0 @@ -The `CLIENT NO-EVICT` command sets the [client eviction](../topics/clients.md#client-eviction) mode for the current connection. - -When turned on and client eviction is configured, the current connection will be excluded from the client eviction process even if we're above the configured client eviction threshold. - -When turned off, the current client will be re-included in the pool of potential clients to be evicted (and evicted if needed). - -See [client eviction](../topics/clients.md#client-eviction) for more details. - -## Reply - -`OK`. diff --git a/commands/client-no-touch.md b/commands/client-no-touch.md deleted file mode 100644 index 6ca31d4a..00000000 --- a/commands/client-no-touch.md +++ /dev/null @@ -1,9 +0,0 @@ -The `CLIENT NO-TOUCH` command controls whether commands sent by the client will alter the LRU/LFU of the keys they access. - -When turned on, the current client will not change LFU/LRU stats, unless it sends the [`TOUCH`](touch.md) command. - -When turned off, the client touches LFU/LRU stats just as a normal client. - -## Reply - -`OK`. diff --git a/commands/client-pause.md b/commands/client-pause.md deleted file mode 100644 index 3c564b3a..00000000 --- a/commands/client-pause.md +++ /dev/null @@ -1,38 +0,0 @@ -`CLIENT PAUSE` is a connections control command able to suspend all the Valkey clients for the specified amount of time (in milliseconds). - -The command performs the following actions: - -* It stops processing all the pending commands from normal and pub/sub clients for the given mode. Replica connections are not paused, but in both modes no writes are propagated to replicas while clients are paused. Note that clients are formally paused when they try to execute a command, so no work is taken on the server side for inactive clients. -* However it returns OK to the caller ASAP, so the `CLIENT PAUSE` command execution is not paused by itself. -* When the specified amount of time has elapsed, all the clients are unblocked: this will trigger the processing of all the commands accumulated in the query buffer of every client during the pause. - -Client pause currently supports two modes: - -* `ALL`: This is the default mode. All client commands are blocked. -* `WRITE`: Clients are only blocked if they attempt to execute a write command. - -For the `WRITE` mode, some commands have special behavior: - -* `EVAL`/`EVALSHA`: Will block client for all scripts. -* `PUBLISH`: Will block client. -* `PFCOUNT`: Will block client. -* `WAIT`/`WAITAOF`: Acknowledgments will be delayed, so these commands will appear blocked. - -This command is useful as it makes able to switch clients from a Valkey instance to another one in a controlled way. For example during an instance upgrade the system administrator could do the following: - -* Pause the clients using `CLIENT PAUSE` -* Wait a few seconds to make sure the replicas processed the latest replication stream from the primary. -* Turn one of the replicas into a primary. -* Reconfigure clients to connect with the new primary. - -The recommended mode for client pause is `WRITE`. This mode only blocks clients that attempt to write, can be -aborted with the [`CLIENT UNPAUSE`](client-unpause.md) command, and allows reconfiguring the old primary without risking accepting writes after the -failover. This is also the mode used during cluster failover. - -This command also prevents keys to be evicted or expired during the time clients are paused. -This way the dataset is guaranteed to be static not just from the point of view of clients not being able to write, -but also from the point of view of internal operations. - -## Reply - -`OK` or an error if the timeout is invalid. diff --git a/commands/client-reply.md b/commands/client-reply.md deleted file mode 100644 index 2de23503..00000000 --- a/commands/client-reply.md +++ /dev/null @@ -1,14 +0,0 @@ -Sometimes it can be useful for clients to completely disable replies from the Valkey server. For example when the client sends fire and forget commands or performs a mass loading of data, or in caching contexts where new data is streamed constantly. In such contexts to use server time and bandwidth in order to send back replies to clients, which are going to be ignored, is considered wasteful. - -The `CLIENT REPLY` command controls whether the server will reply the client's commands. The following modes are available: - -* `ON`. This is the default mode in which the server returns a reply to every command. -* `OFF`. In this mode the server will not reply to client commands. -* `SKIP`. This mode skips the reply of command immediately after it. - -**Note:** -Starting with Valkey 9.0, the `CLIENT REPLY` command is disallowed inside a transaction `(MULTI/EXEC)`. In earlier versions, using `CLIENT REPLY` within a transaction could corrupt the reply stream. Attempting to use it within a transaction now results in an error reply. - -## Reply - -`OK` when called with `ON`. When called with either `OFF` or `SKIP` sub-commands, no reply is made. diff --git a/commands/client-setinfo.md b/commands/client-setinfo.md deleted file mode 100644 index f201635b..00000000 --- a/commands/client-setinfo.md +++ /dev/null @@ -1,16 +0,0 @@ -The `CLIENT SETINFO` command assigns various info attributes to the current connection which are displayed in the output of [`CLIENT LIST`](client-list.md) and [`CLIENT INFO`](client-info.md). - -Client libraries are expected to pipeline this command after authentication on all connections -and ignore failures since they could be connected to an older version that doesn't support them. - -Currently the supported attributes are: -* `lib-name` - meant to hold the name of the client library that's in use. -* `lib-ver` - meant to hold the client library's version. - -There is no limit to the length of these attributes. However it is not possible to use spaces, newlines, or other non-printable characters that would violate the format of the `CLIENT LIST` reply. - -Note that these attributes are **not** cleared by the [`RESET`](reset.md) command. - -## Reply - -`OK` if the attribute name was successfully set. diff --git a/commands/client-setname.md b/commands/client-setname.md deleted file mode 100644 index eb38fffb..00000000 --- a/commands/client-setname.md +++ /dev/null @@ -1,19 +0,0 @@ -The `CLIENT SETNAME` command assigns a name to the current connection. - -The assigned name is displayed in the output of [`CLIENT LIST`](client-list.md) so that it is possible to identify the client that performed a given connection. - -For instance when Valkey is used in order to implement a queue, producers and consumers of messages may want to set the name of the connection according to their role. - -There is no limit to the length of the name that can be assigned if not the usual limits of the String type (512 MB). However it is not possible to use spaces in the connection name as this would violate the format of the `CLIENT LIST` reply. - -It is possible to entirely remove the connection name setting it to the empty string, that is not a valid connection name since it serves to this specific purpose. - -The connection name can be inspected using [`CLIENT GETNAME`](client-getname.md). - -Every new connection starts without an assigned name. - -Tip: setting names to connections is a good way to debug connection leaks due to bugs in the application using Valkey. - -## Reply - -`OK` if the connection name was successfully set. diff --git a/commands/client-tracking.md b/commands/client-tracking.md deleted file mode 100644 index db8c797a..00000000 --- a/commands/client-tracking.md +++ /dev/null @@ -1,33 +0,0 @@ -This command enables the tracking feature of the Valkey server, that is used -for [server assisted client side caching](../topics/client-side-caching.md). - -When tracking is enabled Valkey remembers the keys that the connection -requested, in order to send later invalidation messages when such keys are -modified. Invalidation messages are sent in the same connection (only available -when the RESP3 protocol is used) or redirected in a different connection -(available also with RESP2 and Pub/Sub). A special *broadcasting* mode is -available where clients participating in this protocol receive every -notification just subscribing to given key prefixes, regardless of the -keys that they requested. Given the complexity of the argument please -refer to [the main client side caching documentation](../topics/client-side-caching.md) for the details. This manual page is only a reference for the options of this subcommand. - -In order to enable tracking, use: - - CLIENT TRACKING on ... options ... - -The feature will remain active in the current connection for all its life, -unless tracking is turned off with `CLIENT TRACKING off` at some point. - -The following are the list of options that modify the behavior of the -command when enabling tracking: - -* `REDIRECT `: send invalidation messages to the connection with the specified ID. The connection must exist. You can get the ID of a connection using [`CLIENT ID`](client-id.md). If the connection we are redirecting to is terminated, when in RESP3 mode the connection with tracking enabled will receive `tracking-redir-broken` push messages in order to signal the condition. -* `BCAST`: enable tracking in broadcasting mode. In this mode invalidation messages are reported for all the prefixes specified, regardless of the keys requested by the connection. Instead when the broadcasting mode is not enabled, Valkey will track which keys are fetched using read-only commands, and will report invalidation messages only for such keys. -* `PREFIX `: for broadcasting, register a given key prefix, so that notifications will be provided only for keys starting with this string. This option can be given multiple times to register multiple prefixes. If broadcasting is enabled without this option, Valkey will send notifications for every key. You can't delete a single prefix, but you can delete all prefixes by disabling and re-enabling tracking. Using this option adds the additional time complexity of O(N^2), where N is the total number of prefixes tracked. -* `OPTIN`: when broadcasting is NOT active, normally don't track keys in read only commands, unless they are called immediately after a [`CLIENT CACHING yes`](client-caching.md) command. -* `OPTOUT`: when broadcasting is NOT active, normally track keys in read only commands, unless they are called immediately after a `CLIENT CACHING no` command. -* `NOLOOP`: don't send notifications about keys modified by this connection itself. - -## Reply - -`OK` if the connection was successfully put in tracking mode or if the tracking mode was successfully disabled. Otherwise, an error is returned. diff --git a/commands/client-trackinginfo.md b/commands/client-trackinginfo.md deleted file mode 100644 index 2655f123..00000000 --- a/commands/client-trackinginfo.md +++ /dev/null @@ -1,20 +0,0 @@ -The command returns information about the current client connection's use of the [server assisted client side caching](../topics/client-side-caching.md) feature. - -Here's the list of tracking information sections and their respective values: - -* **flags**: A list of tracking flags used by the connection. The flags and their meanings are as follows: - * `off`: The connection isn't using server assisted client side caching. - * `on`: Server assisted client side caching is enabled for the connection. - * `bcast`: The client uses broadcasting mode. - * `optin`: The client does not cache keys by default. - * `optout`: The client caches keys by default. - * `caching-yes`: The next command will cache keys (exists only together with `optin`). - * `caching-no`: The next command won't cache keys (exists only together with `optout`). - * `noloop`: The client isn't notified about keys modified by itself. - * `broken_redirect`: The client ID used for redirection isn't valid anymore. -* **redirect**: The client ID used for notifications redirection, or -1 when none. -* **prefixes**: A list of key prefixes for which notifications are sent to the client. - -## Reply - -Map of tracking information sections and their respective values. diff --git a/commands/client-unblock.md b/commands/client-unblock.md deleted file mode 100644 index 4dff4920..00000000 --- a/commands/client-unblock.md +++ /dev/null @@ -1,58 +0,0 @@ -This command can unblock, from a different connection, a client blocked in a blocking operation, such as for instance [`BRPOP`](brpop.md) or [`XREAD`](xread.md) or [`WAIT`](wait.md). - -By default the client is unblocked as if the timeout of the command was -reached, however if an additional (and optional) argument is passed, it is possible to specify the unblocking behavior, that can be **TIMEOUT** (the default) or **ERROR**. If **ERROR** is specified, the behavior is to unblock the client returning as error the fact that the client was force-unblocked. Specifically the client will receive the following error: - - -UNBLOCKED client unblocked via CLIENT UNBLOCK - -Note: of course as usually it is not guaranteed that the error text remains -the same, however the error code will remain `-UNBLOCKED`. - -This command is useful especially when we are monitoring many keys with -a limited number of connections. For instance we may want to monitor multiple -streams with `XREAD` without using more than N connections. However at some -point the consumer process is informed that there is one more stream key -to monitor. In order to avoid using more connections, the best behavior would -be to stop the blocking command from one of the connections in the pool, add -the new key, and issue the blocking command again. - -To obtain this behavior the following pattern is used. The process uses -an additional *control connection* in order to send the `CLIENT UNBLOCK` command -if needed. In the meantime, before running the blocking operation on the other -connections, the process runs [`CLIENT ID`](client-id.md) in order to get the ID associated -with that connection. When a new key should be added, or when a key should -no longer be monitored, the relevant connection blocking command is aborted -by sending `CLIENT UNBLOCK` in the control connection. The blocking command -will return and can be finally reissued. - -This example shows the application in the context of streams, however -the pattern is a general one and can be applied to other cases. - -## Reply - -One of the following: - -* Integer: `0` if the client was unblocked successfully. -* Integer: `1` if the client wasn't unblocked. - -## Examples - -``` -Connection A (blocking connection): -> CLIENT ID -2934 -> BRPOP key1 key2 key3 0 -(client is blocked) - -... Now we want to add a new key ... - -Connection B (control connection): -> CLIENT UNBLOCK 2934 -1 - -Connection A (blocking connection): -... BRPOP reply with timeout ... -NULL -> BRPOP key1 key2 key3 key4 0 -(client is blocked again) -``` diff --git a/commands/client-unpause.md b/commands/client-unpause.md deleted file mode 100644 index 5ed199d0..00000000 --- a/commands/client-unpause.md +++ /dev/null @@ -1,5 +0,0 @@ -`CLIENT UNPAUSE` is used to resume command processing for all clients that were paused by [`CLIENT PAUSE`](client-pause.md). - -## Reply - -`OK`. diff --git a/commands/client.md b/commands/client.md deleted file mode 100644 index 657fbd30..00000000 --- a/commands/client.md +++ /dev/null @@ -1,3 +0,0 @@ -This is a container command for client connection commands. - -To see the list of available commands you can call [`CLIENT HELP`](client-help.md). diff --git a/commands/cluster-addslots.md b/commands/cluster-addslots.md deleted file mode 100644 index c2ba3858..00000000 --- a/commands/cluster-addslots.md +++ /dev/null @@ -1,51 +0,0 @@ -This command is useful in order to modify a node's view of the cluster -configuration. Specifically it assigns a set of hash slots to the node -receiving the command. If the command is successful, the node will map -the specified hash slots to itself, and will start broadcasting the new -configuration. - -However note that: - -1. The command only works if all the specified slots are, from the point of view of the node receiving the command, currently not assigned. A node will refuse to take ownership for slots that already belong to some other node (including itself). -2. The command fails if the same slot is specified multiple times. -3. As a side effect of the command execution, if a slot among the ones specified as argument is set as `importing`, this state gets cleared once the node assigns the (previously unbound) slot to itself. - -## Reply - -`OK` if the command was successful. Otherwise an error is returned. - -## Example - -For example the following command assigns slots 1 2 3 to the node receiving -the command: - - > CLUSTER ADDSLOTS 1 2 3 - OK - -However trying to execute it again results into an error since the slots -are already assigned: - - > CLUSTER ADDSLOTS 1 2 3 - ERR Slot 1 is already busy - -## Usage in Valkey Cluster - -This command only works in cluster mode and is useful in the following -Valkey Cluster operations: - -1. To create a new `cluster ADDSLOTS` is used in order to initially setup primary nodes splitting the available hash slots among them. -2. In order to fix a broken cluster where certain slots are unassigned. - -## Information about slots propagation and warnings - -Note that once a node assigns a set of slots to itself, it will start -propagating this information in heartbeat packet headers. However the -other nodes will accept the information only if they have the slot as -not already bound with another node, or if the configuration epoch of the -node advertising the new hash slot, is greater than the node currently listed -in the table. - -This means that this command should be used with care only by applications -orchestrating Valkey Cluster, like `valkey-cli`, and the command if used -out of the right context can leave the cluster in a wrong state or cause -data loss. diff --git a/commands/cluster-addslotsrange.md b/commands/cluster-addslotsrange.md deleted file mode 100644 index c0af74ae..00000000 --- a/commands/cluster-addslotsrange.md +++ /dev/null @@ -1,27 +0,0 @@ -The `CLUSTER ADDSLOTSRANGE` is similar to the [`CLUSTER ADDSLOTS`](cluster-addslots.md) command in that they both assign hash slots to nodes. - -The difference between the two commands is that `CLUSTER ADDSLOTS` takes a list of slots to assign to the node, while `CLUSTER ADDSLOTSRANGE` takes a list of slot ranges (specified by start and end slots) to assign to the node. - -## Reply - -`OK` if the command was successful. Otherwise an error is returned. - -## Example - -To assign slots 1 2 3 4 5 to the node, the `CLUSTER ADDSLOTS` command is: - - > CLUSTER ADDSLOTS 1 2 3 4 5 - OK - -The same operation can be completed with the following `CLUSTER ADDSLOTSRANGE` command: - - > CLUSTER ADDSLOTSRANGE 1 5 - OK - - -## Usage in Valkey Cluster - -This command only works in cluster mode and is useful in the following Valkey Cluster operations: - -1. To create a new cluster, `CLUSTER ADDSLOTSRANGE` is used to initially set up primary nodes splitting the available hash slots among them. -2. In order to fix a broken cluster where certain slots are unassigned. diff --git a/commands/cluster-bumpepoch.md b/commands/cluster-bumpepoch.md deleted file mode 100644 index e432a266..00000000 --- a/commands/cluster-bumpepoch.md +++ /dev/null @@ -1,12 +0,0 @@ -Advances the cluster config epoch. - -The `CLUSTER BUMPEPOCH` command triggers an increment to the cluster's config epoch from the connected node. The epoch will be incremented if the node's config epoch is zero, or if it is less than the cluster's greatest epoch. - -**Note:** config epoch management is performed internally by the cluster, and relies on obtaining a consensus of nodes. The `CLUSTER BUMPEPOCH` attempts to increment the config epoch **WITHOUT** getting the consensus, so using it may violate the "last failover wins" rule. Use it with caution. - -## Reply - -One of the following: - -* `BUMPED ` if the epoch was incremented. -* `STILL ` if the node already has the greatest configured epoch in the cluster. diff --git a/commands/cluster-cancelslotmigrations.md b/commands/cluster-cancelslotmigrations.md deleted file mode 100644 index 6058e48c..00000000 --- a/commands/cluster-cancelslotmigrations.md +++ /dev/null @@ -1,11 +0,0 @@ -`CLUSTER CANCELSLOTMIGRATIONS` cancels all in progress -[atomic slot migrations](../topics/atomic-slot-migration.md) initiated through -[`CLUSTER MIGRATESLOTS`](cluster-migrateslots.md). - -Only slot migrations initiated on this node are cancelled. If this node is the -target of a slot migration, the cancellation must be performed on the source -node. - -Because the migrations being cancelled may touch keys in any database, the -caller must have ACL access to all databases (the `alldbs` rule). See -[database permissions](../topics/acl.md#database-permissions). diff --git a/commands/cluster-count-failure-reports.md b/commands/cluster-count-failure-reports.md deleted file mode 100644 index 6ade460e..00000000 --- a/commands/cluster-count-failure-reports.md +++ /dev/null @@ -1,22 +0,0 @@ -The command returns the number of *failure reports* for the specified node. -Failure reports are the way Valkey Cluster uses in order to promote a -`PFAIL` state, that means a node is not reachable, to a `FAIL` state, -that means that the majority of primaries in the cluster agreed within -a window of time that the node is not reachable. - -A few more details: - -* A node flags another node with `PFAIL` when the node is not reachable for a time greater than the configured *node timeout*, which is a fundamental configuration parameter of a Valkey Cluster. -* Nodes in `PFAIL` state are provided in gossip sections of heartbeat packets. -* Every time a node processes gossip packets from other nodes, it creates (and refreshes the TTL if needed) **failure reports**, remembering that a given node said another given node is in `PFAIL` condition. However, once a node has been marked `FAIL`, additional failure reports are ignored. -* Each failure report has a time to live of two times the *node timeout* time. -* If at a given time a node has another node flagged with `PFAIL`, and at the same time collected the majority of other primary nodes *failure reports* about this node (including itself if it is a primary), then it elevates the failure state of the node from `PFAIL` to `FAIL`, and broadcasts a message forcing all the nodes that can be reached to flag the node as `FAIL`. - -This command returns the number of failure reports for the current node which are currently not expired (so received within two times the *node timeout* time). The count does not include what the node we are asking this count believes about the node ID we pass as argument, the count *only* includes the failure reports the node received from other nodes. - -This command is mainly useful for debugging, when the failure detector of -Valkey Cluster is not operating as we believe it should. - -## Reply - -Integer: the number of active failure reports for the node. diff --git a/commands/cluster-countkeysinslot.md b/commands/cluster-countkeysinslot.md deleted file mode 100644 index 7c85e96c..00000000 --- a/commands/cluster-countkeysinslot.md +++ /dev/null @@ -1,14 +0,0 @@ -Returns the number of keys in the specified Valkey Cluster hash slot in the -currently selected database. The command only queries the local data set, -so contacting a node that is not serving the specified hash slot will always -result in a count of zero being returned. - - -``` -> CLUSTER COUNTKEYSINSLOT 7000 -(integer) 50341 -``` - -## Reply - -Integer: The number of keys in the specified hash slot, or an error if the hash slot is invalid. diff --git a/commands/cluster-delslots.md b/commands/cluster-delslots.md deleted file mode 100644 index 18e9c6ec..00000000 --- a/commands/cluster-delslots.md +++ /dev/null @@ -1,47 +0,0 @@ -In Valkey Cluster, each node keeps track of which primary is serving -a particular hash slot. - -The `CLUSTER DELSLOTS` command asks a particular Valkey Cluster node to -forget which primary is serving the hash slots specified as arguments. - -In the context of a node that has received a `CLUSTER DELSLOTS` command and -has consequently removed the associations for the passed hash slots, -we say those hash slots are *unbound*. Note that the existence of -unbound hash slots occurs naturally when a node has not been -configured to handle them (something that can be done with the -[`CLUSTER ADDSLOTS`](cluster-addslots.md) command) and if it has not received any information about -who owns those hash slots (something that it can learn from heartbeat -or update messages). - -If a node with unbound hash slots receives a heartbeat packet from -another node that claims to be the owner of some of those hash -slots, the association is established instantly. Moreover, if a -heartbeat or update message is received with a configuration epoch -greater than the node's own, the association is re-established. - -However, note that: - -1. The command only works if all the specified slots are already -associated with some node. -2. The command fails if the same slot is specified multiple times. -3. As a side effect of the command execution, the node may go into -*down* state because not all hash slots are covered. - -## Reply - -`OK` if the command was successful. Otherwise an error is returned. - -## Example - -The following command removes the association for slots 5000 and -5001 from the node receiving the command: - - > CLUSTER DELSLOTS 5000 5001 - OK - -## Usage in Valkey Cluster - -This command only works in cluster mode and may be useful for -debugging and in order to manually orchestrate a cluster configuration -when a new cluster is created. It is currently not used by `valkey-cli`, -and mainly exists for API completeness. diff --git a/commands/cluster-delslotsrange.md b/commands/cluster-delslotsrange.md deleted file mode 100644 index 948cb53d..00000000 --- a/commands/cluster-delslotsrange.md +++ /dev/null @@ -1,31 +0,0 @@ -The `CLUSTER DELSLOTSRANGE` command is similar to the [`CLUSTER DELSLOTS`](cluster-delslots.md) command in that they both remove hash slots from the node. -The difference is that `CLUSTER DELSLOTS` takes a list of hash slots to remove from the node, while `CLUSTER DELSLOTSRANGE` takes a list of slot ranges (specified by start and end slots) to remove from the node. - -## Reply - -`OK` if the command was successful. Otherwise an error is returned. - -## Example - -To remove slots 1 2 3 4 5 from the node, the `CLUSTER DELSLOTS` command is: - - > CLUSTER DELSLOTS 1 2 3 4 5 - OK - -The same operation can be completed with the following `CLUSTER DELSLOTSRANGE` command: - - > CLUSTER DELSLOTSRANGE 1 5 - OK - -However, note that: - -1. The command only works if all the specified slots are already associated with the node. -2. The command fails if the same slot is specified multiple times. -3. As a side effect of the command execution, the node may go into *down* state because not all hash slots are covered. - -## Usage in Valkey Cluster - -This command only works in cluster mode and may be useful for -debugging and in order to manually orchestrate a cluster configuration -when a new cluster is created. It is currently not used by `valkey-cli`, -and mainly exists for API completeness. diff --git a/commands/cluster-failover.md b/commands/cluster-failover.md deleted file mode 100644 index a19a755a..00000000 --- a/commands/cluster-failover.md +++ /dev/null @@ -1,74 +0,0 @@ -This command, that can only be sent to a Valkey Cluster replica node, forces -the replica to start a manual failover of its primary instance. -For non-clustered Valkey, see [`FAILOVER`](failover.md). - -A manual failover is a special kind of failover that is usually executed when -there are no actual failures, but we wish to swap the current primary with one -of its replicas (which is the node we send the command to), in a safe way, -without any window for data loss. It works in the following way: - -1. The replica tells the primary to stop processing queries from clients. -2. The primary replies to the replica with the current *replication offset*. -3. The replica waits for the replication offset to match on its side, to make sure it processed all the data from the primary before it continues. -4. The replica starts a failover, obtains a new configuration epoch from the majority of the primaries, and broadcasts the new configuration. -5. The old primary receives the configuration update: unblocks its clients and starts replying with redirection messages so that they'll continue the chat with the new primary. - -This way clients are moved away from the old primary to the new primary -atomically and only when the replica that is turning into the new primary -has processed all of the replication stream from the old primary. - -There is a built-in timeout for the primary to resume processing queries if the -replica does not catch quickly enough or is unable to secure the votes to take over. -The default failover timeout is 5000ms. It is possible to configure the timeout -via the `cluster-manual-failover-timeout` configuration parameter (added in Valkey 8.1) -and decide how long the primary will pause in the worst case scenario. - -## FORCE option: manual failover when the primary is down - -The command behavior can be modified by two options: **FORCE** and **TAKEOVER**. - -If the **FORCE** option is given, the replica does not perform any handshake -with the primary, that may be not reachable, but instead just starts a -failover ASAP starting from point 4. This is useful when we want to start -a manual failover while the primary is no longer reachable. - -However using **FORCE** we still need the majority of primaries to be available -in order to authorize the failover and generate a new configuration epoch -for the replica that is going to become primary. - -## TAKEOVER option: manual failover without cluster consensus - -There are situations where this is not enough, and we want a replica to failover -without any agreement with the rest of the cluster. A real world use case -for this is to mass promote replicas in a different data center to primaries -in order to perform a data center switch, while all the primaries are down -or partitioned away. - -The **TAKEOVER** option implies everything **FORCE** implies, but also does -not uses any cluster authorization in order to failover. A replica receiving -`CLUSTER FAILOVER TAKEOVER` will instead: - -1. Generate a new `configEpoch` unilaterally, just taking the current greatest epoch available and incrementing it if its local configuration epoch is not already the greatest. -2. Assign itself all the hash slots of its primary, and propagate the new configuration to every node which is reachable ASAP, and eventually to every other node. - -Note that **TAKEOVER violates the last-failover-wins principle** of Valkey Cluster, since the configuration epoch generated by the replica violates the normal generation of configuration epochs in several ways: - -1. There is no guarantee that it is actually the higher configuration epoch, since, for example, we can use the **TAKEOVER** option within a minority, nor any message exchange is performed to generate the new configuration epoch. -2. If we generate a configuration epoch which happens to collide with another instance, eventually our configuration epoch, or the one of another instance with our same epoch, will be moved away using the *configuration epoch collision resolution algorithm*. - -Because of this the **TAKEOVER** option should be used with care. - -## Implementation details and notes - -* `CLUSTER FAILOVER`, unless the **TAKEOVER** option is specified, does not execute a failover synchronously. - It only *schedules* a manual failover, bypassing the failure detection stage. -* An `OK` reply is no guarantee that the failover will succeed. -* A replica can only be promoted to a primary if it is known as a replica by a majority of the primaries in the cluster. - If the replica is a new node that has just been added to the cluster (for example after upgrading it), it may not yet be known to all the primaries in the cluster. - To check that the primaries are aware of a new replica, you can send [`CLUSTER NODES`](cluster-nodes.md) or [`CLUSTER REPLICAS`](cluster-replicas.md) to each of the primary nodes and check that it appears as a replica, before sending `CLUSTER FAILOVER` to the replica. -* To check that the failover has actually happened you can use [`ROLE`](role.md), [`INFO REPLICATION`](info.md) (which indicates "role:master" after successful failover), or `CLUSTER NODES` to verify that the state of the cluster has changed sometime after the command was sent. -* To check if the failover has failed, check the replica's log for "Manual failover timed out", which is logged if the replica has given up after a few seconds. - -## Reply - -`OK` if the command was accepted and a manual failover is going to be attempted. An error if the operation cannot be executed, for example if the client is connected to a node that is already a primary. diff --git a/commands/cluster-flushslots.md b/commands/cluster-flushslots.md deleted file mode 100644 index 8da8ec61..00000000 --- a/commands/cluster-flushslots.md +++ /dev/null @@ -1,7 +0,0 @@ -Deletes all slots from a node. - -The `CLUSTER FLUSHSLOTS` deletes all information about slots from the connected node. It can only be called when the database is empty. - -## Reply - -`OK`. diff --git a/commands/cluster-forget.md b/commands/cluster-forget.md deleted file mode 100644 index 64f9fe12..00000000 --- a/commands/cluster-forget.md +++ /dev/null @@ -1,57 +0,0 @@ -The command is used in order to remove a node, specified via its node ID, -from the set of *known nodes* of the Valkey Cluster node receiving the command. -In other words the specified node is removed from the *nodes table* of the -node receiving the command. - -Because when a given node is part of the cluster, all the other nodes -participating in the cluster knows about it, in order for a node to be -completely removed from a cluster, the `CLUSTER FORGET` command must be -sent to all the remaining nodes, regardless of the fact they are primaries -or replicas. - -However the command cannot simply drop the node from the internal node -table of the node receiving the command, it also implements a ban-list, not -allowing the same node to be added again as a side effect of processing the -*gossip section* of the heartbeat packets received from other nodes. - -## Details on why the ban-list is needed - -In the following example we'll show why the command must not just remove -a given node from the nodes table, but also prevent it for being re-inserted -again for some time. - -Let's assume we have four nodes, A, B, C and D. In order to -end with just a three nodes cluster A, B, C we may follow these steps: - -1. Reshard all the hash slots from D to nodes A, B, C. -2. D is now empty, but still listed in the nodes table of A, B and C. -3. We contact A, and send `CLUSTER FORGET D`. -4. B sends node A a heartbeat packet, where node D is listed. -5. A does no longer known node D (see step 3), so it starts a handshake with D. -6. D ends re-added in the nodes table of A. - -As you can see in this way removing a node is fragile, we need to send -`CLUSTER FORGET` commands to all the nodes ASAP hoping there are no -gossip sections processing in the meantime. Because of this problem the -command implements a ban-list with an expire time for each entry. - -So what the command really does is: - -1. The specified node gets removed from the nodes table. -2. The node ID of the removed node gets added to the ban-list, for 1 minute. -3. The node will skip all the node IDs listed in the ban-list when processing gossip sections received in heartbeat packets from other nodes. - -This way we have a 60 second window to inform all the nodes in the cluster that -we want to remove a node. - -## Special conditions not allowing the command execution - -The command does not succeed and returns an error in the following cases: - -1. The specified node ID is not found in the nodes table. -2. The node receiving the command is a replica, and the specified node ID identifies its current primary. -3. The node ID identifies the same node we are sending the command to. - -## Reply - -`OK` if the command was executed successfully. Otherwise an error is returned. diff --git a/commands/cluster-getkeysinslot.md b/commands/cluster-getkeysinslot.md deleted file mode 100644 index 863f82ea..00000000 --- a/commands/cluster-getkeysinslot.md +++ /dev/null @@ -1,22 +0,0 @@ -The command returns an array of key names stored in the contacted node and -hashing to the specified hash slot in the currently selected database. -The maximum number of keys to return is specified via the `count` argument, -so that it is possible for the user of this API to batch-process keys. -Note that this works only when deleting keys, as the same `count` keys are -returned on each call unless removed. - -The main usage of this command is during rehashing of cluster slots from one -node to another. The way the rehashing is performed is exposed in the [Valkey -Cluster specification](../topics/cluster-spec.md), or in a more simple to digest form, as an appendix -of the [`CLUSTER SETSLOT`](cluster-setslot.md) command documentation. - -``` -> CLUSTER GETKEYSINSLOT 7000 3 -1) "key_39015" -2) "key_89793" -3) "key_92937" -``` - -## Reply - -Array with up to count elements. diff --git a/commands/cluster-getslotmigrations.md b/commands/cluster-getslotmigrations.md deleted file mode 100644 index ba067d6b..00000000 --- a/commands/cluster-getslotmigrations.md +++ /dev/null @@ -1,99 +0,0 @@ -`CLUSTER GETSLOTMIGRATIONS` returns an array of information about in-progress -and recently completed -[atomic slot migrations](../topics/atomic-slot-migration.md). - -Each job previously started by [`CLUSTER MIGRATESLOTS`](cluster-migrateslots.md) -creates a single entry. The number of visible slot migration entries depends on -the configured `cluster-slot-migration-log-max-len`. After the limit is reached, -the oldest inactive entry is removed. Note that active slot migrations will -always be visible through `CLUSTER GETSLOTMIGRATIONS`, even if there are more -entries than the configured limit. - -Information about the slot migration operations is stored in-memory and is not -persisted across restarts. Slot migration entries are visible on the primary -node of both the target and source shard and the replica nodes of the target -shard. - -The following information is reported for each slot migration entry: - -- `name`: A unique 40 byte name for the slot migration -- `operation`: The operation performed by the slot migration job on this node - (either `EXPORT` or `IMPORT`) -- `slot_ranges`: The range(s) of slots being migrated, with both start and end - inclusive. The start and end slot are separated by `-` in each range, and - multiple ranges are joined together with a space ("` `"). -- `target_node`: The primary node receiving the slot ownership as part of the - migration. This information is only supplied on the primary node of the - participating shards. -- `source_node`: The primary node sending the slot ownership as part of the - migration. This information is only supplied on the primary node of the - participating shards. -- `create_time`: The Unix timestamp (in seconds) when the slot - migration was started. -- `last_update_time`: The Unix timestamp (in seconds) when the slot - migration's status was last changed. -- `last_ack_time`: The Unix timestamp (in seconds) when the slot - migration last received a heartbeat. -- `state`: The current state of the slot migration. The terminal states are - `success` if completed successfully, `failed` if some unexpected failure - occurred, and `cancelled` if a `CLUSTER CANCELSLOTMIGRATIONS` request was - received during the migration. Any other state denotes an active slot - migration. -- `message`: Either a human readable status message, if there is more - information to display about the state, or empty string if no message is - available. -- `cow_size`: The copy-on-write overhead accumulated while the migration was - in progress, in bytes. -- `remaining_repl_size`: The number of bytes remaining in the source node's - output buffer that are pending to be sent to the target node during slot - migration. Added in Valkey 9.1. - -## Examples - -### Response in RESP 2 - -``` -127.0.0.1:30001> CLUSTER GETSLOTMIGRATIONS -1) 1) "name" - 2) "5371b28997de6fd0bbe813ad8ebdfdf2faadb308" - 3) "operation" - 4) "EXPORT" - 5) "slot_ranges" - 6) "0-10" - 7) "target_node" - 8) "4b4f12fdfb58d5e30fef7b9ad3f1651dacbbaba9" - 9) "source_node" - 10) "93941e777e17fcbc92d4398cc957ffea888f472b" - 11) "create_time" - 12) (integer) 1754870400 - 13) "last_update_time" - 14) (integer) 1754870400 - 15) "last_ack_time" - 16) (integer) 1754870400 - 17) "state" - 18) "success" - 19) "message" - 20) "" - 21) "cow_size" - 22) (integer) 0 - 23) "remaining_repl_size" - 24) (integer) 0 -``` - -### Response in RESP 3 - -``` -127.0.0.1:30001> CLUSTER GETSLOTMIGRATIONS -1) 1# "name" => "5371b28997de6fd0bbe813ad8ebdfdf2faadb308" - 2# "operation" => "EXPORT" - 3# "slot_ranges" => "0-10" - 4# "target_node" => "4b4f12fdfb58d5e30fef7b9ad3f1651dacbbaba9" - 5# "source_node" => "93941e777e17fcbc92d4398cc957ffea888f472b" - 6# "create_time" => (integer) 1754870400 - 7# "last_update_time" => (integer) 1754870400 - 8# "last_ack_time" => (integer) 1754870400 - 9# "state" => "success" - 10# "message" => "" - 11# "cow_size" => (integer) 0 - 12# "remaining_repl_size" => (integer) 0 -``` diff --git a/commands/cluster-help.md b/commands/cluster-help.md deleted file mode 100644 index 21ee97d7..00000000 --- a/commands/cluster-help.md +++ /dev/null @@ -1,5 +0,0 @@ -The `CLUSTER HELP` command returns a helpful text describing the different subcommands. - -## Reply - -Array of subcommands and their descriptions. diff --git a/commands/cluster-info.md b/commands/cluster-info.md deleted file mode 100644 index 35e3fb10..00000000 --- a/commands/cluster-info.md +++ /dev/null @@ -1,68 +0,0 @@ -`CLUSTER INFO` provides [`INFO`](info.md) style information about Valkey Cluster vital parameters. -The following fields are always present in the reply: - -``` -cluster_state:ok -cluster_slots_assigned:16384 -cluster_slots_ok:16384 -cluster_slots_pfail:0 -cluster_slots_fail:0 -cluster_nodes_pfail:0 -cluster_nodes_fail:0 -cluster_voting_nodes_pfail:0 -cluster_voting_nodes_fail:0 -cluster_known_nodes:6 -cluster_size:3 -cluster_current_epoch:6 -cluster_my_epoch:2 -cluster_stats_messages_sent:1483972 -cluster_stats_messages_received:1483968 -total_cluster_links_buffer_limit_exceeded:0 -cluster_io_threaded_reads_processed:0 -cluster_io_threaded_writes_processed:0 -cluster_io_threaded_accepts_processed:0 -cluster_io_main_thread_fallbacks:0 -``` - -* `cluster_state`: State is `ok` if the node is able to receive queries. `fail` if there is at least one hash slot which is unbound (no node associated), in error state (node serving it is flagged with FAIL flag), or if the majority of primaries can't be reached by this node. -* `cluster_slots_assigned`: Number of slots which are associated to some node (not unbound). This number should be 16384 for the node to work properly, which means that each hash slot should be mapped to a node. -* `cluster_slots_ok`: Number of hash slots mapping to a node not in `FAIL` or `PFAIL` state. -* `cluster_slots_pfail`: Number of hash slots mapping to a node in `PFAIL` state. Note that those hash slots still work correctly, as long as the `PFAIL` state is not promoted to `FAIL` by the failure detection algorithm. `PFAIL` only means that we are currently not able to talk with the node, but may be just a transient error. -* `cluster_slots_fail`: Number of hash slots mapping to a node in `FAIL` state. If this number is not zero the node is not able to serve queries unless `cluster-require-full-coverage` is set to `no` in the configuration. -* `cluster_nodes_pfail`: Number of nodes in `PFAIL` state. A non-zero value indicates one or more nodes have been detected as unreachable but have not yet been confirmed as failed by a quorum of voting nodes. -* `cluster_nodes_fail`: Number of nodes in `FAIL` state. A non-zero value indicates one or more nodes are unreachable and have been marked as failed by a quorum of voting nodes. -* `cluster_voting_nodes_pfail`: Number of voting nodes in `PFAIL` state. A non-zero value indicates one or more primary nodes serving at least one slot are unreachable but not yet confirmed as failed by a quorum of voting nodes. -* `cluster_voting_nodes_fail`: Number of voting nodes in `FAIL` state. A non-zero value indicates one or more primary nodes serving at least one slot have been marked as failed by a quorum of voting nodes. -* `cluster_known_nodes`: The total number of known nodes in the cluster, including nodes in [`HANDSHAKE`](../topics/cluster-spec.md#node-handshake) state that may not currently be proper members of the cluster. -* `cluster_size`: The number of primary nodes serving at least one hash slot in the cluster. -* `cluster_current_epoch`: The local [Current Epoch](../topics/cluster-spec.md#cluster-current-epoch). This is used in order to create unique increasing version numbers during fail overs. -* `cluster_my_epoch`: The [Config Epoch](../topics/cluster-spec.md#configuration-epoch) of the node we are talking with. This is the current configuration version assigned to this node. -* `cluster_stats_messages_sent`: Number of messages sent via the cluster node-to-node binary bus. -* `cluster_stats_messages_received`: Number of messages received via the cluster node-to-node binary bus. -* `total_cluster_links_buffer_limit_exceeded`: Accumulated count of cluster links freed due to exceeding the `cluster-link-sendbuf-limit` configuration. -* `cluster_io_threaded_reads_processed`: Number of cluster bus read operations completed by the I/O threads. Added in Valkey 9.2. -* `cluster_io_threaded_writes_processed`: Number of cluster bus write operations completed by the I/O threads. Added in Valkey 9.2. -* `cluster_io_threaded_accepts_processed`: Number of inbound cluster bus TLS accepts (handshakes) completed by the I/O threads. Added in Valkey 9.2. -* `cluster_io_main_thread_fallbacks`: Number of cluster bus read, write, or inbound TLS accept operations performed on the main thread because they could not be offloaded to the I/O threads, either because no I/O threads were active or because the I/O job queue was full. I/O threads are only activated under load, so on a lightly loaded node most cluster bus I/O is expected to be counted here. Added in Valkey 9.2. - -The following message-related fields may be included in the reply if the value is not 0: -Each message type includes statistics on the number of messages sent and received. -Here are the explanation of these fields: -] -* `cluster_stats_messages_ping_sent` and `cluster_stats_messages_ping_received`: Cluster bus PING (not to be confused with the client command [`PING`](ping.md). -* `cluster_stats_messages_pong_sent` and `cluster_stats_messages_pong_received`: PONG (reply to PING). -* `cluster_stats_messages_meet_sent` and `cluster_stats_messages_meet_received`: Handshake message sent to a new node, either through gossip or [`CLUSTER MEET`](cluster-meet.md). -* `cluster_stats_messages_fail_sent` and `cluster_stats_messages_fail_received`: Mark node xxx as failing. -* `cluster_stats_messages_publish_sent` and `cluster_stats_messages_publish_received`: Pub/Sub Publish propagation, see [Pubsub](../topics/pubsub.md). -* `cluster_stats_messages_auth-req_sent` and `cluster_stats_messages_auth-req_received`: Replica initiated leader election to replace its primary. -* `cluster_stats_messages_auth-ack_sent` and `cluster_stats_messages_auth-ack_received`: Message indicating a vote during leader election. -* `cluster_stats_messages_update_sent` and `cluster_stats_messages_update_received`: Another node slots configuration. -* `cluster_stats_messages_mfstart_sent` and `cluster_stats_messages_mfstart_received`: Pause clients for manual failover. -* `cluster_stats_messages_module_sent` and `cluster_stats_messages_module_received`: Module cluster API message. -* `cluster_stats_messages_publishshard_sent` and `cluster_stats_messages_publishshard_received`: Pub/Sub Publish shard propagation, see [Sharded Pubsub](../topics/pubsub.md#sharded-pub-sub). - -More information about the Current Epoch and Config Epoch variables are available in the [Valkey Cluster specification document](../topics/cluster-spec.md#cluster-current-epoch). - -## Reply - -Verbatim string: A map between named fields and values in the form of `:` lines separated by newlines composed by the two bytes `CRLF`. diff --git a/commands/cluster-keyslot.md b/commands/cluster-keyslot.md deleted file mode 100644 index 8a77b48b..00000000 --- a/commands/cluster-keyslot.md +++ /dev/null @@ -1,24 +0,0 @@ -Returns an integer identifying the hash slot the specified key hashes to. -This command is mainly useful for debugging and testing, since it exposes -via an API the underlying Valkey implementation of the hashing algorithm. -Example use cases for this command: - -1. Client libraries may use Valkey in order to test their own hashing algorithm, generating random keys and hashing them with both their local implementation and using Valkey `CLUSTER KEYSLOT` command, then checking if the result is the same. -2. Humans may use this command in order to check what is the hash slot, and then the associated Valkey Cluster node, responsible for a given key. - -## Reply - -Integer: The hash slot number for the specified key - -## Example - -``` -> CLUSTER KEYSLOT somekey -(integer) 11058 -> CLUSTER KEYSLOT foo{hash_tag} -(integer) 2515 -> CLUSTER KEYSLOT bar{hash_tag} -(integer) 2515 -``` - -Note that the command implements the full hashing algorithm, including support for [hash tags](../topics/cluster-spec.md#hash-tags), that is the special property of Valkey Cluster key hashing algorithm, of hashing just what is between `{` and `}` if such a pattern is found inside the key name, in order to force multiple keys to be handled by the same node. diff --git a/commands/cluster-links.md b/commands/cluster-links.md deleted file mode 100644 index eb66827d..00000000 --- a/commands/cluster-links.md +++ /dev/null @@ -1,48 +0,0 @@ -Each node in a Valkey Cluster maintains a pair of long-lived TCP link with each peer in the cluster: One for sending outbound messages towards the peer and one for receiving inbound messages from the peer. - -`CLUSTER LINKS` outputs information of all such peer links as an array, where each array element is a map that contains attributes and their values for an individual link. - -## Reply - -Array of maps where each map contains various attributes and their values of a cluster link. - -## Examples - -The following is an example output: - -``` -> CLUSTER LINKS -1) 1) "direction" - 2) "to" - 3) "node" - 4) "8149d745fa551e40764fecaf7cab9dbdf6b659ae" - 5) "create-time" - 6) (integer) 1639442739375 - 7) "events" - 8) "rw" - 9) "send-buffer-allocated" - 10) (integer) 4512 - 11) "send-buffer-used" - 12) (integer) 0 -2) 1) "direction" - 2) "from" - 3) "node" - 4) "8149d745fa551e40764fecaf7cab9dbdf6b659ae" - 5) "create-time" - 6) (integer) 1639442739411 - 7) "events" - 8) "r" - 9) "send-buffer-allocated" - 10) (integer) 0 - 11) "send-buffer-used" - 12) (integer) 0 -``` - -Each map is composed of the following attributes of the corresponding cluster link and their values: - -1. `direction`: This link is established by the local node `to` the peer, or accepted by the local node `from` the peer. -2. `node`: The node id of the peer. -3. `create-time`: Creation time of the link. (In the case of a `to` link, this is the time when the TCP link is created by the local node, not the time when it is actually established.) -4. `events`: Events currently registered for the link. `r` means readable event, `w` means writable event. -5. `send-buffer-allocated`: Allocated size of the link's send buffer, which is used to buffer outgoing messages toward the peer. -6. `send-buffer-used`: Size of the portion of the link's send buffer that is currently holding data(messages). diff --git a/commands/cluster-meet.md b/commands/cluster-meet.md deleted file mode 100644 index fd9f5219..00000000 --- a/commands/cluster-meet.md +++ /dev/null @@ -1,42 +0,0 @@ -`CLUSTER MEET` is used in order to connect different Valkey nodes with cluster -support enabled, into a working cluster. - -The basic idea is that nodes by default don't trust each other, and are -considered unknown, so that it is unlikely that different cluster nodes will -mix into a single one because of system administration errors or network -addresses modifications. - -So in order for a given node to accept another one into the list of nodes -composing a Valkey Cluster, there are only two ways: - -1. The system administrator sends a `CLUSTER MEET` command to force a node to meet another one. -2. An already known node sends a list of nodes in the gossip section that we are not aware of. If the receiving node trusts the sending node as a known node, it will process the gossip section and send a handshake to the nodes that are still not known. - -Note that Valkey Cluster needs to form a full mesh (each node is connected with each other node), but in order to create a cluster, there is no need to send all the `CLUSTER MEET` commands needed to form the full mesh. What matter is to send enough `CLUSTER MEET` messages so that each node can reach each other node through a *chain of known nodes*. Thanks to the exchange of gossip information in heartbeat packets, the missing links will be created. - -So, if we link node A with node B via `CLUSTER MEET`, and B with C, A and C will find their ways to handshake and create a link. - -Another example: if we imagine a cluster formed of the following four nodes called A, B, C and D, we may send just the following set of commands to A: - -1. `CLUSTER MEET B-ip B-port` -2. `CLUSTER MEET C-ip C-port` -3. `CLUSTER MEET D-ip D-port` - -As a side effect of `A` knowing and being known by all the other nodes, it will send gossip sections in the heartbeat packets that will allow each other node to create a link with each other one, forming a full mesh in a matter of seconds, even if the cluster is large. - -Moreover `CLUSTER MEET` does not need to be reciprocal. If I send the command to A in order to join B, I don't need to also send it to B in order to join A. - -If the optional `cluster_bus_port` argument is not provided, the default of port + 10000 will be used. - -## Implementation details: MEET and PING packets - -When a given node receives a `CLUSTER MEET` message, the node specified in the -command still does not know the node we sent the command to. So in order for -the node to force the receiver to accept it as a trusted node, it sends a -`MEET` packet instead of a `PING` packet. The two packets have exactly the -same format, but the former forces the receiver to acknowledge the node as -trusted. - -## Reply - -`OK` if the command was successful. If the port or cluster bus port number is out of range, or if an invalid address is specified, an error is returned. diff --git a/commands/cluster-migrateslots.md b/commands/cluster-migrateslots.md deleted file mode 100644 index 65b3b4e3..00000000 --- a/commands/cluster-migrateslots.md +++ /dev/null @@ -1,36 +0,0 @@ -`CLUSTER MIGRATESLOTS` initiates an asynchronous migration of the designated -slot range(s) to the specified target node using -[atomic slot migration](../topics/atomic-slot-migration.md). - -This command allows for many slot ranges in a single migration through repeated -start and end slot pairs within the `SLOTSRANGE` block. It also supports -multiple migrations in one command, through repeated `SLOTSRANGE` and `NODE` -blocks. For example: - -``` -CLUSTER MIGRATESLOTS SLOTSRANGE 0 9 20 29 NODE SLOTSRANGE 10 19 NODE -``` - -Initiates two slot migration jobs, one to `` with 20 slots (0-9 -inclusive, 20-29 inclusive) and another to `` with 10 slots (10-19 -inclusive). - -`OK` is returned if all slot migrations are successfully initiated, otherwise an -error message is returned and no slot migrations are initiated. - -To check on the progress of the slot migration, use the -[`CLUSTER GETSLOTMIGRATIONS`](cluster-getslotmigrations.md) command. - -To cancel the slot migration jobs, use the [`CLUSTER CANCELSLOTMIGRATIONS`](cluster-cancelslotmigrations.md) command. - -Because slot migrations may move keys belonging to any database, the caller -must have ACL access to all databases (the `alldbs` rule). See -[database permissions](../topics/acl.md#database-permissions). - -## Options - -* `AUTH ` -- Authenticate to the preceding `NODE` with the - given username and password pair. Each `NODE` takes its own `AUTH`. - The `username` can be set to `default` when the target uses `requirepass`. - If `AUTH` is omitted, the source node's configured `primaryuser` and - `primaryauth` credentials are used. diff --git a/commands/cluster-myid.md b/commands/cluster-myid.md deleted file mode 100644 index 63f9d2cd..00000000 --- a/commands/cluster-myid.md +++ /dev/null @@ -1,7 +0,0 @@ -Returns the node's id. - -The `CLUSTER MYID` command returns the unique, auto-generated identifier that is associated with the connected cluster node. - -## Reply - -String: the node ID. diff --git a/commands/cluster-myshardid.md b/commands/cluster-myshardid.md deleted file mode 100644 index 5656bac4..00000000 --- a/commands/cluster-myshardid.md +++ /dev/null @@ -1,7 +0,0 @@ -Returns the node's shard id. - -The `CLUSTER MYSHARDID` command returns the unique, auto-generated identifier that is associated with the shard to which the connected cluster node belongs. - -## Reply - -String: the node's shard ID. diff --git a/commands/cluster-nodes.md b/commands/cluster-nodes.md deleted file mode 100644 index de212dda..00000000 --- a/commands/cluster-nodes.md +++ /dev/null @@ -1,115 +0,0 @@ -Each node in a Valkey Cluster has its view of the current cluster configuration, -given by the set of known nodes, the state of the connection we have with such -nodes, their flags, properties and assigned slots, and so forth. - -`CLUSTER NODES` provides all this information, that is, the current cluster -configuration of the node we are contacting, in a serialization format which -happens to be exactly the same as the one used by the Valkey Cluster itself in -order to store on disk the cluster state (however the on disk cluster state -has a few additional info appended at the end). - -Note that normally clients willing to fetch the map between Cluster -hash slots and node addresses should use [`CLUSTER SLOTS`](cluster-slots.md) instead. -`CLUSTER NODES`, that provides more information, should be used for -administrative tasks, debugging, and configuration inspections. -It is also used by `valkey-cli` in order to manage a cluster. - -## Serialization format - -The output of the command is just a space-separated CSV string, where -each line represents a node in the cluster. The following -is an example of output on Valkey 7.2.4. - -``` -07c37dfeb235213a872192d90877d0cd55635b91 127.0.0.1:30004@31004,hostname4 slave e7d1eecce10fd6bb5eb35b9f99a514335d9ba9ca 0 1426238317239 4 connected -67ed2db8d677e59ec4a4cefb06858cf2a1a89fa1 127.0.0.1:30002@31002,hostname2 master - 0 1426238316232 2 connected 5461-10922 -292f8b365bb7edb5e285caf0b7e6ddc7265d2f4f 127.0.0.1:30003@31003,hostname3 master - 0 1426238318243 3 connected 10923-16383 -6ec23923021cf3ffec47632106199cb7f496ce01 127.0.0.1:30005@31005,hostname5 slave 67ed2db8d677e59ec4a4cefb06858cf2a1a89fa1 0 1426238316232 5 connected -824fe116063bc5fcf9f4ffd895bc17aee7731ac3 127.0.0.1:30006@31006,hostname6 slave 292f8b365bb7edb5e285caf0b7e6ddc7265d2f4f 0 1426238317741 6 connected -e7d1eecce10fd6bb5eb35b9f99a514335d9ba9ca 127.0.0.1:30001@31001,hostname1 myself,master - 0 0 1 connected 0-5460 -``` - -Each line is composed of the following fields: - -``` - ... -``` - -The meaning of each field is the following: - -1. `id`: The node ID, a 40-character globally unique string generated when a node is created and never changed again (unless [`CLUSTER RESET HARD`](cluster-reset.md) is used). -2. `ip:port@cport`: The node address that clients should contact to run queries, along with the used cluster bus port. - `:0@0` can be expected when the address is no longer known for this node ID, hence flagged with `noaddr`. - Note that `ip` can be an IPv6 address, which can contain multiple colons. - Here, an IPv6 address is *not* enclosed in square brackets as it would be in other contexts such as URIs. - To properly split the `ip:port@cport` into `ip` and `port@cport`, you need to locate the *last* colon. -3. `hostname`: A human readable string that can be configured via the `cluster-annouce-hostname` setting. The max length of the string is 256 characters, excluding the null terminator. The name can contain ASCII alphanumeric characters, '-', and '.' only. -5. `flags`: A list of comma separated flags: `myself`, `master`, `slave`, `fail?`, `fail`, `handshake`, `noaddr`, `nofailover`, `noflags`. Flags are explained below. -6. `master`: If the node is a replica, and the primary is known, the primary node ID, otherwise the "-" character. -7. `ping-sent`: Unix time at which the currently active ping was sent, or zero if there are no pending pings, in milliseconds. -8. `pong-recv`: Unix time the last pong was received, in milliseconds. -9. `config-epoch`: The configuration epoch (or version) of the current node (or of the current primary if the node is a replica). Each time there is a failover, a new, unique, monotonically increasing configuration epoch is created. If multiple nodes claim to serve the same hash slots, the one with the higher configuration epoch wins. -10. `link-state`: The state of the link used for the node-to-node cluster bus. Use this link to communicate with the node. Can be `connected` or `disconnected`. -11. `slot`: A hash slot number or range. Starting from argument number 9, but there may be up to 16384 entries in total (limit never reached). This is the list of hash slots served by this node. If the entry is just a number, it is parsed as such. If it is a range, it is in the form `start-end`, and means that the node is responsible for all the hash slots from `start` to `end` including the start and end values. - -Flags are: - -* `myself`: The node you are contacting. -* `master`: Node is a primary. -* `slave`: Node is a replica. -* `fail?`: Node is in `PFAIL` state. Not reachable for the node you are contacting, but still logically reachable (not in `FAIL` state). -* `fail`: Node is in `FAIL` state. It was not reachable for multiple nodes that promoted the `PFAIL` state to `FAIL`. -* `handshake`: Untrusted node, we are handshaking. -* `noaddr`: No address known for this node. -* `nofailover`: Replica will not try to failover. -* `noflags`: No flags at all. - -## Reply - -Verbatim string: the serialized cluster configuration. - -## Notes on published config epochs - -Replicas broadcast their primary's config epochs (in order to get an `UPDATE` -message if they are found to be stale), so the real config epoch of the -replica (which is meaningless more or less, since they don't serve hash slots) -can be only obtained checking the node flagged as `myself`, which is the entry -of the node we are asking to generate `CLUSTER NODES` output. The other -replicas epochs reflect what they publish in heartbeat packets, which is, the -configuration epoch of the primaries they are currently replicating. - -## Special slot entries - -Normally hash slots associated to a given node are in one of the following formats, -as already explained above: - -1. Single number: 3894 -2. Range: 3900-4000 - -However node hash slots can be in a special state, used in order to communicate errors after a node restart (mismatch between the keys in the AOF/RDB file, and the node hash slots configuration), or when there is a resharding operation in progress. This two states are **importing** and **migrating**. - -The meaning of the two states is explained in the [Valkey Specification](../topics/cluster-spec.md), however the gist of the two states is the following: - -* **Importing** slots are yet not part of the nodes hash slot, there is a migration in progress. The node will accept queries about these slots only if the `ASK` command is used. -* **Migrating** slots are assigned to the node, but are being migrated to some other node. The node will accept queries if all the keys in the command exist already, otherwise it will emit what is called an **ASK redirection**, to force new keys creation directly in the importing node. - -Importing and migrating slots are emitted in the `CLUSTER NODES` output as follows: - -* **Importing slot:** `[slot_number-<-importing_from_node_id]` -* **Migrating slot:** `[slot_number->-migrating_to_node_id]` - -The following are a few examples of importing and migrating slots: - -* `[93-<-292f8b365bb7edb5e285caf0b7e6ddc7265d2f4f]` -* `[1002-<-67ed2db8d677e59ec4a4cefb06858cf2a1a89fa1]` -* `[77->-e7d1eecce10fd6bb5eb35b9f99a514335d9ba9ca]` -* `[16311->-292f8b365bb7edb5e285caf0b7e6ddc7265d2f4f]` - -Note that the format does not have any space, so `CLUSTER NODES` output format is plain CSV with space as separator even when these special slots are emitted. However a complete parser for the format should be able to handle them. - -Note that: - -1. Migration and importing slots are only added to the node flagged as `myself`. This information is local to a node, for its own slots. -2. Importing and migrating slots are provided as **additional info**. If the node has a given hash slot assigned, it will be also a plain number in the list of hash slots, so clients that don't have a clue about hash slots migrations can just skip these special fields. - -> NOTE: If not for backward compatibility, the Valkey project no longer uses the words "master" and "slave". Unfortunately, in the given commands these words are part of the protocol, so we'll be able to remove such occurrences only when this API is naturally deprecated. diff --git a/commands/cluster-replicas.md b/commands/cluster-replicas.md deleted file mode 100644 index 48faa6f7..00000000 --- a/commands/cluster-replicas.md +++ /dev/null @@ -1,15 +0,0 @@ -The command provides a list of replica nodes replicating from the specified -primary node. The list is provided in the same format used by [`CLUSTER NODES`](cluster-nodes.md) (please refer to its documentation for the specification of the format). - -The command will fail if the specified node is not known or if it is not -a primary according to the node table of the node receiving the command. - -Note that if a replica is added, moved, or removed from a given primary node, -and we ask `CLUSTER REPLICAS` to a node that has not yet received the -configuration update, it may show stale information. However eventually -(in a matter of seconds if there are no network partitions) all the nodes -will agree about the set of nodes associated with a given primary. - -## Reply - -Array of replica nodes replicating from the specified primary node provided in the same format used by `CLUSTER NODES`. diff --git a/commands/cluster-replicate.md b/commands/cluster-replicate.md deleted file mode 100644 index 84c6a0a9..00000000 --- a/commands/cluster-replicate.md +++ /dev/null @@ -1,27 +0,0 @@ -The command reconfigures a node as a replica of the specified primary. -It's the cluster mode counterpart of [`REPLICAOF`](replicaof.md). -If the node receiving the command is an *empty primary*, as a side effect -of the command, the node role is changed from primary to replica. - -Once a node is turned into the replica of another primary node, there is no need -to inform the other cluster nodes about the change: heartbeat packets exchanged -between nodes will propagate the new configuration automatically. - -A replica will always accept the command, assuming that: - -1. The specified node ID exists in its nodes table. -2. The specified node ID does not identify the instance we are sending the command to. -3. The specified node ID is a primary. - -If the node receiving the command is not already a replica, but is a primary, -the command will only succeed, and the node will be converted into a replica, -only if the following additional conditions are met: - -1. The node is not serving any hash slots. -2. The node is empty, no keys are stored at all in the key space. - -If the command succeeds the new replica will immediately try to contact its primary in order to replicate from it. - -## Reply - -`OK` if the command was successful. Otherwise an error is returned. diff --git a/commands/cluster-reset.md b/commands/cluster-reset.md deleted file mode 100644 index 506b20f1..00000000 --- a/commands/cluster-reset.md +++ /dev/null @@ -1,25 +0,0 @@ -Reset a Valkey Cluster node, in a more or less drastic way depending on the -reset type, that can be **hard** or **soft**. Note that this command -**does not work for primaries if they hold one or more keys**, in that case -to completely reset a primary node keys must be removed first, e.g. by using [`FLUSHALL`](flushall.md) first, -and then `CLUSTER RESET`. - -Effects on the node: - -1. All the other nodes in the cluster are forgotten. -2. All the assigned / open slots are reset, so the slots-to-nodes mapping is totally cleared. -3. If the node is a replica it is turned into an (empty) primary. Its dataset is flushed, so at the end the node will be an empty primary. -4. **Hard reset only**: a new Node ID is generated. -5. **Hard reset only**: `currentEpoch` and `configEpoch` vars are set to 0. -6. The new configuration is persisted on disk in the node cluster configuration file. - -This command is mainly useful to re-provision a Valkey Cluster node -in order to be used in the context of a new, different cluster. The command -is also extensively used by the Valkey Cluster testing framework in order to -reset the state of the cluster every time a new test unit is executed. - -If no reset type is specified, the default is **soft**. - -## Reply - -`OK` if the command was successful. Otherwise an error is returned. diff --git a/commands/cluster-saveconfig.md b/commands/cluster-saveconfig.md deleted file mode 100644 index b650a953..00000000 --- a/commands/cluster-saveconfig.md +++ /dev/null @@ -1,15 +0,0 @@ -Forces a node to save the `nodes.conf` configuration on disk. Before returning, -the command calls `fsync(2)` in order to make sure the configuration is -flushed on the computer disk. - -This command is mainly used in the event a `nodes.conf` node state file -gets lost / deleted for some reason, and we want to generate it again from -scratch. It can also be useful in case of mundane alterations of a node cluster -configuration via the `CLUSTER` command in order to ensure the new configuration -is persisted on disk, however all the commands should normally be able to -auto schedule to persist the configuration on disk when it is important -to do so for the correctness of the system in the event of a restart. - -## Reply - -`OK` if the command was successful. Otherwise an error is returned. diff --git a/commands/cluster-set-config-epoch.md b/commands/cluster-set-config-epoch.md deleted file mode 100644 index 57a1f376..00000000 --- a/commands/cluster-set-config-epoch.md +++ /dev/null @@ -1,25 +0,0 @@ -This command sets a specific *config epoch* in a fresh node. It only works when: - -1. The nodes table of the node is empty. -2. The node current *config epoch* is zero. - -These prerequisites are needed since usually, manually altering the -configuration epoch of a node is unsafe, we want to be sure that the node with -the higher configuration epoch value (that is the last that failed over) wins -over other nodes in claiming the hash slots ownership. - -However there is an exception to this rule, and it is when a new -cluster is created from scratch. Valkey Cluster *config epoch collision -resolution* algorithm can deal with new nodes all configured with the -same configuration at startup, but this process is slow and should be -the exception, only to make sure that whatever happens, two more -nodes eventually always move away from the state of having the same -configuration epoch. - -So, using `CLUSTER SET-CONFIG-EPOCH`, when a new cluster is created, we can -assign a different progressive configuration epoch to each node before -joining the cluster together. - -## Reply - -`OK` if the command was successful. Otherwise an error is returned. diff --git a/commands/cluster-setslot.md b/commands/cluster-setslot.md deleted file mode 100644 index b4de16f0..00000000 --- a/commands/cluster-setslot.md +++ /dev/null @@ -1,100 +0,0 @@ -`CLUSTER SETSLOT` is responsible for changing the state of a hash slot in the receiving node in different ways. It is part of the legacy mechanism for cluster resharding. - -**Note:** For live resharding, the newer [atomic slot migration](../topics/atomic-slot-migration.md) mechanism using `CLUSTER MIGRATESLOTS` is recommended as it is faster, more reliable, and has less impact on client applications. - -`CLUSTER SETSLOT` can, depending on the subcommand used: - -1. `MIGRATING` subcommand: Set a hash slot in *migrating* state. -2. `IMPORTING` subcommand: Set a hash slot in *importing* state. -3. `STABLE` subcommand: Clear any importing / migrating state from hash slot. -4. `NODE` subcommand: Bind the hash slot to a different node. - -The command with its set of subcommands is useful in order to start and end cluster live resharding operations, which are accomplished by setting a hash slot in migrating state in the source node, and importing state in the destination node. - -Each subcommand is documented below. At the end you'll find a description of -how live resharding is performed using this command and other related commands. - -## CLUSTER SETSLOT `` MIGRATING `` - -This subcommand sets a slot to *migrating* state. In order to set a slot -in this state, the node receiving the command must be the hash slot owner, -otherwise an error is returned. - -When a slot is set in migrating state, the node changes behavior in the -following way: - -1. If a command is received about an existing key, the command is processed as usually. -2. If a command is received about a key that does not exists, an `ASK` redirection is emitted by the node, asking the client to retry only that specific query into `destination-node`. In this case the client should not update its hash slot to node mapping. -3. If the command contains multiple keys, in case none exist, the behavior is the same as point 2, if all exist, it is the same as point 1, however if only a partial number of keys exist, the command emits a `TRYAGAIN` error in order for the keys interested to finish being migrated to the target node, so that the multi keys command can be executed. - -## CLUSTER SETSLOT `` IMPORTING `` - -This subcommand is the reverse of `MIGRATING`, and prepares the destination -node to import keys from the specified source node. The command only works if -the node is not already owner of the specified hash slot. - -When a slot is set in importing state, the node changes behavior in the following way: - -1. Commands about this hash slot are refused and a `MOVED` redirection is generated as usually, but in the case the command follows an `ASKING` command, in this case the command is executed. - -In this way when a node in migrating state generates an `ASK` redirection, the client contacts the target node, sends `ASKING`, and immediately after sends the command. This way commands about non-existing keys in the old node or keys already migrated to the target node are executed in the target node, so that: - -1. New keys are always created in the target node. During a hash slot migration we'll have to move only old keys, not new ones. -2. Commands about keys already migrated are correctly processed in the context of the node which is the target of the migration, the new hash slot owner, in order to guarantee consistency. -3. Without `ASKING` the behavior is the same as usually. This guarantees that clients with a broken hash slots mapping will not write for error in the target node, creating a new version of a key that has yet to be migrated. - -## CLUSTER SETSLOT `` STABLE - -This subcommand just clears migrating / importing state from the slot. It is -mainly used to fix a cluster stuck in a wrong state by `valkey-cli --cluster fix`. -Normally the two states are cleared automatically at the end of the migration -using the `SETSLOT ... NODE ...` subcommand as explained in the next section. - -## CLUSTER SETSLOT `` NODE `` - -The `NODE` subcommand is the one with the most complex semantics. It -associates the hash slot with the specified node, however the command works -only in specific situations and has different side effects depending on the -slot state. The following is the set of pre-conditions and side effects of the -command: - -1. If the current hash slot owner is the node receiving the command, but for effect of the command the slot would be assigned to a different node, the command will return an error if there are still keys for that hash slot in the node receiving the command. -2. If the slot is in *migrating* state, the state gets cleared when the slot is assigned to another node. -3. If the slot was in *importing* state in the node receiving the command, and the command assigns the slot to this node (which happens in the target node at the end of the resharding of a hash slot from one node to another), the command has the following side effects: A) the *importing* state is cleared. B) If the node config epoch is not already the greatest of the cluster, it generates a new one and assigns the new config epoch to itself. This way its new hash slot ownership will win over any past configuration created by previous failovers or slot migrations. - -It is important to note that step 3 is the only time when a Valkey Cluster node will create a new config epoch without agreement from other nodes. This only happens when a manual configuration is operated. However it is impossible that this creates a non-transient setup where two nodes have the same config epoch, since Valkey Cluster uses a config epoch collision resolution algorithm. - -## Valkey Cluster live resharding explained - -The `CLUSTER SETSLOT` command is an important piece used by Valkey Cluster in order to migrate all the keys contained in one hash slot from one node to another. This is how the migration is orchestrated, with the help of other commands as well. We'll call the node that has the current ownership of the hash slot the `source` node, and the node where we want to migrate the `destination` node. - -1. Set the destination node slot to *importing* state using `CLUSTER SETSLOT IMPORTING `. -2. Set the source node slot to *migrating* state using `CLUSTER SETSLOT MIGRATING `. -3. Get keys from the source node with [`CLUSTER GETKEYSINSLOT`](cluster-getkeysinslot.md) command and move them into the destination node using the [`MIGRATE`](migrate.md) command. -4. Send `CLUSTER SETSLOT NODE ` to the destination node. -5. Send `CLUSTER SETSLOT NODE ` to the source node. -6. Send `CLUSTER SETSLOT NODE ` to the other primary nodes (optional). - -Notes: - -* The order of step 1 and 2 is important. We want the destination node to be ready to accept `ASK` redirections when the source node is configured to redirect. -* The order of step 4 and 5 is important. - The destination node is responsible for propagating the change to the rest of the cluster. - If the source node is informed before the destination node and the destination node crashes before it is set as new slot owner, the slot is left with no owner, even after a successful failover. -* Step 6, sending `SETSLOT` to the nodes not involved in the resharding, is not technically necessary since the configuration will eventually propagate itself. - However, it is a good idea to do so in order to stop nodes from pointing to the wrong node for the hash slot moved as soon as possible, resulting in less redirections to find the right node. -* Starting from Valkey 8.0, `CLUSTER SETSLOT` is synchronously replicated to all healthy replicas - running Valkey version 8.0+. By default, this synchronous replication must complete within 2 seconds. - If the replication fails, the primary does not execute the command, and the client receives a - `NOREPLICAS Not enough good replicas to write` error. Operators can retry the command or customize the - timeout using the `TIMEOUT` parameter to further increase the reliability of live reconfiguration: - - ``` - CLUSTER SETSLOT slot [MIGRATING|IMPORTING|NODE] node-id [TIMEOUT timeout] - ``` - - Here, `timeout` is measured in seconds, with 0 meaning to wait indefinitely. - -## Reply - -`OK` if the command was successful. Otherwise an error is returned. diff --git a/commands/cluster-shards.md b/commands/cluster-shards.md deleted file mode 100644 index bca0a1bc..00000000 --- a/commands/cluster-shards.md +++ /dev/null @@ -1,176 +0,0 @@ -`CLUSTER SHARDS` returns details about the shards of the cluster. -A shard is defined as a collection of nodes that serve the same set of slots and that replicate from each other. -A shard may only have a single primary at a given time, but may have multiple or no replicas. -It is possible for a shard to not be serving any slots while still having replicas. - -The command is suitable to be used by Valkey Cluster client libraries in order to understand the topology of the cluster. -A client should issue this command on startup in order to retrieve the map associating cluster *hash slots* with actual node information. -This map should be used to direct commands to the node that is likely serving the slot associated with a given command. -In the event the command is sent to the wrong node, in that it received a '-MOVED' redirect, this command can then be used to update the topology of the cluster. - -The command returns an array of shards, with each shard containing three fields, 'slots', 'nodes' and 'id'. - -The 'slots' field is a list of slot ranges served by this shard, stored as pair of integers representing the inclusive start and end slots of the ranges. -For example, if a node owns the slots 1, 2, 3, 5, 7, 8 and 9, the slots ranges would be stored as [1-3], [5-5], [7-9]. -The slots field would therefore be represented by the following list of integers. - -``` -1) 1) "slots" - 2) 1) (integer) 1 - 2) (integer) 3 - 3) (integer) 5 - 4) (integer) 5 - 5) (integer) 7 - 6) (integer) 9 -``` - -The 'nodes' field contains a list of all nodes within the shard. -Each individual node is a map of attributes that describe the node. -Some attributes are optional and more attributes may be added in the future. -The current list of attributes: - -* id: The unique node id for this particular node. -* endpoint: The preferred endpoint to reach the node, see below for more information about the possible values of this field. -* ip: The IP address to send requests to for this node. -* hostname (optional): The announced hostname to send requests to for this node. -* port (optional): The TCP (non-TLS) port of the node. At least one of port or tls-port will be present. -* tls-port (optional): The TLS port of the node. At least one of port or tls-port will be present. -* role: The replication role of this node. -* replication-offset: The replication offset of this node. This information can be used to send commands to the most up to date replicas. -* health: Either `online`, `fail`, or `loading`. This information should be used to determine which nodes should be sent traffic. The `loading` health state should be used to know that a node is not currently eligible to serve traffic, but may be eligible in the future. -* availability-zone (optional): The availability zone configured for this node. This field is returned only when the node has a non-empty `availability-zone` configuration value, and is omitted otherwise. - -The endpoint, along with the port, defines the location that clients should use to send requests for a given slot. -A NULL value for the endpoint indicates the node has an unknown endpoint and the client should connect to the same endpoint it used to send the `CLUSTER SHARDS` command but with the port returned from the command. -This unknown endpoint configuration is useful when the Valkey nodes are behind a load balancer that Valkey doesn't know the endpoint of. -Which endpoint is set is determined by the `cluster-preferred-endpoint-type` config. -An empty string `""` is another abnormal value of the endpoint field, as well as for the ip field, which is returned if the node doesn't know its own IP address. -This can happen in a cluster that consists of only one node or the node has not yet been joined with the rest of the cluster. -The value `?` is displayed if the node is incorrectly configured to use announced hostnames but no hostname is configured using `cluster-announce-hostname`. -Clients may treat the empty string in the same way as NULL, that is the same endpoint it used to send the current command to, while `"?"` should be treated as an unknown node, not necessarily the same node as the one serving the current command. - -The 'id' field is the unique id of the shard, which is randomly generated and 40 characters long. - -## Reply - -Nested array of maps of hash ranges and shard nodes describing individual shards. - -## Examples - -``` -> CLUSTER SHARDS -1) 1) "slots" - 2) 1) (integer) 0 - 2) (integer) 5460 - 3) "nodes" - 4) 1) 1) "id" - 2) "e10b7051d6bf2d5febd39a2be297bbaea6084111" - 3) "port" - 4) (integer) 30001 - 5) "ip" - 6) "127.0.0.1" - 7) "endpoint" - 8) "127.0.0.1" - 9) "role" - 10) "master" - 11) "replication-offset" - 12) (integer) 72156 - 13) "health" - 14) "online" - 15) "availability-zone" - 16) "zone-a" - 2) 1) "id" - 2) "1901f5962d865341e81c85f9f596b1e7160c35ce" - 3) "port" - 4) (integer) 30006 - 5) "ip" - 6) "127.0.0.1" - 7) "endpoint" - 8) "127.0.0.1" - 9) "role" - 10) "replica" - 11) "replication-offset" - 12) (integer) 72156 - 13) "health" - 14) "online" - 15) "availability-zone" - 16) "zone-a" - 5) "id" - 6) "cd7688ca959bf54a32569ccf260b26715b82a6e3" -2) 1) "slots" - 2) 1) (integer) 10923 - 2) (integer) 16383 - 3) "nodes" - 4) 1) 1) "id" - 2) "fd20502fe1b32fc32c15b69b0a9537551f162f1f" - 3) "port" - 4) (integer) 30003 - 5) "ip" - 6) "127.0.0.1" - 7) "endpoint" - 8) "127.0.0.1" - 9) "role" - 10) "master" - 11) "replication-offset" - 12) (integer) 72156 - 13) "health" - 14) "online" - 15) "availability-zone" - 16) "zone-a" - 2) 1) "id" - 2) "6daa25c08025a0c7e4cc0d1ab255949ce6cee902" - 3) "port" - 4) (integer) 30005 - 5) "ip" - 6) "127.0.0.1" - 7) "endpoint" - 8) "127.0.0.1" - 9) "role" - 10) "replica" - 11) "replication-offset" - 12) (integer) 72156 - 13) "health" - 14) "online" - 15) "availability-zone" - 16) "zone-a" - 5) "id" - 6) "0d77234c440a6b05c2d77d1b9f37ac63585fc747" -3) 1) "slots" - 2) 1) (integer) 5461 - 2) (integer) 10922 - 3) "nodes" - 4) 1) 1) "id" - 2) "a4a3f445ead085eb3eb9ee7d8c644ec4481ec9be" - 3) "port" - 4) (integer) 30002 - 5) "ip" - 6) "127.0.0.1" - 7) "endpoint" - 8) "127.0.0.1" - 9) "role" - 10) "master" - 11) "replication-offset" - 12) (integer) 72156 - 13) "health" - 14) "online" - 15) "availability-zone" - 16) "zone-a" - 2) 1) "id" - 2) "da6d5847aa019e9b9d2a8aa24a75f856fd3456cc" - 3) "port" - 4) (integer) 30004 - 5) "ip" - 6) "127.0.0.1" - 7) "endpoint" - 8) "127.0.0.1" - 9) "role" - 10) "replica" - 11) "replication-offset" - 12) (integer) 72156 - 13) "health" - 14) "online" - 15) "availability-zone" - 16) "zone-a" - 5) "id" - 6) "a96f023185ea6d7f5e9a0d6ada6f112741217e6a" -``` diff --git a/commands/cluster-slaves.md b/commands/cluster-slaves.md deleted file mode 100644 index ecc964cd..00000000 --- a/commands/cluster-slaves.md +++ /dev/null @@ -1,17 +0,0 @@ -**A note about the word slave used in this man page and command name**: the Valkey project no longer uses the words "master" and "slave". Please use the new command `CLUSTER REPLICAS`. The command `CLUSTER SLAVES` will continue to work for backward compatibility. - -The command provides a list of replica nodes replicating from the specified -primary node. The list is provided in the same format used by `CLUSTER NODES` (please refer to its documentation for the specification of the format). - -The command will fail if the specified node is not known or if it is not -a primary according to the node table of the node receiving the command. - -Note that if a replica is added, moved, or removed from a given primary node, -and we ask `CLUSTER SLAVES` to a node that has not yet received the -configuration update, it may show stale information. However eventually -(in a matter of seconds if there are no network partitions) all the nodes -will agree about the set of nodes associated with a given primary. - -## Reply - -Array of replica nodes replicating from the specified primary node provided in the same format used by `CLUSTER NODES`. diff --git a/commands/cluster-slot-stats.md b/commands/cluster-slot-stats.md deleted file mode 100644 index ed6ba5eb..00000000 --- a/commands/cluster-slot-stats.md +++ /dev/null @@ -1,102 +0,0 @@ -Returns an array of slot usage statistics for slots assigned to the current shard. -The command is suitable for Valkey Cluster users aiming to assess general slot usage trends, identify hot / cold slots, migrate slots for a balanced cluster workload, and / or re-write application logic to better utilize slots. - -The following statistics are supported: - -* `key-count` -- Number of keys residing in a given slot. -* `cpu-usec` -- Amount of CPU time (in microseconds) spent on a given slot. -* `network-bytes-in` -- Amount of network ingress (in bytes) received for given slot. -* `network-bytes-out` -- Amount of network egress (in bytes) sent out for given slot. - -**Note:** By default, only `key-count` is returned. To enable `cpu-usec`, `network-bytes-in`, and `network-bytes-out` statistics, set `cluster-slot-stats-enabled yes` in the configuration. - -## Options - -* `ORDERBY` -- Returns an ordered slot statistics based on the specified statistic and sub-arguments to identify hot / cold slots across the cluster. Either `ASC` or `DESC` modifiers can be used. In the event of a tie in the stats, ascending slot number is used as a tie breaker. -* `SLOTSRANGE` -- Returns slot statistics based on the slots range provided for pagination. The range is inclusive. The response is ordered in ascending slot number. - -## Reply - -Nested array of slot usage statistics. - -## Examples - -### Response in RESP2 - -For `ORDERBY`: -``` -> CLUSTER SLOT-STATS ORDERBY KEY-COUNT LIMIT 2 DESC -1) 1) (integer) 12426 - 2) 1) "key-count" - 2) (integer) 45 - 3) "cpu-usec" - 4) (integer) 0 - 5) "network-bytes-in" - 6) (integer) 0 - 7) "network-bytes-out" - 8) (integer) 0 -2) 1) (integer) 13902 - 2) 1) "key-count" - 2) (integer) 20 - 3) "cpu-usec" - 4) (integer) 0 - 5) "network-bytes-in" - 6) (integer) 0 - 7) "network-bytes-out" - 8) (integer) 0 -``` - -For `SLOTSRANGE`: -``` -> CLUSTER SLOT-STATS SLOTSRANGE 0 1 -1) 1) (integer) 0 - 2) 1) "key-count" - 2) (integer) 0 - 3) "cpu-usec" - 4) (integer) 0 - 5) "network-bytes-in" - 6) (integer) 0 - 7) "network-bytes-out" - 8) (integer) 0 -2) 1) (integer) 1 - 2) 1) "key-count" - 2) (integer) 0 - 3) "cpu-usec" - 4) (integer) 0 - 5) "network-bytes-in" - 6) (integer) 0 - 7) "network-bytes-out" - 8) (integer) 0 -``` - -### Response in RESP3 - -For `ORDERBY`: -``` -> CLUSTER SLOT-STATS ORDERBY KEY-COUNT LIMIT 2 DESC -1) 1) (integer) 12426 - 2) 1# "key-count" => (integer) 45 - 2# "cpu-usec" => (integer) 0 - 3# "network-bytes-in" => (integer) 0 - 4# "network-bytes-out" => (integer) 0 -2) 1) (integer) 13902 - 2) 1# "key-count" => (integer) 20 - 2# "cpu-usec" => (integer) 0 - 3# "network-bytes-in" => (integer) 0 - 4# "network-bytes-out" => (integer) 0 -``` - -For `SLOTSRANGE`: -``` -> CLUSTER SLOT-STATS SLOTSRANGE 0 1 -1) 1) (integer) 0 - 2) 1# "key-count" => (integer) 0 - 2# "cpu-usec" => (integer) 0 - 3# "network-bytes-in" => (integer) 0 - 4# "network-bytes-out" => (integer) 0 -2) 1) (integer) 1 - 2) 1# "key-count" => (integer) 0 - 2# "cpu-usec" => (integer) 0 - 3# "network-bytes-in" => (integer) 0 - 4# "network-bytes-out" => (integer) 0 -``` diff --git a/commands/cluster-slots.md b/commands/cluster-slots.md deleted file mode 100644 index 9e62edec..00000000 --- a/commands/cluster-slots.md +++ /dev/null @@ -1,105 +0,0 @@ -`CLUSTER SLOTS` returns details about which cluster slots map to which Valkey instances. -The command is suitable to be used by Valkey Cluster client libraries implementations in order to retrieve (or update when a redirection is received) the map associating cluster *hash slots* with actual nodes network information, so that when a command is received, it can be sent to what is likely the right instance for the keys specified in the command. - -The networking information for each node is an array containing the following elements: - -* Preferred endpoint (Either an IP address, hostname, or NULL) -* Port number -* The node ID -* A map of additional networking metadata - -The preferred endpoint, along with the port, defines the location that clients should use to send requests for a given slot. -A NULL value for the endpoint indicates the node has an unknown endpoint and the client should connect to the same endpoint it used to send the `CLUSTER SLOTS` command but with the port returned from the command. -This unknown endpoint configuration is useful when the Valkey nodes are behind a load balancer that Valkey doesn't know the endpoint of. -Which endpoint is set as preferred is determined by the `cluster-preferred-endpoint-type` config. -An empty string `""` is another abnormal value of the endpoint field, as well as for the ip field, which is returned if the node doesn't know its own IP address. -This can happen in a cluster that consists of only one node or the node has not yet been joined with the rest of the cluster. -The value `?` is displayed if the node is incorrectly configured to use announced hostnames but no hostname is configured using `cluster-announce-hostname`. -Clients may treat the empty string in the same way as NULL, that is the same endpoint it used to send the current command to, while `"?"` should be treated as an unknown node, not necessarily the same node as the one serving the current command. - -Additional networking metadata is provided as a map on the fourth argument for each node. -The following networking metadata may be returned: - -* `ip`: When the preferred endpoint is not set to IP. -* `hostname`: When a node has an announced hostname but the primary endpoint is not set to hostname. -* `availability-zone`: When the node has a non-empty `availability-zone` configuration value. This key is omitted when the value is empty. - -## Nested Result Array -Each nested result is: - - - Start slot range - - End slot range - - Primary for slot range represented as nested networking information - - First replica of primary for slot range - - Second replica - - ...continues until all replicas for this primary are returned. - -Each result includes all active replicas of the primary instance -for the listed slot range. Failed replicas are not returned. - -The command response is deterministic across all nodes in a cluster, which means that if two nodes return the same response they have the same view of the cluster. -Primaries are ordered by the slots they serve and then replicas are ordered lexicographically by the node-id they were assigned by the cluster. -The third nested reply is guaranteed to be the networking information of the primary instance for the slot range. -All networking information after the third nested reply are replicas of the primary. - -If a cluster instance has non-contiguous slots (e.g. 1-400,900,1800-6000) then primary and replica networking information results will be duplicated for each top-level slot range reply. - -``` -> CLUSTER SLOTS -1) 1) (integer) 0 - 2) (integer) 5460 - 3) 1) "127.0.0.1" - 2) (integer) 30001 - 3) "09dbe9720cda62f7865eabc5fd8857c5d2678366" - 4) 1) hostname - 2) "host-1.valkey.example.com" - 3) availability-zone - 4) "zone-a" - 4) 1) "127.0.0.1" - 2) (integer) 30004 - 3) "821d8ca00d7ccf931ed3ffc7e3db0599d2271abf" - 4) 1) hostname - 2) "host-2.valkey.example.com" - 3) availability-zone - 4) "zone-a" -2) 1) (integer) 5461 - 2) (integer) 10922 - 3) 1) "127.0.0.1" - 2) (integer) 30002 - 3) "c9d93d9f2c0c524ff34cc11838c2003d8c29e013" - 4) 1) hostname - 2) "host-3.valkey.example.com" - 3) availability-zone - 4) "zone-a" - 4) 1) "127.0.0.1" - 2) (integer) 30005 - 3) "faadb3eb99009de4ab72ad6b6ed87634c7ee410f" - 4) 1) hostname - 2) "host-4.valkey.example.com" - 3) availability-zone - 4) "zone-a" -3) 1) (integer) 10923 - 2) (integer) 16383 - 3) 1) "127.0.0.1" - 2) (integer) 30003 - 3) "044ec91f325b7595e76dbcb18cc688b6a5b434a1" - 4) 1) hostname - 2) "host-5.valkey.example.com" - 3) availability-zone - 4) "zone-a" - 4) 1) "127.0.0.1" - 2) (integer) 30006 - 3) "58e6e48d41228013e5d9c1c37c5060693925e97e" - 4) 1) hostname - 2) "host-6.valkey.example.com" - 3) availability-zone - 4) "zone-a" -``` - -**Warning:** In future versions there could be more elements describing the node better. -In general a client implementation should just rely on the fact that certain parameters are at fixed positions as specified, but more parameters may follow and should be ignored. -Similarly a client library should try if possible to cope with the fact that older versions may just have the primary endpoint and port parameter. - -## Reply - -Nested array of slot ranges with networking information. diff --git a/commands/cluster-syncslots.md b/commands/cluster-syncslots.md deleted file mode 100644 index f39bb08b..00000000 --- a/commands/cluster-syncslots.md +++ /dev/null @@ -1,4 +0,0 @@ -Internal command to allow navigation of the atomic slot migration state machine. - -For more information about atomic slot migration in Valkey please check the -[atomic slot migration](../topics/atomic-slot-migration.md) page. diff --git a/commands/cluster.md b/commands/cluster.md deleted file mode 100644 index 0d8f3e8a..00000000 --- a/commands/cluster.md +++ /dev/null @@ -1,3 +0,0 @@ -This is a container command for Valkey Cluster commands. - -To see the list of available commands you can call `CLUSTER HELP`. diff --git a/commands/clusterscan.md b/commands/clusterscan.md deleted file mode 100644 index 9191b4f6..00000000 --- a/commands/clusterscan.md +++ /dev/null @@ -1,83 +0,0 @@ -`CLUSTERSCAN` iterates over keys across a Valkey Cluster. -It walks through every hash slot in the cluster, one slot at a time. - -Similar to `SCAN`, it is cursor-based. You start by passing `0` as the cursor and keep calling until the returned cursor is `0` again. -The cursor format is `fingerprint-{hashtag}-localcursor`. -The fingerprint is an opaque string that identifies how the node will return cursor, which currently includes information about the engine version and the `hash-seed` config value. -Mismatches in the fingerprint will result in the cursor restarting the current slot. -The [hash tag](../topics/cluster-spec.md#hash-tags) represents the current slot (e.g., `{06S}`), so cluster-aware clients will route each call to the right node automatically. -The local cursor helps resume the scan from where it left off. - -``` -127.0.0.1:6379> CLUSTERSCAN 0 -1) "0-{06S}-0" -2) (empty list or set) -127.0.0.1:6379> CLUSTERSCAN 0-{06S}-0 -1) "0B3a21-{06S}-96" -2) 1) "key:1" - 2) "key:2" - 3) "key:3" -127.0.0.1:6379> CLUSTERSCAN 0B3a21-{06S}-96 -1) "0-{Qi}-0" -2) 1) "key:4" -``` - -In this example, the first call returns an initial cursor for slot 0 with no keys. -The next call scans through slot 0 and returns keys. -Once slot 0 is done, the cursor moves on to slot 1 (you can see the hash tag change from `{06S}` to `{Qi}`). -Since the cursor carries the hash tag, the client naturally routes the next call to whichever node owns slot 1. -This continues until all slots have been visited and the cursor comes back as `0`. - -## The SLOT option - -By default `CLUSTERSCAN` goes through all slots from 0 to 16383. -If you only care about keys in a particular slot, pass the `SLOT` option: - -``` -127.0.0.1:6379> CLUSTERSCAN 0 SLOT 0 -1) "0-{06S}-0" -2) (empty list or set) -127.0.0.1:6379> CLUSTERSCAN 0-{06S}-0 SLOT 0 -1) "0B3a21-{06S}-64" -2) 1) "key_in_slot0:1" -``` - -With `SLOT`, the scan stays within that slot and returns `0` when it's done rather than advancing to the next one. -This also makes it possible to run scans in parallel by issuing concurrent `CLUSTERSCAN` calls for different slots. -If the cursor already points to a different slot than the `SLOT` argument, you'll get an error. -You can only specify `SLOT` once per call. - -## MATCH, COUNT and TYPE options - -These work the same way as in [`SCAN`](scan.md). -`MATCH` filters by a glob-style pattern, `COUNT` hints how many keys to return per call (default 10), and `TYPE` filters by data type. - -## Handling topology changes - -`CLUSTERSCAN` is designed to keep working when the cluster topology changes mid-scan: - -* **Slot migration**: If a slot moves to another node while you're scanning it, the old node sends back a `-MOVED` redirect. - Just follow the redirect and continue with the same cursor on the new owner. -* **Failover and node restart**: If the node's memory layout has changed since the cursor was issued, the scan restarts from the beginning of that slot instead of returning an error. - To avoid this, set [`hash-seed`](scan.md) to the same value on all nodes. -* **Unassigned slots**: If the cursor points to a slot that no node is serving, you'll get a `-CLUSTERDOWN` error. - -When all nodes share the same [`hash-seed`](scan.md), the fingerprint stays consistent across failovers and resharding, so cursors remain valid without restarting. - -## Guarantees - -`CLUSTERSCAN` gives the same guarantees as [`SCAN`](scan.md): - -* Every key that exists throughout the entire iteration of a slot will be returned at least once. -* Duplicates are possible, especially around topology changes, so your application should be prepared to handle them. - -## Return value - -An array with two elements: the cursor to pass in the next call, and an array of key names. - -## Reply - -Array with two elements. - -* The first element is a string that represents the cursor. -* The second element is an array with the names of scanned keys. diff --git a/commands/command-count.md b/commands/command-count.md deleted file mode 100644 index a5a43dd6..00000000 --- a/commands/command-count.md +++ /dev/null @@ -1,12 +0,0 @@ -Returns the total number of commands in this Valkey server. - -## Reply - -Integer: the number of commands returned by `COMMAND`. - -## Examples - -``` -127.0.0.1:6379> COMMAND COUNT -(integer) 274 -``` diff --git a/commands/command-docs.md b/commands/command-docs.md deleted file mode 100644 index b9310a87..00000000 --- a/commands/command-docs.md +++ /dev/null @@ -1,182 +0,0 @@ -Return documentary information about commands. - -By default, the reply includes all of the server's commands. -You can use the optional _command-name_ argument to specify the names of one or more commands. - -The reply includes a map for each returned command. -The following keys may be included in the mapped reply: - -* **summary:** short command description. -* **since:** the Valkey version that added the command (or for module commands, the module version). -* **group:** the functional group to which the command belongs. - Possible values are: - - _bitmap_ - - _cluster_ - - _connection_ - - _generic_ - - _geo_ - - _hash_ - - _hyperloglog_ - - _list_ - - _module_ - - _pubsub_ - - _scripting_ - - _sentinel_ - - _server_ - - _set_ - - _sorted-set_ - - _stream_ - - _string_ - - _transactions_ -* **complexity:** a short explanation about the command's time complexity. -* **doc_flags:** an array of documentation flags. - Possible values are: - - _deprecated:_ the command is deprecated. - - _syscmd:_ a system command that isn't meant to be called by users. -* **deprecated_since:** the Valkey version that deprecated the command (or for module commands, the module version).. -* **replaced_by:** the alternative for a deprecated command. -* **history:** an array of historical notes describing changes to the command's output or arguments. It should not contain information about behavioral changes. - Each entry is an array itself, made up of two elements: - 1. The Valkey version that the entry applies to. - 2. The description of the change. -* **arguments:** an array of maps that describe the command's arguments. - Please refer to the [Valkey command arguments][td] page for more information. - -[td]: ../topics/command-arguments.md - -## Reply - -Map where each key is a command name, and each value is the documentary information. - -## Examples - -``` -127.0.0.1:6379> COMMAND DOCS SET -1) "set" -2) 1) "summary" - 2) "Sets the string value of a key, ignoring its type. The key is created if it doesn't exist." - 3) "since" - 4) "1.0.0" - 5) "group" - 6) "string" - 7) "complexity" - 8) "O(1)" - 9) "history" - 10) 1) 1) "2.6.12" - 2) "Added the `EX`, `PX`, `NX` and `XX` options." - 2) 1) "6.0.0" - 2) "Added the `KEEPTTL` option." - 3) 1) "6.2.0" - 2) "Added the `GET`, `EXAT` and `PXAT` option." - 4) 1) "7.0.0" - 2) "Allowed the `NX` and `GET` options to be used together." - 11) "arguments" - 12) 1) 1) "name" - 2) "key" - 3) "type" - 4) "key" - 5) "display_text" - 6) "key" - 7) "key_spec_index" - 8) (integer) 0 - 2) 1) "name" - 2) "value" - 3) "type" - 4) "string" - 5) "display_text" - 6) "value" - 3) 1) "name" - 2) "condition" - 3) "type" - 4) "oneof" - 5) "since" - 6) "2.6.12" - 7) "flags" - 8) 1) optional - 9) "arguments" - 10) 1) 1) "name" - 2) "nx" - 3) "type" - 4) "pure-token" - 5) "display_text" - 6) "nx" - 7) "token" - 8) "NX" - 2) 1) "name" - 2) "xx" - 3) "type" - 4) "pure-token" - 5) "display_text" - 6) "xx" - 7) "token" - 8) "XX" - 4) 1) "name" - 2) "get" - 3) "type" - 4) "pure-token" - 5) "display_text" - 6) "get" - 7) "token" - 8) "GET" - 9) "since" - 10) "6.2.0" - 11) "flags" - 12) 1) optional - 5) 1) "name" - 2) "expiration" - 3) "type" - 4) "oneof" - 5) "flags" - 6) 1) optional - 7) "arguments" - 8) 1) 1) "name" - 2) "seconds" - 3) "type" - 4) "integer" - 5) "display_text" - 6) "seconds" - 7) "token" - 8) "EX" - 9) "since" - 10) "2.6.12" - 2) 1) "name" - 2) "milliseconds" - 3) "type" - 4) "integer" - 5) "display_text" - 6) "milliseconds" - 7) "token" - 8) "PX" - 9) "since" - 10) "2.6.12" - 3) 1) "name" - 2) "unix-time-seconds" - 3) "type" - 4) "unix-time" - 5) "display_text" - 6) "unix-time-seconds" - 7) "token" - 8) "EXAT" - 9) "since" - 10) "6.2.0" - 4) 1) "name" - 2) "unix-time-milliseconds" - 3) "type" - 4) "unix-time" - 5) "display_text" - 6) "unix-time-milliseconds" - 7) "token" - 8) "PXAT" - 9) "since" - 10) "6.2.0" - 5) 1) "name" - 2) "keepttl" - 3) "type" - 4) "pure-token" - 5) "display_text" - 6) "keepttl" - 7) "token" - 8) "KEEPTTL" - 9) "since" - 10) "6.0.0" -``` diff --git a/commands/command-getkeys.md b/commands/command-getkeys.md deleted file mode 100644 index 5619422d..00000000 --- a/commands/command-getkeys.md +++ /dev/null @@ -1,28 +0,0 @@ -Returns @array-reply of keys from a full Valkey command. - -`COMMAND GETKEYS` is a helper command to let you find the keys -from a full Valkey command. - -`COMMAND` provides information on how to find the key names of each command (see `firstkey`, [key specifications](../topics/key-specs.md#logical-operation-flags), and `movablekeys`), -but in some cases it's not possible to find keys of certain commands and then the entire command must be parsed to discover some / all key names. -You can use `COMMAND GETKEYS` or [`COMMAND GETKEYSANDFLAGS`](command-getkeysandflags.md) to discover key names directly from how Valkey parses the commands. - -## Reply - -Array of keys from the given command. - -## Examples - -``` -127.0.0.1:6379> COMMAND GETKEYS MSET a b c d e f -1) "a" -2) "c" -3) "e" -127.0.0.1:6379> COMMAND GETKEYS EVAL "not consulted" 3 key1 key2 key3 arg1 arg2 arg3 argN -1) "key1" -2) "key2" -3) "key3" -127.0.0.1:6379> COMMAND GETKEYS SORT mylist ALPHA STORE outlist -1) "mylist" -2) "outlist" -``` diff --git a/commands/command-getkeysandflags.md b/commands/command-getkeysandflags.md deleted file mode 100644 index 6561eb9f..00000000 --- a/commands/command-getkeysandflags.md +++ /dev/null @@ -1,34 +0,0 @@ -Returns @array-reply of keys from a full Valkey command and their usage flags. - -`COMMAND GETKEYSANDFLAGS` is a helper command to let you find the keys from a full Valkey command together with flags indicating what each key is used for. - -[`COMMAND`](command.md) provides information on how to find the key names of each command (see `firstkey`, [key specifications](../topics/key-specs.md#logical-operation-flags), and `movablekeys`), -but in some cases it's not possible to find keys of certain commands and then the entire command must be parsed to discover some / all key names. -You can use [`COMMAND GETKEYS`](command-getkeys.md) or `COMMAND GETKEYSANDFLAGS` to discover key names directly from how Valkey parses the commands. - -Refer to [key specifications](../topics/key-specs.md#logical-operation-flags) for information about the meaning of the key flags. - -## Reply - -Array of keys from the given command and their usage flags. - -## Examples - -``` -127.0.0.1:6379> COMMAND GETKEYS MSET a b c d e f -1) "a" -2) "c" -3) "e" -127.0.0.1:6379> COMMAND GETKEYS EVAL "not consulted" 3 key1 key2 key3 arg1 arg2 arg3 argN -1) "key1" -2) "key2" -3) "key3" -127.0.0.1:6379> COMMAND GETKEYSANDFLAGS LMOVE mylist1 mylist2 left left -1) 1) "mylist1" - 2) 1) RW - 2) access - 3) delete -2) 1) "mylist2" - 2) 1) RW - 2) insert -``` diff --git a/commands/command-help.md b/commands/command-help.md deleted file mode 100644 index 8cae4e59..00000000 --- a/commands/command-help.md +++ /dev/null @@ -1,5 +0,0 @@ -The `COMMAND HELP` command returns a helpful text describing the different subcommands. - -## Reply - -Array of sub-commands and their descriptions. diff --git a/commands/command-info.md b/commands/command-info.md deleted file mode 100644 index 23f0ea96..00000000 --- a/commands/command-info.md +++ /dev/null @@ -1,239 +0,0 @@ -Returns @array-reply of details about multiple Valkey commands. - -Same result format as [`COMMAND`](command.md) except you can specify which commands -get returned. - -If you request details about non-existing commands, their return -position will be nil. - -## Reply - -Nested array of command details. - -## Examples - -``` -127.0.0.1:6379> COMMAND INFO get set eval -1) 1) "get" - 2) (integer) 2 - 3) 1) readonly - 2) fast - 4) (integer) 1 - 5) (integer) 1 - 6) (integer) 1 - 7) 1) @read - 2) @string - 3) @fast - 8) (empty array) - 9) 1) 1) "flags" - 2) 1) RO - 2) access - 3) "begin_search" - 4) 1) "type" - 2) "index" - 3) "spec" - 4) 1) "index" - 2) (integer) 1 - 5) "find_keys" - 6) 1) "type" - 2) "range" - 3) "spec" - 4) 1) "lastkey" - 2) (integer) 0 - 3) "keystep" - 4) (integer) 1 - 5) "limit" - 6) (integer) 0 - 10) (empty array) -2) 1) "set" - 2) (integer) -3 - 3) 1) write - 2) denyoom - 4) (integer) 1 - 5) (integer) 1 - 6) (integer) 1 - 7) 1) @write - 2) @string - 3) @slow - 8) (empty array) - 9) 1) 1) "notes" - 2) "RW and ACCESS due to the optional `GET` argument" - 3) "flags" - 4) 1) RW - 2) access - 3) update - 4) variable_flags - 5) "begin_search" - 6) 1) "type" - 2) "index" - 3) "spec" - 4) 1) "index" - 2) (integer) 1 - 7) "find_keys" - 8) 1) "type" - 2) "range" - 3) "spec" - 4) 1) "lastkey" - 2) (integer) 0 - 3) "keystep" - 4) (integer) 1 - 5) "limit" - 6) (integer) 0 - 10) (empty array) -3) 1) "eval" - 2) (integer) -3 - 3) 1) noscript - 2) stale - 3) skip_monitor - 4) no_mandatory_keys - 5) movablekeys - 4) (integer) 0 - 5) (integer) 0 - 6) (integer) 0 - 7) 1) @slow - 2) @scripting - 8) (empty array) - 9) 1) 1) "notes" - 2) "We cannot tell how the keys will be used so we assume the worst, RW and UPDATE" - 3) "flags" - 4) 1) RW - 2) access - 3) update - 5) "begin_search" - 6) 1) "type" - 2) "index" - 3) "spec" - 4) 1) "index" - 2) (integer) 2 - 7) "find_keys" - 8) 1) "type" - 2) "keynum" - 3) "spec" - 4) 1) "keynumidx" - 2) (integer) 0 - 3) "firstkey" - 4) (integer) 1 - 5) "keystep" - 6) (integer) 1 - 10) (empty array) -127.0.0.1:6379> COMMAND INFO foo evalsha config bar -1) (nil) -2) 1) "evalsha" - 2) (integer) -3 - 3) 1) noscript - 2) stale - 3) skip_monitor - 4) no_mandatory_keys - 5) movablekeys - 4) (integer) 0 - 5) (integer) 0 - 6) (integer) 0 - 7) 1) @slow - 2) @scripting - 8) (empty array) - 9) 1) 1) "flags" - 2) 1) RW - 2) access - 3) update - 3) "begin_search" - 4) 1) "type" - 2) "index" - 3) "spec" - 4) 1) "index" - 2) (integer) 2 - 5) "find_keys" - 6) 1) "type" - 2) "keynum" - 3) "spec" - 4) 1) "keynumidx" - 2) (integer) 0 - 3) "firstkey" - 4) (integer) 1 - 5) "keystep" - 6) (integer) 1 - 10) (empty array) -3) 1) "config" - 2) (integer) -2 - 3) (empty array) - 4) (integer) 0 - 5) (integer) 0 - 6) (integer) 0 - 7) 1) @slow - 8) (empty array) - 9) (empty array) - 10) 1) 1) "config|rewrite" - 2) (integer) 2 - 3) 1) admin - 2) noscript - 3) loading - 4) stale - 4) (integer) 0 - 5) (integer) 0 - 6) (integer) 0 - 7) 1) @admin - 2) @slow - 3) @dangerous - 8) 1) "request_policy:all_nodes" - 2) "response_policy:all_succeeded" - 9) (empty array) - 10) (empty array) - 2) 1) "config|resetstat" - 2) (integer) 2 - 3) 1) admin - 2) noscript - 3) loading - 4) stale - 4) (integer) 0 - 5) (integer) 0 - 6) (integer) 0 - 7) 1) @admin - 2) @slow - 3) @dangerous - 8) 1) "request_policy:all_nodes" - 2) "response_policy:all_succeeded" - 9) (empty array) - 10) (empty array) - 3) 1) "config|help" - 2) (integer) 2 - 3) 1) loading - 2) stale - 4) (integer) 0 - 5) (integer) 0 - 6) (integer) 0 - 7) 1) @slow - 8) (empty array) - 9) (empty array) - 10) (empty array) - 4) 1) "config|get" - 2) (integer) -3 - 3) 1) admin - 2) noscript - 3) loading - 4) stale - 4) (integer) 0 - 5) (integer) 0 - 6) (integer) 0 - 7) 1) @admin - 2) @slow - 3) @dangerous - 8) (empty array) - 9) (empty array) - 10) (empty array) - 5) 1) "config|set" - 2) (integer) -4 - 3) 1) admin - 2) noscript - 3) loading - 4) stale - 4) (integer) 0 - 5) (integer) 0 - 6) (integer) 0 - 7) 1) @admin - 2) @slow - 3) @dangerous - 8) 1) "request_policy:all_nodes" - 2) "response_policy:all_succeeded" - 9) (empty array) - 10) (empty array) -4) (nil) -``` diff --git a/commands/command-list.md b/commands/command-list.md deleted file mode 100644 index aee522ad..00000000 --- a/commands/command-list.md +++ /dev/null @@ -1,11 +0,0 @@ -Return an array of the server's command names. - -You can use the optional _FILTERBY_ modifier to apply one of the following filters: - - - **MODULE module-name**: get the commands that belong to the module specified by _module-name_. - - **ACLCAT category**: get the commands in the [ACL category](../topics/acl.md#command-categories) specified by _category_. - - **PATTERN pattern**: get the commands that match the given glob-like _pattern_. - -## Reply - -Array of command names. diff --git a/commands/command.md b/commands/command.md deleted file mode 100644 index 891b3cd1..00000000 --- a/commands/command.md +++ /dev/null @@ -1,237 +0,0 @@ -Return an array with details about every Valkey command. - -The `COMMAND` command is introspective. -Its reply describes all commands that the server can process. -Valkey clients can call it to obtain the server's runtime capabilities during the handshake. - -`COMMAND` also has several subcommands. -Please refer to its subcommands for further details. - -**Cluster note:** -this command is especially beneficial for cluster-aware clients. -Such clients must identify the names of keys in commands to route requests to the correct shard. -Although most commands accept a single key as their first argument, there are many exceptions to this rule. -You can call `COMMAND` and then keep the mapping between commands and their respective key specification rules cached in the client. - -The reply it returns is an array with an element per command. -Each element that describes a Valkey command is represented as an array by itself. - -The command's array consists of a fixed number of elements. -The exact number of elements in the array depends on the server's version. - -1. Name -1. Arity -1. Flags -1. First key -1. Last key -1. Step -1. [ACL categories][ta] -1. [Tips][tb] -1. [Key specifications][td] -1. Subcommands - -## Name - -This is the command's name in lowercase. - -**Note:** -Valkey command names are case-insensitive. - -## Arity - -Arity is the number of arguments a command expects. -It follows a simple pattern: - -* A positive integer means a fixed number of arguments. -* A negative integer means a minimal number of arguments. - -Command arity _always includes_ the command's name itself (and the subcommand when applicable). - -Examples: - -* The arity of [`GET`](get.md) is _2_ since the command only accepts one argument and always has the format `GET _key_`. -* The arity of [`MGET`](mget.md) is _-2_ since the command accepts at least one argument, but possibly multiple ones: `MGET _key1_ [key2] [key3] ...`. - -## Flags - -Command flags are an array. It can contain the following simple strings (status reply): - -* **admin:** the command is an administrative command. -* **asking:** the command is allowed even during hash slot migration. - This flag is relevant in Valkey Cluster deployments. -* **blocking:** the command may block the requesting client. -* **denyoom**: the command is rejected if the server's memory usage is too high (see the _maxmemory_ configuration directive). -* **fast:** the command operates in constant or log(N) time. - This flag is used for monitoring latency with the [`LATENCY`](latency.md) command. -* **loading:** the command is allowed while the database is loading. -* **movablekeys:** the _first key_, _last key_, and _step_ values don't determine all key positions. - Clients need to use [`COMMAND GETKEYS`](command-getkeys.md) or [key specifications][td] in this case. - See below for more details. -* **no_auth:** executing the command doesn't require authentication. -* **no_async_loading:** the command is denied during asynchronous loading (that is when a replica uses disk-less [`SWAPDB`](swapdb.md) [`SYNC`](sync.md), and allows access to the old dataset). -* **no_mandatory_keys:** the command may accept key name arguments, but these aren't mandatory. -* **no_multi:** the command isn't allowed inside the context of a [transaction](../topics/transactions.md). -* **noscript:** the command can't be called from [scripts](../topics/eval-intro.md) or [functions](../topics/functions-intro.md). -* **pubsub:** the command is related to [Valkey Pub/Sub](../topics/pubsub.md). -* **random**: the command returns random results, which is a concern with verbatim script replication. This flag is a [command tip][tb]. -* **readonly:** the command doesn't modify data. -* **sort_for_script:** the command's output is sorted when called from a script. -* **skip_monitor:** the command is not shown in the output of the [`MONITOR`](monitor.md) command. -* **skip_slowlog:** the command is not shown in the output of the [`SLOWLOG`](slowlog.md) command. This flag is a [command tip][tb]. -* **stale:** the command is allowed while a replica has stale data. -* **write:** the command may modify data. - -### Movablekeys - -Consider `SORT`: - -``` -1) 1) "sort" - 2) (integer) -2 - 3) 1) write - 2) denyoom - 3) movablekeys - 4) (integer) 1 - 5) (integer) 1 - 6) (integer) 1 - ... -``` - -Some Valkey commands have no predetermined key locations or are not easy to find. -For those commands, the _movablekeys_ flag indicates that the _first key_, _last key_, and _step_ values are insufficient to find all the keys. - -Here are several examples of commands that have the _movablekeys_ flag: - -* [`SORT`](sort.md): the optional _STORE_, _BY_, and _GET_ modifiers are followed by names of keys. -* [`ZUNION`](zunion.md): the _numkeys_ argument specifies the number key name arguments. -* [`MIGRATE`](migrate.md): the keys appear _KEYS_ keyword and only when the second argument is the empty string. - -Valkey Cluster clients need to use other measures, as follows, to locate the keys for such commands. - -You can use the [`COMMAND GETKEYS`](command-getkeys.md) command and have your Valkey server report all keys of a given command's invocation. - -Clients can use the [key specifications](#key-specifications) to identify the positions of key names. -The only commands that require using `COMMAND GETKEYS` are `SORT` and `MIGRATE` for clients that parse keys' specifications. - -For more information, please refer to the [key specifications page][tr]. - -## First key - -The position of the command's first key name argument. -For most commands, the first key's position is 1. -Position 0 is always the command name itself. - -## Last key - -The position of the command's last key name argument. -Valkey commands usually accept one, two or multiple number of keys. - -Commands that accept a single key have both _first key_ and _last key_ set to 1. - -Commands that accept two key name arguments, e.g. [`BRPOPLPUSH`](brpoplpush.md), [`SMOVE`](smove.md) and [`RENAME`](rename.md), have this value set to the position of their second key. - -Multi-key commands that accept an arbitrary number of keys, such as [`MSET`](mset.md), use the value -1. - -## Step - -The step, or increment, between the _first key_ and the position of the next key. - -Consider the following two examples: - -``` -1) 1) "mset" - 2) (integer) -3 - 3) 1) write - 2) denyoom - 4) (integer) 1 - 5) (integer) -1 - 6) (integer) 2 - ... -``` - -``` -1) 1) "mget" - 2) (integer) -2 - 3) 1) readonly - 2) fast - 4) (integer) 1 - 5) (integer) -1 - 6) (integer) 1 - ... -``` - -The step count allows us to find keys' positions. -For example [`MSET`](mset.md): Its syntax is `MSET _key1_ _val1_ [key2] [val2] [key3] [val3]...`, so the keys are at every other position (step value of _2_). -Unlike [`MGET`](mget.md), which uses a step value of _1_. - -## ACL categories - -This is an array of simple strings that are the ACL categories to which the command belongs. -Please refer to the [Access Control List][ta] page for more information. - -## Command tips - -Helpful information about the command. -To be used by clients/proxies. - -Please check the [Command tips][tb] page for more information. - -## Key specifications - -This is an array consisting of the command's key specifications. -Each element in the array is a map describing a method for locating keys in the command's arguments. - -For more information please check the [key specifications page][td]. - -## Subcommands - -This is an array containing all of the command's subcommands, if any. -Some Valkey commands have subcommands (e.g., the [`REWRITE`](config-rewrite.md) subcommand of `CONFIG`). -Each element in the array represents one subcommand and follows the same specifications as those of `COMMAND`'s reply. - -[ta]: ../topics/acl.md -[tb]: ../topics/command-tips.md -[td]: ../topics/key-specs.md -[tr]: ../topics/key-specs.md - -## Reply - -Nested array of command details. The order of the commands in the array is random. - -## Examples - -The following is `COMMAND`'s output for the [`GET`](get.md) command: - -``` -1) 1) "get" - 2) (integer) 2 - 3) 1) readonly - 2) fast - 4) (integer) 1 - 5) (integer) 1 - 6) (integer) 1 - 7) 1) @read - 2) @string - 3) @fast - 8) (empty array) - 9) 1) 1) "flags" - 2) 1) read - 3) "begin_search" - 4) 1) "type" - 2) "index" - 3) "spec" - 4) 1) "index" - 2) (integer) 1 - 5) "find_keys" - 6) 1) "type" - 2) "range" - 3) "spec" - 4) 1) "lastkey" - 2) (integer) 0 - 3) "keystep" - 4) (integer) 1 - 5) "limit" - 6) (integer) 0 - 10) (empty array) -... -``` diff --git a/commands/commandlog-get.md b/commands/commandlog-get.md deleted file mode 100644 index 074c7873..00000000 --- a/commands/commandlog-get.md +++ /dev/null @@ -1,33 +0,0 @@ -The `COMMANDLOG GET` command returns entries from the command log of specified type in chronological order. - -The Command Log system is used to record commands that consume significant resources during server operation, including CPU, memory, and network bandwidth. -These commands and the data they access may lead to abnormal instance operations, the command log can help users quickly and intuitively locate issues. - -Currently, three types of command logs are supported: - -* SLOW: Logs commands that exceed a specified execution time. This excludes time spent on I/O operations like client communication and focuses solely on the command's processing time, where the main thread is blocked. - -* LARGE-REQUEST: Logs commands with requests exceeding a defined size. This helps identify potentially problematic commands that send excessive data to the server. - -* LARGE-REPLY: Logs commands that generate replies exceeding a defined size. This helps identify commands that return unusually large amounts of data, which may impact network performance or client processing. - -Each log type has two key parameters: -1. A threshold value that determines when a command is logged. This threshold is specific to the type of log (e.g., execution time, request size, or reply size). A negative value disables logging. A value of 0 logs all commands. -2. A maximum length that specifies the number of entries to retain in the log. Increasing the length allows more entries to be stored but consumes additional memory. To clear all entries for a specific log type and reclaim memory, use the [`COMMANDLOG RESET`](commandlog-reset.md) subcommand followed by the log type. - -See the details of configurations in valkey.conf. - -Each entry from the specific type of command log is comprised of the following six values: - -1. A unique progressive identifier for every entry. -2. The unix timestamp at which the logged command was processed. -3. Each type of command log has its own meaning, currently there are three types: - * time in microseconds for type of slow - * size in bytes for type of large-request - * size in bytes for type of large-reply -4. The array composing the arguments of the command. -5. Client peer information (e.g. Client IP address and port for TCP connected clients or unix path for unix sockets). -6. Client name if set via the [`CLIENT SETNAME`](client-setname.md) command. - -The entry's unique ID can be used in order to avoid processing command log entries multiple times (for instance you may have a script sending you an email alert for every new command log entry). -The ID is never reset in the course of the Valkey server execution, even after [`COMMANDLOG RESET`](commandlog-reset.md) was executed. In order to reset the ID a server restart is needed. diff --git a/commands/commandlog-help.md b/commands/commandlog-help.md deleted file mode 100644 index dcfc7d19..00000000 --- a/commands/commandlog-help.md +++ /dev/null @@ -1 +0,0 @@ -The `COMMANDLOG HELP` command returns a helpful text describing the different subcommands. diff --git a/commands/commandlog-len.md b/commands/commandlog-len.md deleted file mode 100644 index e95fd59b..00000000 --- a/commands/commandlog-len.md +++ /dev/null @@ -1,9 +0,0 @@ -The `COMMANDLOG LEN` command returns the current number of entries in the specified type of command log. - -A new entry is added to the specified command log whenever a command exceeds the corresponding threshold. There are currently three different types of command log, each with an independent threshold, including `commandlog-execution-slower-than`, `commandlog-request-larger-than`, and `commandlog-reply-larger-than`. - -The maximum number of entries in the different command log is governed by the `commandlog-slow-execution-max-len`, `commandlog-large-request-max-len` and `commandlog-large-reply-max-len` configurations. - -Once the command log reaches its maximal size, the oldest entry is removed whenever a new entry is created. - -The command log can be cleared with the [`COMMANDLOG RESET`](commandlog-reset.md) command. diff --git a/commands/commandlog-reset.md b/commands/commandlog-reset.md deleted file mode 100644 index 66d32767..00000000 --- a/commands/commandlog-reset.md +++ /dev/null @@ -1,3 +0,0 @@ -This command resets the specified type of command log, clearing all entries in it. - -Once deleted the information is lost forever. diff --git a/commands/commandlog.md b/commands/commandlog.md deleted file mode 100644 index f7aab3bf..00000000 --- a/commands/commandlog.md +++ /dev/null @@ -1,3 +0,0 @@ -This is a container command for command log management commands. - -To see the list of available commands you can call [`COMMANDLOG HELP`](commandlog-help.md). diff --git a/commands/config-get.md b/commands/config-get.md deleted file mode 100644 index f1abbb7f..00000000 --- a/commands/config-get.md +++ /dev/null @@ -1,45 +0,0 @@ -The `CONFIG GET` command is used to read the configuration parameters of a -running Valkey server. - -The symmetric command used to alter the configuration at run time is [`CONFIG -SET`](config-set.md). - -`CONFIG GET` takes multiple arguments, which are glob-style patterns. -Any configuration parameter matching any of the patterns are reported as a list -of key-value pairs. -In Valkey 9.0 and later, the list is sorted alphabetically by keys. -Example: - -``` -127.0.0.1:6379> config get *max-*-entries* maxmemory - 1) "hash-max-listpack-entries" - 2) "512" - 3) "hash-max-ziplist-entries" - 4) "512" - 5) "maxmemory" - 6) "0" - 7) "set-max-intset-entries" - 8) "512" - 9) "set-max-listpack-entries" -10) "128" -11) "zset-max-listpack-entries" -12) "128" -13) "zset-max-ziplist-entries" -14) "128" -``` - -You can obtain a list of all the supported configuration parameters by typing -`CONFIG GET *` in an open [valkey-cli](../topics/cli.md) prompt. - -All the supported parameters have the same meaning of the equivalent -configuration parameter used in the [valkey.conf][hgcarr22rc] file: - -[hgcarr22rc]: http://github.com/valkey-io/valkey/raw/unstable/valkey.conf - -Note that you should look at the valkey.conf file relevant to the version you're -working with as configuration options might change between versions. The link -above is to the latest development version. - -## Reply - -Map of configuration parameters matching the provided arguments. diff --git a/commands/config-help.md b/commands/config-help.md deleted file mode 100644 index 602d0efe..00000000 --- a/commands/config-help.md +++ /dev/null @@ -1,5 +0,0 @@ -The `CONFIG HELP` command returns a helpful text describing the different subcommands. - -## Reply - -Array of sub-commands and their descriptions. diff --git a/commands/config-info.md b/commands/config-info.md deleted file mode 100644 index eee4b7ac..00000000 --- a/commands/config-info.md +++ /dev/null @@ -1,237 +0,0 @@ -The `CONFIG INFO` command returns metadata about the configuration parameters -that match the given patterns. -It is similar to [`COMMAND INFO`](command-info.md), which returns metadata about -commands. -It is useful for discovering valid values programmatically, for example when -automated tools need to generate parameter values without maintaining -hardcoded enum values or numeric ranges. -To get the current values of configuration parameters, use -[`CONFIG GET`](config-get.md). - -`CONFIG INFO` takes one or more case-insensitive glob-style patterns and returns -one map for each matching configuration parameter. -Results are sorted by name. -A parameter that matches more than one pattern is returned once. -If no parameter matches, the reply is an empty array. - -Each map can contain: - -* `name`: The name of the configuration parameter. -* `type`: The type of the parameter: `bool`, `numeric`, `string`, `enum`, or - `special`. -* `flags`: An array of the flags set on the parameter. -* `alias`: The other name of the parameter. - Only present when the parameter has another name. -* `values`: An array of the valid values. - Only present for `enum` parameters. -* `range`: A two-element array `[min, max]` with the valid bounds, returned as - strings. - Only present for `numeric` parameters. - -The `flags` array can contain: - -* `immutable`: The parameter can only be set at startup, not with - [`CONFIG SET`](config-set.md). -* `sensitive`: The value can contain sensitive information, such as a password. -* `debug`: The parameter is useful for debugging. -* `multi-arg`: The parameter takes multiple arguments. -* `hidden`: The parameter is only matched by its exact name, not by glob-style - patterns. -* `protected`: The parameter can only be changed when - `enable-protected-configs` allows it. -* `deny-loading`: The parameter cannot be changed while the server is loading - data. -* `alias`: This entry is another name for a parameter. -* `module`: The parameter is defined by a module. -* `volatile`: The value refers to data outside the configuration, such as a - file, so setting the same value again still applies it. - -## Parameters with another name - -A parameter that has another name is returned as two separate entries, one for -each name. -For example, `CONFIG INFO *` returns both `replicaof` and `slaveof`. -The entry for the other name lists it in `name` and includes `alias` in its -`flags`. -The entry for the other name is returned both for its exact name and for -glob-style patterns that match it, such as `slave*`. -Tools that only need one entry per parameter can skip the entries with the -`alias` flag. - -## Numeric ranges - -The bounds in `range` are in the parameter's base unit, for example bytes for -memory parameters. -The upper bound of an unsigned parameter can be as large as -`18446744073709551615`. -Some parameters give negative values a special meaning. -For example, `maxmemory-clients` stores a percentage as a negative number, and -`commandlog-request-larger-than` uses `-1` to disable a feature. -`CONFIG INFO` does not report these special meanings, so check the parameter's -description in `valkey.conf`. - -## Enum values - -The `values` array can contain synonyms. -For example, `oom-score-adj` returns `no`, `yes`, `relative`, and `absolute`, -where `yes` and `relative` mean the same thing. -An enum parameter with the `multi-arg` flag, such as `shutdown-on-sigterm`, -accepts several values combined, although not every combination is valid. -For example, `shutdown-on-sigterm` does not accept `save` together with -`nosave`. - -## Special parameters - -Parameters with type `special`, such as `save` and -`client-output-buffer-limit`, have no `values` or `range` field. -Their entries contain `name`, `type`, `flags`, and `alias` when the parameter -has another name. - -## Reply - -Array of maps, one map for each matching configuration parameter. -In RESP2, each map is returned as an array of alternating field names and -values. - -## Examples - -### Enum parameter - -``` -127.0.0.1:6379> CONFIG INFO repl-diskless-load -1) 1) "name" - 2) "repl-diskless-load" - 3) "type" - 4) "enum" - 5) "flags" - 6) 1) "debug" - 2) "deny-loading" - 7) "values" - 8) 1) "disabled" - 2) "on-empty-db" - 3) "swapdb" - 4) "flush-before-load" -``` - -### Numeric parameter - -``` -127.0.0.1:6379> CONFIG INFO timeout -1) 1) "name" - 2) "timeout" - 3) "type" - 4) "numeric" - 5) "flags" - 6) (empty array) - 7) "range" - 8) 1) "0" - 2) "2147483647" -``` - -### Boolean parameter - -``` -127.0.0.1:6379> CONFIG INFO activedefrag -1) 1) "name" - 2) "activedefrag" - 3) "type" - 4) "bool" - 5) "flags" - 6) 1) "debug" -``` - -### String parameter - -``` -127.0.0.1:6379> CONFIG INFO dbfilename -1) 1) "name" - 2) "dbfilename" - 3) "type" - 4) "string" - 5) "flags" - 6) 1) "protected" -``` - -### Special parameter - -``` -127.0.0.1:6379> CONFIG INFO save -1) 1) "name" - 2) "save" - 3) "type" - 4) "special" - 5) "flags" - 6) 1) "multi-arg" -``` - -### Parameter with another name - -``` -127.0.0.1:6379> CONFIG INFO replicaof -1) 1) "name" - 2) "replicaof" - 3) "type" - 4) "special" - 5) "flags" - 6) 1) "immutable" - 2) "multi-arg" - 7) "alias" - 8) "slaveof" -``` - -``` -127.0.0.1:6379> CONFIG INFO slaveof -1) 1) "name" - 2) "slaveof" - 3) "type" - 4) "special" - 5) "flags" - 6) 1) "immutable" - 2) "multi-arg" - 3) "alias" - 7) "alias" - 8) "replicaof" -``` - -### Multiple patterns - -``` -127.0.0.1:6379> CONFIG INFO shutdown-on-* maxmemory -1) 1) "name" - 2) "maxmemory" - 3) "type" - 4) "numeric" - 5) "flags" - 6) (empty array) - 7) "range" - 8) 1) "0" - 2) "18446744073709551615" -2) 1) "name" - 2) "shutdown-on-sigint" - 3) "type" - 4) "enum" - 5) "flags" - 6) 1) "multi-arg" - 7) "values" - 8) 1) "default" - 2) "save" - 3) "nosave" - 4) "now" - 5) "force" - 6) "safe" - 7) "failover" -3) 1) "name" - 2) "shutdown-on-sigterm" - 3) "type" - 4) "enum" - 5) "flags" - 6) 1) "multi-arg" - 7) "values" - 8) 1) "default" - 2) "save" - 3) "nosave" - 4) "now" - 5) "force" - 6) "safe" - 7) "failover" -``` diff --git a/commands/config-resetstat.md b/commands/config-resetstat.md deleted file mode 100644 index 09f021f9..00000000 --- a/commands/config-resetstat.md +++ /dev/null @@ -1,14 +0,0 @@ -Resets the statistics reported by Valkey using the [`INFO`](info.md) and [`LATENCY HISTOGRAM`](latency-histogram.md) commands. - -The following is a non-exhaustive list of values that are reset: - -* Keyspace hits and misses -* Number of expired keys -* Command and error statistics -* Connections received, rejected and evicted -* Persistence statistics -* Active defragmentation statistics - -## Reply - -`OK`. diff --git a/commands/config-rewrite.md b/commands/config-rewrite.md deleted file mode 100644 index 6ae99c7e..00000000 --- a/commands/config-rewrite.md +++ /dev/null @@ -1,19 +0,0 @@ -The `CONFIG REWRITE` command rewrites the `valkey.conf` file the server was started with, applying the minimal changes needed to make it reflect the configuration currently used by the server, which may be different compared to the original one because of the use of the [`CONFIG SET`](config-set.md) command. - -The rewrite is performed in a very conservative way: - -* Comments and the overall structure of the original valkey.conf are preserved as much as possible. -* If an option already exists in the old valkey.conf file, it will be rewritten at the same position (line number). -* If an option was not already present, but it is set to its default value, it is not added by the rewrite process. -* If an option was not already present, but it is set to a non-default value, it is appended at the end of the file. -* Non used lines are blanked. For instance if you used to have multiple `save` directives, but the current configuration has fewer or none as you disabled RDB persistence, all the lines will be blanked. - -CONFIG REWRITE is also able to rewrite the configuration file from scratch if the original one no longer exists for some reason. However if the server was started without a configuration file at all, the CONFIG REWRITE will just return an error. - -## Atomic rewrite process - -In order to make sure the valkey.conf file is always consistent, that is, on errors or crashes you always end with the old file, or the new one, the rewrite is performed with a single `write(2)` call that has enough content to be at least as big as the old file. Sometimes additional padding in the form of comments is added in order to make sure the resulting file is big enough, and later the file gets truncated to remove the padding at the end. - -## Reply - -`OK` when the configuration was rewritten properly. Otherwise an error is returned. diff --git a/commands/config-set.md b/commands/config-set.md deleted file mode 100644 index 7dce3c94..00000000 --- a/commands/config-set.md +++ /dev/null @@ -1,40 +0,0 @@ -The `CONFIG SET` command is used in order to reconfigure the server at run time -without the need to restart Valkey. -You can change both trivial parameters or switch from one to another persistence -option using this command. - -The list of configuration parameters supported by `CONFIG SET` can be obtained -issuing a [`CONFIG GET *`](config-get.md) command, that is the symmetrical command used to obtain -information about the configuration of a running Valkey instance. - -All the configuration parameters set using `CONFIG SET` are immediately loaded -by Valkey and will take effect starting with the next command executed. - -All the supported parameters have the same meaning of the equivalent -configuration parameter used in the [valkey.conf][hgcarr22rc] file. - -[hgcarr22rc]: http://github.com/valkey-io/valkey/raw/unstable/valkey.conf - -Note that you should look at the valkey.conf file relevant to the version you're -working with as configuration options might change between versions. The link -above is to the latest development version. - -It is possible to switch persistence from RDB snapshotting to append-only file -(and the other way around) using the `CONFIG SET` command. -For more information about how to do that please check the [persistence -page][tp]. - -[tp]: ../topics/persistence.md - -In general what you should know is that setting the `appendonly` parameter to -`yes` will start a background process to save the initial append-only file -(obtained from the in memory data set), and will append all the subsequent -commands on the append-only file, thus obtaining exactly the same effect of a -Valkey server that started with AOF turned on since the start. - -You can have both the AOF enabled with RDB snapshotting if you want, the two -options are not mutually exclusive. - -## Reply - -`OK` when the configuration was set properly. Otherwise an error is returned. diff --git a/commands/config.md b/commands/config.md deleted file mode 100644 index 641224b0..00000000 --- a/commands/config.md +++ /dev/null @@ -1,3 +0,0 @@ -This is a container command for runtime configuration commands. - -To see the list of available commands you can call [`CONFIG HELP`](config-help.md). diff --git a/commands/copy.md b/commands/copy.md deleted file mode 100644 index b861eaaa..00000000 --- a/commands/copy.md +++ /dev/null @@ -1,29 +0,0 @@ -This command copies the value stored at the `source` key to the `destination` -key. - -By default, the `destination` key is created in the logical database used by the -connection. The `DB` option allows specifying an alternative logical database -index for the destination key. The `REPLACE` option removes the `destination` -key before copying the value to it. - -The command returns zero when the `source` key does not exist or when the -`destination` key already exists and the `REPLACE` option is not specified. - -When the `DB` option is used, the caller must have ACL permission to access -the specified destination database. See -[database permissions](../topics/acl.md#database-permissions). - -## Reply - -One of the following: - -* Integer: `1` if _source_ was copied. -* Integer: `0` if _source_ was not copied when the destination key already exists. - -## Examples - -``` -SET dolly "sheep" -COPY dolly clone -GET clone -``` diff --git a/commands/dbsize.md b/commands/dbsize.md deleted file mode 100644 index ac057603..00000000 --- a/commands/dbsize.md +++ /dev/null @@ -1,5 +0,0 @@ -Return the number of keys in the currently-selected database. - -## Reply - -Integer: the number of keys in the currently-selected database. diff --git a/commands/debug.md b/commands/debug.md deleted file mode 100644 index 0468abbf..00000000 --- a/commands/debug.md +++ /dev/null @@ -1,2 +0,0 @@ -The `DEBUG` command is an internal command. -It is meant to be used for developing and testing Valkey. \ No newline at end of file diff --git a/commands/decr.md b/commands/decr.md deleted file mode 100644 index a1060b9f..00000000 --- a/commands/decr.md +++ /dev/null @@ -1,24 +0,0 @@ -Decrements the number stored at `key` by one. -If the key does not exist, it is set to `0` before performing the operation. -An error is returned if the key contains a value of the wrong type or contains a -string that can not be represented as integer. -This operation is limited to **64 bit signed integers**. - -See `INCR` for extra information on increment/decrement operations. - -## Reply - -Integer: the value of the key after decrementing it. - -## Examples - -``` -127.0.0.1:6379> SET mykey "10" -OK -127.0.0.1:6379> DECR mykey -(integer) 9 -127.0.0.1:6379> SET mykey "234293482390480948029348230948" -OK -127.0.0.1:6379> DECR mykey -(error) ERR value is not an integer or out of range -``` diff --git a/commands/decrby.md b/commands/decrby.md deleted file mode 100644 index 17babcc5..00000000 --- a/commands/decrby.md +++ /dev/null @@ -1,20 +0,0 @@ -Decrements the number stored at `key` by `decrement`. -If the key does not exist, it is set to `0` before performing the operation. -An error is returned if the key contains a value of the wrong type or contains a -string that can not be represented as integer. -This operation is limited to 64 bit signed integers. - -See `INCR` for extra information on increment/decrement operations. - -## Reply - -Integer: the value of the key after decrementing it. - -## Examples - -``` -127.0.0.1:6379> SET mykey "10" -OK -127.0.0.1:6379> DECRBY mykey 3 -(integer) 7 -``` diff --git a/commands/del.md b/commands/del.md deleted file mode 100644 index 7b9ed274..00000000 --- a/commands/del.md +++ /dev/null @@ -1,17 +0,0 @@ -Removes the specified keys. -A key is ignored if it does not exist. - -## Reply - -Integer: the number of keys that were removed. - -## Examples - -``` -127.0.0.1:6379> SET key1 "Hello" -OK -127.0.0.1:6379> SET key2 "World" -OK -127.0.0.1:6379> DEL key1 key2 key3 -(integer) 2 -``` diff --git a/commands/delex.md b/commands/delex.md deleted file mode 100644 index 8ce0c1b7..00000000 --- a/commands/delex.md +++ /dev/null @@ -1,34 +0,0 @@ -Delete `key` based on condition. - -## Options - -* `IFEQ` *comparison-value* -- Delete the key only if the comparison value matches key's existing value. Error is returned if provided key or value is not string. -* `IFNE` *comparison-value* -- Delete the key only if the comparison value does not matches key's existing value. Error is returned if provided key or value is not string. - -## Reply - -One of the following: - -* Integer: `1` if `key` was deleted. -* Integer: `0` if `key` was not deleted because it did not exist or the value did not follow the condition. - -## Example - -Delete the `key` if given value is equal to existing value. - -``` -127.0.0.1:6379> SET x 1 -OK -127.0.0.1:6379> DELEX x IFEQ 1 -(integer) 1 -``` - -Delete the `key` if given value is not equal to existing value. - -``` -127.0.0.1:6379> SET x 1 -OK -127.0.0.1:6379> DELEX x IFNE 2 -(integer) 1 -``` - diff --git a/commands/delifeq.md b/commands/delifeq.md deleted file mode 100644 index 043ba6bd..00000000 --- a/commands/delifeq.md +++ /dev/null @@ -1,65 +0,0 @@ -Deletes the key if its value matches the given string. - -This command is typically used to safely release locks in distributed systems, ensuring that only the owner of the lock (as identified by the value) can delete it. - -If the key exists and the stored value is a string that exactly matches the provided value, the key is removed and `1` is returned. Otherwise, the key is left unchanged and `0` is returned. - -## Reply - -One of the following: - -* Integer: `1` if the key was deleted. -* Integer: `0` if the key was not deleted because it did not exist or the value was not equal to the provided value. - -## Examples - -Basic usage: - -``` -127.0.0.1:6379> SET mykey abc123 -OK -127.0.0.1:6379> DELIFEQ mykey abc123 -(integer) 1 -127.0.0.1:6379> DELIFEQ mykey abc123 -(integer) 0 -``` - -Wrong value: - -``` -127.0.0.1:6379> SET mykey xyz789 -OK -127.0.0.1:6379> DELIFEQ mykey abc123 -(integer) 0 -``` - -Wrong type: - -``` -127.0.0.1:6379> SADD mykey somevalue -(integer) 1 -127.0.0.1:6379> DELIFEQ mykey somevalue -(error) WRONGTYPE Operation against a key holding the wrong kind of value -``` - -## Use case: Safe lock release - -`DELIFEQ` enables an atomic check-and-delete operation to safely release a lock only if the process still holds it. This avoids race conditions where a lock might expire and be claimed by another process before the original owner tries to delete it. - -This pattern is commonly used as part of distributed locking systems like [Redlock](../topics/distlock.md), which previously relied on Lua scripting to implement this logic. With `DELIFEQ`, such a use case becomes more robust and idiomatic. - -Instead of: - -``` -EVAL "if redis.call('GET',KEYS[1]) == ARGV[1] then return redis.call('DEL',KEYS[1]) else return 0 end" 1 mykey abc123 -``` - -You can now use: - -``` -DELIFEQ mykey abc123 -``` - -## See also - -* [`SET IFEQ`](set.md) - Sets the key only if it matches the given value. diff --git a/commands/discard.md b/commands/discard.md deleted file mode 100644 index 7bfd1709..00000000 --- a/commands/discard.md +++ /dev/null @@ -1,10 +0,0 @@ -Flushes all previously queued commands in a [transaction][tt] and restores the -connection state to normal. - -[tt]: ../topics/transactions.md - -If `WATCH` was used, `DISCARD` unwatches all keys watched by the connection. - -## Reply - -`OK`. diff --git a/commands/dump.md b/commands/dump.md deleted file mode 100644 index 63b924f9..00000000 --- a/commands/dump.md +++ /dev/null @@ -1,38 +0,0 @@ -Serialize the value stored at key in a Valkey-specific format and return it to -the user. -The returned value can be synthesized back into a Valkey key using the [`RESTORE`](restore.md) -command. - -The serialization format is opaque and non-standard, however it has a few -semantic characteristics: - -* It contains a 64-bit checksum that is used to make sure errors will be - detected. - The `RESTORE` command makes sure to check the checksum before synthesizing a - key using the serialized value. -* Values are encoded in the same format used by RDB. -* An RDB version is encoded inside the serialized value, so that different Valkey - versions with incompatible RDB formats will refuse to process the serialized - value. - -The serialized value does NOT contain expire information. -In order to capture the time to live of the current value the [`PTTL`](pttl.md) command -should be used. - -If `key` does not exist a nil bulk reply is returned. - -## Reply - -One of the following: - -* String: the serialized value of the key. -* Null: the key does not exist. - -## Examples - -``` -> SET mykey 10 -OK -> DUMP mykey -"\x00\xc0\n\n\x00n\x9fWE\x0e\xaec\xbb" -``` diff --git a/commands/echo.md b/commands/echo.md deleted file mode 100644 index 9ad210e4..00000000 --- a/commands/echo.md +++ /dev/null @@ -1,12 +0,0 @@ -Returns `message`. - -## Reply - -String: the given string. - -## Examples - -``` -127.0.0.1:6379> ECHO "Hello World!" -"Hello World!" -``` diff --git a/commands/eval.md b/commands/eval.md deleted file mode 100644 index b074be51..00000000 --- a/commands/eval.md +++ /dev/null @@ -1,35 +0,0 @@ -Invoke the execution of a server-side Lua script. - -The first argument is the script's source code. -Scripts are written in [Lua](https://lua.org) and executed by the embedded [Lua 5.1](../topics/lua-api.md) interpreter in Valkey. - -The second argument is the number of input key name arguments, followed by all the keys accessed by the script. -These names of input keys are available to the script as the [_KEYS_ global runtime variable](../topics/lua-api.md#the-keys-global-variable) -Any additional input arguments **should not** represent names of keys. - -**Important:** -to ensure the correct execution of scripts, both in standalone and clustered deployments, all names of keys that a script accesses must be explicitly provided as input key arguments. -The script **should only** access keys whose names are given as input arguments. -Scripts **should never** access keys with programmatically-generated names or based on the contents of data structures stored in the database. - -**Note:** -in some cases, users will abuse Lua EVAL by embedding values in the script instead of providing them as argument, and thus generating a different script on each call to EVAL. -These are added to the Lua interpreter and cached to valkey-server, consuming a large amount of memory over time. -Starting from Valkey 8.0, scripts loaded with `EVAL` or [`EVAL_RO`](eval_ro.md) will be deleted from Valkey after a certain number (least recently used order). -Starting from Valkey 9.2, eviction can also be triggered by the `maxmemory-scripts` limit. See [Script cache semantics](../topics/eval-intro.md#script-cache-semantics). -The number of evicted scripts can be viewed through the `evicted_scripts` field in the `stats` section of the [`INFO`](info.md) command. - -Please refer to the [Valkey Programmability](../topics/programmability.md) and [Introduction to Eval Scripts](../topics/eval-intro.md) for more information about Lua scripts. - -## Reply - -The return value depends on the script that was executed. - -## Examples - -The following example will run a script that returns the first argument that it gets. - -``` -> EVAL "return ARGV[1]" 0 hello -"hello" -``` diff --git a/commands/eval_ro.md b/commands/eval_ro.md deleted file mode 100644 index 56efc271..00000000 --- a/commands/eval_ro.md +++ /dev/null @@ -1,22 +0,0 @@ -This is a read-only variant of the [`EVAL`](eval.md) command that cannot execute commands that modify data. - -For more information about when to use this command vs `EVAL`, please refer to [Read-only scripts](../topics/programmability.md#read-only-scripts). - -For more information about `EVAL` scripts please refer to [Introduction to Eval Scripts](../topics/eval-intro.md). - -## Reply - -The return value depends on the script that was executed. - -## Examples - -``` -> SET mykey "Hello" -OK - -> EVAL_RO "return server.call('GET', KEYS[1])" 1 mykey -"Hello" - -> EVAL_RO "return server.call('DEL', KEYS[1])" 1 mykey -(error) ERR Error running script (call to b0d697da25b13e49157b2c214a4033546aba2104): @user_script:1: @user_script: 1: Write commands are not allowed from read-only scripts. -``` diff --git a/commands/evalsha.md b/commands/evalsha.md deleted file mode 100644 index b62965a7..00000000 --- a/commands/evalsha.md +++ /dev/null @@ -1,10 +0,0 @@ -Evaluate a script from the server's cache by its SHA1 digest. - -The server caches scripts by using the [`SCRIPT LOAD`](script-load.md) command. -The command is otherwise identical to [`EVAL`](eval.md). - -Please refer to the [Valkey Programmability](../topics/programmability.md) and [Introduction to Eval Scripts](../topics/eval-intro.md) for more information about Lua scripts. - -## Reply - -The return value depends on the script that was executed. diff --git a/commands/evalsha_ro.md b/commands/evalsha_ro.md deleted file mode 100644 index 76d4c045..00000000 --- a/commands/evalsha_ro.md +++ /dev/null @@ -1,9 +0,0 @@ -This is a read-only variant of the [`EVALSHA`](evalsha.md) command that cannot execute commands that modify data. - -For more information about when to use this command vs `EVALSHA`, please refer to [Read-only scripts](../topics/programmability.md#read-only-scripts). - -For more information about `EVALSHA` scripts, please refer to [Introduction to Eval Scripts](../topics/eval-intro.md). - -## Reply - -The return value depends on the script that was executed. diff --git a/commands/exec.md b/commands/exec.md deleted file mode 100644 index 24e8547d..00000000 --- a/commands/exec.md +++ /dev/null @@ -1,55 +0,0 @@ -Executes all previously queued commands in a [transaction][tt] and restores the -connection state to normal. - -[tt]: ../topics/transactions.md - -When using `WATCH`, `EXEC` will execute commands only if the watched keys were -not modified, allowing for a [check-and-set mechanism][ttc]. - -[ttc]: ../topics/transactions.md#cas - -## Options - -`EXEC` accepts conditions that are checked before the queued commands run, providing [optimistic locking][ttcond] without `WATCH`: - -[ttcond]: ../topics/transactions.md#exec-conditions - -* `IFEQ` *key* *value* -- Execute only if *key* holds a string equal to *value*. -* `IFNE` *key* *value* -- Execute only if *key* does not exist, or holds a string different from *value*. -* `NX` *key* -- Execute only if *key* does not exist. -* `XX` *key* -- Execute only if *key* exists. - -When multiple conditions are given, all of them must match. -If any condition does not match, or if a `WATCH`ed key was modified, the transaction is discarded and `EXEC` returns a Null reply. - -The transaction is discarded and `EXEC` returns an `EXECABORT` error if `IFEQ` or `IFNE` is used on a key that does not hold a string, if the conditions are malformed, or if the user has no read permission on a condition key. -In cluster mode, condition keys must be in the same hash slot as the keys of the queued commands. - -## Reply - -One of the following: - -* Array: each element being the reply to each of the commands in the atomic transaction. -* Null: the transaction was aborted because a `WATCH`ed key was touched or a condition did not match. - -## Examples - -``` -127.0.0.1:6379> SET version 1 -OK -127.0.0.1:6379> MULTI -OK -127.0.0.1:6379(TX)> SET version 2 -QUEUED -127.0.0.1:6379(TX)> SET data "new data" -QUEUED -127.0.0.1:6379(TX)> EXEC IFEQ version 1 -1) OK -2) OK -127.0.0.1:6379> MULTI -OK -127.0.0.1:6379(TX)> SET version 2 -QUEUED -127.0.0.1:6379(TX)> EXEC IFEQ version 1 -(nil) -``` diff --git a/commands/exists.md b/commands/exists.md deleted file mode 100644 index 851dbf9c..00000000 --- a/commands/exists.md +++ /dev/null @@ -1,22 +0,0 @@ -Returns if `key` exists. - -The user should be aware that if the same existing key is mentioned in the arguments multiple times, it will be counted multiple times. So if `somekey` exists, `EXISTS somekey somekey` will return 2. - -## Reply - -Integer: the number of keys that exist from those specified as arguments. - -## Examples - -``` -127.0.0.1:6379> SET key1 "Hello" -OK -127.0.0.1:6379> EXISTS key1 -(integer) 1 -127.0.0.1:6379> EXISTS nosuchkey -(integer) 0 -127.0.0.1:6379> SET key2 "World" -OK -127.0.0.1:6379> EXISTS key1 key2 nosuchkey -(integer) 2 -``` diff --git a/commands/expire.md b/commands/expire.md deleted file mode 100644 index 44eb2b6d..00000000 --- a/commands/expire.md +++ /dev/null @@ -1,191 +0,0 @@ -Set a timeout on `key`. -After the timeout has expired, the key will automatically be deleted. -A key with an associated timeout is often said to be _volatile_ in Valkey -terminology. - -The timeout will only be cleared by commands that delete or overwrite the -contents of the key, including [`DEL`](del.md), [`SET`](set.md), [`GETSET`](getset.md) and all the `*STORE` -commands. -This means that all the operations that conceptually _alter_ the value stored at -the key without replacing it with a new one will leave the timeout untouched. -For instance, incrementing the value of a key with [`INCR`](incr.md), pushing a new value -into a list with [`LPUSH`](lpush.md), or altering the field value of a hash with [`HSET`](hset.md) are -all operations that will leave the timeout untouched. - -The timeout can also be cleared, turning the key back into a persistent key, -using the [`PERSIST`](persist.md) command. - -If a key is renamed with [`RENAME`](rename.md), the associated time to live is transferred to -the new key name. - -If a key is overwritten by `RENAME`, like in the case of an existing key `Key_A` -that is overwritten by a call like `RENAME Key_B Key_A`, it does not matter if -the original `Key_A` had a timeout associated or not, the new key `Key_A` will -inherit all the characteristics of `Key_B`. - -Note that calling `EXPIRE`/[`PEXPIRE`](pexpire.md) with a non-positive timeout or -[`EXPIREAT`](expireat.md)/[`PEXPIREAT`](pexpireat.md) with a time in the past will result in the key being -[deleted][del] rather than expired (accordingly, the emitted [key event][ntf] -will be `del`, not `expired`). - -[del]: del.md -[ntf]: ../topics/notifications.md - -## Options - -The `EXPIRE` command supports a set of options: - -* `NX` -- Set expiry only when the key has no expiry -* `XX` -- Set expiry only when the key has an existing expiry -* `GT` -- Set expiry only when the new expiry is greater than current one -* `LT` -- Set expiry only when the new expiry is less than current one - -A non-volatile key is treated as an infinite TTL for the purpose of `GT` and `LT`. -The `GT`, `LT` and `NX` options are mutually exclusive. - -## Refreshing expires - -It is possible to call `EXPIRE` using as argument a key that already has an -existing expire set. -In this case the time to live of a key is _updated_ to the new value. -There are many useful applications for this, an example is documented in the -_Navigation session_ pattern section below. - -`EXPIRE` would return 0 and not alter the timeout for a key with a timeout set. - -## Reply - -One of the following: - -* Integer: `0` if the timeout was not set; for example, the key doesn't exist, or the operation was skipped because of the provided arguments. -* Integer: `1` if the timeout was set. - -## Examples - -``` -127.0.0.1:6379> SET mykey "Hello" -OK -127.0.0.1:6379> EXPIRE mykey 10 -(integer) 1 -127.0.0.1:6379> TTL mykey -(integer) 10 -127.0.0.1:6379> SET mykey "Hello World" -OK -127.0.0.1:6379> TTL mykey -(integer) -1 -127.0.0.1:6379> EXPIRE mykey 10 XX -(integer) 0 -127.0.0.1:6379> TTL mykey -(integer) -1 -127.0.0.1:6379> EXPIRE mykey 10 NX -(integer) 1 -127.0.0.1:6379> TTL mykey -(integer) 10 -``` - -## Pattern: Navigation session - -Imagine you have a web service and you are interested in the latest N pages -_recently_ visited by your users, such that each adjacent page view was not -performed more than 60 seconds after the previous. -Conceptually you may consider this set of page views as a _Navigation session_ -of your user, that may contain interesting information about what kind of -products he or she is looking for currently, so that you can recommend related -products. - -You can easily model this pattern in Valkey using the following strategy: every -time the user does a page view you call the following commands: - -``` -MULTI -RPUSH pagewviews.user: http://..... -EXPIRE pagewviews.user: 60 -EXEC -``` - -If the user will be idle more than 60 seconds, the key will be deleted and only -subsequent page views that have less than 60 seconds of difference will be -recorded. - -This pattern is easily modified to use counters using `INCR` instead of lists -using [`RPUSH`](rpush.md). - -# Appendix: Valkey expires - -## Keys with an expire - -Normally Valkey keys are created without an associated time to live. -The key will simply live forever, unless it is removed by the user in an -explicit way, for instance using the `DEL` command. - -The `EXPIRE` family of commands is able to associate an expire to a given key, -at the cost of some additional memory used by the key. -When a key has an expire set, Valkey will make sure to remove the key when the -specified amount of time elapsed. - -The key time to live can be updated or entirely removed using the `EXPIRE` and -[`PERSIST`](persist.md) command (or other strictly related commands). - -## Expire accuracy - -The expire error is from 0 to 1 milliseconds. - -## Expires and persistence - -Keys expiring information is stored in milliseconds. -This means that the time is flowing even when the Valkey instance is not active. - -For expires to work well, the computer time must be taken stable. -If you move an RDB file from two computers with a big desync in their clocks, -funny things may happen (like all the keys loaded to be expired at loading -time). - -Even running instances will always check the computer clock, so for instance if -you set a key with a time to live of 1000 seconds, and then set your computer -time 2000 seconds in the future, the key will be expired immediately, instead of -lasting for 1000 seconds. - -## How Valkey reclaims expired keys - -Valkey reclaims expired keys in two ways: on access and in the background in what is called the "active expire key" cycles. On access expiration is when a client tries to access a key with the expiration time which is found to be timed out. Such a key is deleted on this access attempt. - -Relying solely on the on access expiration only is not enough because there are expired keys that may never be accessed again. To address this, Valkey uses the background expiration algorithm known as the "active expire key" effort. This algorithm is adaptive: it tries to use less CPU if there are few expired keys to reclaim. Otherwise, it gets more aggressive trying to free more memory by reclaiming more keys in shorter runs but using more CPU. - -This is how it works: - -Valkey slowly scans the keyspace to identify and reclaim expired keys. This "slow cycle" is the main way to collect expired keys and operates with the server's hertz frequency (usually 10 hertz). During the slow cycle, Valkey tolerates having not more than 10% of the expired keys in the memory and tries to use a maximum of 25% CPU power. These default values are adjusted if the user changes the active expire key effort configuration. - -If the number of expired keys remains high after the slow cycle, the active expire key effort transitions into the "fast cycle", trying to do less work but more often. The fast cycle runs no longer than 1000 microseconds and repeats at the same interval. During the fast cycle, the check of every database is interrupted once the number of already expired keys in the database is estimated to be lower than 10%. This is done to avoid doing too much work to gain too little memory. - -You can modify the active expire key effort with the `active-expire-effort` parameter in the configuration file up to the maximum value of `10`. The default `active-expire-effort` value is `1`, and it is described by the following base values: - -* `ACTIVE_EXPIRE_CYCLE_KEYS_PER_LOOP` has a base value of 20. The number of keys for each DB loop. -* `ACTIVE_EXPIRE_CYCLE_FAST_DURATION` has a base value of 1000. The maximum duration of the fast cycle in microseconds. -* `ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC` has a base value of 25. The maximum % of CPU to use during the slow cycle. -* `ACTIVE_EXPIRE_CYCLE_ACCEPTABLE_STALE` has a base value of 10. The maximum % of expired keys to tolerate in memory. - -Changing the `active-expire-effort` value results in a lower percentage of expired keys tolerated in memory. However, it will lead to longer cycles and increased CPU usage, which may introduce latency. - -To calculate the new values, use the following formulas: - -* `ACTIVE_EXPIRE_CYCLE_KEYS_PER_LOOP + (ACTIVE_EXPIRE_CYCLE_KEYS_PER_LOOP / 4 * (effort - 1))` -* `ACTIVE_EXPIRE_CYCLE_FAST_DURATION + (ACTIVE_EXPIRE_CYCLE_FAST_DURATION / 4 * (effort - 1))` -* `ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC + (2 * (effort - 1))` -* `ACTIVE_EXPIRE_CYCLE_ACCEPTABLE_STALE - (effort - 1)` - -where `ACTIVE_EXPIRE_CYCLE_KEYS_PER_LOOP`, `ACTIVE_EXPIRE_CYCLE_FAST_DURATION`, `ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC`, and `ACTIVE_EXPIRE_CYCLE_ACCEPTABLE_STALE` are the base values, and `effort` is the specified `active-expire-effort`. - - -## How expires are handled in the replication link and AOF file - -In order to obtain a correct behavior without sacrificing consistency, when a -key expires, a `DEL` operation is synthesized in both the AOF file and gains all -the attached replicas nodes. -This way the expiration process is centralized in the primary instance, and there -is no chance of consistency errors. - -However while the replicas connected to a primary will not expire keys -independently (but will wait for the `DEL` coming from the primary), they'll -still take the full state of the expires existing in the dataset, so when a -replica is elected to primary it will be able to expire the keys independently, -fully acting as a primary. diff --git a/commands/expireat.md b/commands/expireat.md deleted file mode 100644 index da7539a5..00000000 --- a/commands/expireat.md +++ /dev/null @@ -1,48 +0,0 @@ -`EXPIREAT` has the same effect and semantic as [`EXPIRE`](expire.md), but instead of -specifying the number of seconds representing the TTL (time to live), it takes -an absolute [Unix timestamp][hewowu] (seconds since January 1, 1970). A -timestamp in the past will delete the key immediately. - -[hewowu]: http://en.wikipedia.org/wiki/Unix_time - -Please for the specific semantics of the command refer to the documentation of -`EXPIRE`. - -## Background - -`EXPIREAT` was introduced in order to convert relative timeouts to absolute -timeouts for the AOF persistence mode. -Of course, it can be used directly to specify that a given key should expire at -a given time in the future. - -## Options - -The `EXPIREAT` command supports a set of options: - -* `NX` -- Set expiry only when the key has no expiry -* `XX` -- Set expiry only when the key has an existing expiry -* `GT` -- Set expiry only when the new expiry is greater than current one -* `LT` -- Set expiry only when the new expiry is less than current one - -A non-volatile key is treated as an infinite TTL for the purpose of `GT` and `LT`. -The `GT`, `LT` and `NX` options are mutually exclusive. - -## Reply - -One of the following: - -* Integer: `0` if the timeout was not set; for example, the key doesn't exist, or the operation was skipped because of the provided arguments. -* Integer: `1` if the timeout was set. - -## Examples - -``` -127.0.0.1:6379> SET mykey "Hello" -OK -127.0.0.1:6379> EXISTS mykey -(integer) 1 -127.0.0.1:6379> EXPIREAT mykey 1293840000 -(integer) 1 -127.0.0.1:6379> EXISTS mykey -(integer) 0 -``` diff --git a/commands/expiretime.md b/commands/expiretime.md deleted file mode 100644 index 3455206c..00000000 --- a/commands/expiretime.md +++ /dev/null @@ -1,22 +0,0 @@ -Returns the absolute Unix timestamp (since January 1, 1970) in seconds at which the given key will expire. - -See also the [`PEXPIRETIME`](pexpiretime.md) command which returns the same information with milliseconds resolution. - -## Reply - -One of the following: - -* Integer: the expiration Unix timestamp in seconds. -* Integer: `-1` if the key exists but has no associated expiration time. -* Integer: `-2` if the key does not exist. - -## Examples - -``` -127.0.0.1:6379> SET mykey "Hello" -OK -127.0.0.1:6379> EXPIREAT mykey 33177117420 -(integer) 1 -127.0.0.1:6379> EXPIRETIME mykey -(integer) 33177117420 -``` diff --git a/commands/failover.md b/commands/failover.md deleted file mode 100644 index 8e5259a7..00000000 --- a/commands/failover.md +++ /dev/null @@ -1,54 +0,0 @@ -This command will start a coordinated failover between the currently-connected-to primary and one of its replicas. -The failover is not synchronous, instead a background task will handle coordinating the failover. -It is designed to limit data loss and unavailability of the cluster during the failover. -This command is analogous to the [`CLUSTER FAILOVER`](cluster-failover.md) command for non-clustered Valkey and is similar to the failover support provided by sentinel. - -The specific details of the default failover flow are as follows: - -1. The primary will internally start a [`CLIENT PAUSE WRITE`](client-pause.md), which will pause incoming writes and prevent the accumulation of new data in the replication stream. -2. The primary will monitor its replicas, waiting for a replica to indicate that it has fully consumed the replication stream. If the primary has multiple replicas, it will only wait for the first replica to catch up. -3. The primary will then demote itself to a replica. This is done to prevent any dual primary scenarios. NOTE: The primary will not discard its data, so it will be able to rollback if the replica rejects the failover request in the next step. -4. The previous primary will send a special PSYNC request to the target replica, [`PSYNC FAILOVER`](psync.md), instructing the target replica to become a primary. -5. Once the previous primary receives acknowledgement the `PSYNC FAILOVER` was accepted it will unpause its clients. If the PSYNC request is rejected, the primary will abort the failover and return to normal. - -The field `master_failover_state` in [`INFO replication`](info.md) can be used to track the current state of the failover, which has the following values: - -* `no-failover`: There is no ongoing coordinated failover. -* `waiting-for-sync`: The primary is waiting for the replica to catch up to its replication offset. -* `failover-in-progress`: The primary has demoted itself, and is attempting to hand off ownership to a target replica. - -NOTE: -During the `failover-in-progress` phase, the primary first demotes itself to a replica and then notifies the replica to promote itself to primary. -These two steps are an asynchronous process, which may result in the simultaneous existence of two nodes as replicas. -In this scenario, for clients that support REDIRECT (explicitly execute [`CLIENT CAPA REDIRECT`](client-capa.md)), the redirection result may bounce back and forth between the two replicas until the target replica completes the process of promoting itself to primary. -To avoid this situation, during the `failover-in-progress` phase, we temporarily suspend the clients that need to be redirected until the replica truly becomes the primary, and then resume the execution. - -If the previous primary had additional replicas attached to it, they will continue replicating from it as chained replicas. You will need to manually execute a [`REPLICAOF`](replicaof.md) on these replicas to start replicating directly from the new primary. - -## Optional arguments -The following optional arguments exist to modify the behavior of the failover flow: - -* `TIMEOUT` *milliseconds* -- This option allows specifying a maximum time a primary will wait in the `waiting-for-sync` state before aborting the failover attempt and rolling back. -This is intended to set an upper bound on the write outage the Valkey cluster can experience. -Failovers typically happen in less than a second, but could take longer if there is a large amount of write traffic or the replica is already behind in consuming the replication stream. -If this value is not specified, the timeout can be considered to be "infinite". - -* `TO` *HOST* *PORT* -- This option allows designating a specific replica, by its host and port, to failover to. The primary will wait specifically for this replica to catch up to its replication offset, and then failover to it. - -* `FORCE` -- If both the `TIMEOUT` and `TO` options are set, the force flag can also be used to designate that that once the timeout has elapsed, the primary should failover to the target replica instead of rolling back. -This can be used for a best-effort attempt at a failover without data loss, but limiting write outage. - -NOTE: The primary will always rollback if the `PSYNC FAILOVER` request is rejected by the target replica. - -## Failover abort - -The failover command is intended to be safe from data loss and corruption, but can encounter some scenarios it can not automatically remediate from and may get stuck. -For this purpose, the `FAILOVER ABORT` command exists, which will abort an ongoing failover and return the primary to its normal state. -The command has no side effects if issued in the `waiting-for-sync` state but can introduce multi-primary scenarios in the `failover-in-progress` state. -If a multi-primary scenario is encountered, you will need to manually identify which primary has the latest data and designate it as the primary and have the other replicas. - -NOTE: [`REPLICAOF`](replicaof.md) is disabled while a failover is in progress, this is to prevent unintended interactions with the failover that might cause data loss. - -## Reply - -`OK` if the command was accepted and a coordinated failover is in progress. An error if the operation cannot be executed. diff --git a/commands/fcall.md b/commands/fcall.md deleted file mode 100644 index c8bb17bf..00000000 --- a/commands/fcall.md +++ /dev/null @@ -1,32 +0,0 @@ -Invoke a function. - -Functions are loaded to the server with the [`FUNCTION LOAD`](function-load.md) command. -The first argument is the name of a loaded function. - -The second argument is the number of input key name arguments, followed by all the keys accessed by the function. -In Lua, these names of input keys are available to the function as a table that is the callback's first argument. - -**Important:** -To ensure the correct execution of functions, both in standalone and clustered deployments, all names of keys that a function accesses must be explicitly provided as input key arguments. -The function **should only** access keys whose names are given as input arguments. -Functions **should never** access keys with programmatically-generated names or based on the contents of data structures stored in the database. - -Any additional input argument **should not** represent names of keys. -These are regular arguments and are passed in a Lua table as the callback's second argument. - -For more information please refer to the [Valkey Programmability](../topics/programmability.md) and [Introduction to Valkey Functions](../topics/functions-intro.md) pages. - -## Reply - -The return value depends on the function that was executed. - -## Examples - -The following example will create a library named `mylib` with a single function, `myfunc`, that returns the first argument it gets. - -``` -127.0.0.1:6379> FUNCTION LOAD "#!lua name=mylib \n server.register_function('myfunc', function(keys, args) return args[1] end)" -"mylib" -127.0.0.1:6379> FCALL myfunc 0 hello -"hello" -``` diff --git a/commands/fcall_ro.md b/commands/fcall_ro.md deleted file mode 100644 index 923b69f6..00000000 --- a/commands/fcall_ro.md +++ /dev/null @@ -1,9 +0,0 @@ -This is a read-only variant of the [`FCALL`](fcall.md) command that cannot execute commands that modify data. - -For more information about when to use this command vs `FCALL`, please refer to [Read-only scripts](../topics/programmability.md#read-only-scripts). - -For more information please refer to [Introduction to Valkey Functions](../topics/functions-intro.md). - -## Reply - -The return value depends on the function that was executed. diff --git a/commands/flushall.md b/commands/flushall.md deleted file mode 100644 index 454faddd..00000000 --- a/commands/flushall.md +++ /dev/null @@ -1,20 +0,0 @@ -Delete all the keys of all the existing databases, not just the currently selected one. -This command never fails. - -By default, `FLUSHALL` will synchronously flush all the databases. -Setting the **lazyfree-lazy-user-flush** configuration directive to "yes" changes the default flush mode to asynchronous. - -It is possible to use one of the following modifiers to dictate the flushing mode explicitly: - -* `ASYNC`: flushes the databases asynchronously -* `SYNC`: flushes the databases synchronously - -Note: an asynchronous `FLUSHALL` command only deletes keys that were present at the time the command was invoked. Keys created during an asynchronous flush will be unaffected. - -Because `FLUSHALL` operates on every database, the caller must have ACL access -to all databases (the `alldbs` rule). See -[database permissions](../topics/acl.md#database-permissions). - -## Reply - -`OK`. diff --git a/commands/flushdb.md b/commands/flushdb.md deleted file mode 100644 index 1b3c2aa4..00000000 --- a/commands/flushdb.md +++ /dev/null @@ -1,16 +0,0 @@ -Delete all the keys of the currently selected DB. -This command never fails. - -By default, `FLUSHDB` will synchronously flush all keys from the database. -Setting the **lazyfree-lazy-user-flush** configuration directive to "yes" changes the default flush mode to asynchronous. - -It is possible to use one of the following modifiers to dictate the flushing mode explicitly: - -* `ASYNC`: flushes the database asynchronously -* `!SYNC`: flushes the database synchronously - -Note: an asynchronous `FLUSHDB` command only deletes keys that were present at the time the command was invoked. Keys created during an asynchronous flush will be unaffected. - -## Reply - -`OK`. diff --git a/commands/ft._list.md b/commands/ft._list.md deleted file mode 100644 index ebf9ea3e..00000000 --- a/commands/ft._list.md +++ /dev/null @@ -1,19 +0,0 @@ -Lists the currently defined indexes for the current data base. - -``` -FT._LIST -``` - -## Reply - -An array of strings. Each string is the name of an index in the current database. The index names are in no particular order. - -## Examples - -``` -ft._list -1) index -2) products -3) users -4) transactions -``` diff --git a/commands/ft.aggregate.md b/commands/ft.aggregate.md deleted file mode 100644 index a0cdbf34..00000000 --- a/commands/ft.aggregate.md +++ /dev/null @@ -1,158 +0,0 @@ -The `FT.AGGREGATE` command extends the query capabilities of the `FT.SEARCH` command with substantial server-side data processing capabilities. - -The first step of the command is to use the index name and query string to locate a list of Valkey keys. This process is identical to the `FT.SEARCH` command. - -The second step is executed once for each key found in the first step. The contents of the key are extracted as directed by the `LOAD` clause, plus any declared attribute (other than a vector field) that a later stage references as `@`, resulting in a set of name/value pairs which are collected into a record. Thus the output of this step is the working set of records, one record for each key found in the first step. If the query is a KNN query then the initial working set will be sorted by distance, otherwise the working set will be in no particular order. - -The next steps are to execute the list of stages provided on the command, sequentially one at a time. Each step takes as input the working set of records and performs some transformation on it, i.e., the output of one stage is fed into the input of the next stage. - -Once all stages have been executed, the working set of records output from the last stage is returned as the result of the command. - -``` -FT.AGGREGATE - [ADDSCORES] - [DIALECT 2] - [INORDER] - [LOAD * | LOAD [AS ] [ [AS ] ...]] - [PARAMS [ ...]] - [SCORER ] - [SLOP ] - [TIMEOUT ] - [VERBATIM] - [WITHCURSOR [COUNT ] [MAXIDLE ]] - ( - APPLY AS - | FILTER - | GROUPBY [ ... ] [REDUCE [ ...] [AS ] [REDUCE ...]] - | LIMIT - | SORTBY [ASC | DESC] [ [ASC | DESC] ...] [MAX ] - )+ -``` - -- `` (required): This index name you want to query. -- `` (required): The query string, see [Search - query language](../topics/search-query.md) for details. -- `ADDSCORES` (optional): Adds the relevance score computed for each key to its record as the field `__score`, which later stages can reference as `@__score`. -- `DIALECT 2` (optional): Specifies your dialect. The only supported dialect is 2, which is also the default. -- `INORDER` (optional): Indicates that proximity matching of terms must be in order. -- `LOAD * | LOAD [AS ] [ [AS ] ...]` (optional): This controls which fields of those keys are loaded into the working set. A star (\*) indicates that all of the fields of the keys are loaded. The key itself can be loaded by specifying `@__key`. For vector queries, the distance can also be loaded by using its `AS` name (for KNN the default is `___score`). - - `` is a count of the arguments that follow, not a count of fields. An `AS` keyword and its alias each count against ``, so `LOAD 4 @a @b AS c` loads two fields using four arguments. - - Each `` may be a declared attribute name (`@price`), or, for a JSON index, a JSON path (`$.price`). A JSON path that resolves to a declared attribute is loaded as that attribute. - - `AS ` renames the loaded field: it is emitted under `` in the result and is referenced as `@` by later stages. Without an `AS` clause the field is emitted under the name given in the `LOAD` clause (for a JSON attribute this requires `search.emulate-release` 1.3.0 or later; below that it is emitted under its JSON path). An alias may reuse the name of a declared attribute, in which case it hides that attribute for the remainder of the pipeline. If an `AS` alias collides with another output name in the same `LOAD` clause, the command fails; loading the same field twice without `AS` is allowed. - - Honoring `AS` in the `LOAD` clause is a compatibility fix gated on `search.emulate-release` being `1.3.0` or greater; under an emulated release below that, `AS` is treated as an ordinary field name. Accepting a JSON path as `` is not gated, since before it was supported such a load simply failed. See [COMPATIBILITY.md](https://github.com/valkey-io/valkey-search/blob/main/COMPATIBILITY.md) for details. -- `PARAMS [ ...]` (optional): `` is the number of arguments that follow, i.e., twice the number of `name`/`value` pairs. `PARAMS` can be used in both the query string as well as within an expression context. See [Search - query language](../topics/search-query.md) for usage details. -- `SCORER ` (optional): Selects the relevance scoring function used to rank text results. The only supported scorer is `BM25STD`, which is also the default. -- `SLOP ` (optional): Specifies a slop value for proximity matching of terms. -- `TIMEOUT ` (optional): Lets you set a timeout value for the search command. This must be an integer in milliseconds. -- `VERBATIM` (optional): If specified stemming is not applied to term searches. -- `WITHCURSOR [COUNT ] [MAXIDLE ]` (optional): Returns at most `` records and saves the remaining records in a cursor, which is read with [`FT.CURSOR`](ft.cursor.md). `` must be between 1 and `search.cursor-max-count` (default 100000), the default is 1000. `` is the number of milliseconds the cursor may go unread before it is destroyed; it must be between 1 and `search.cursor-max-idle-ms` (default unlimited, see [configurables](../topics/search-configurables.md)), the default is 300000 (or `search.cursor-max-idle-ms` if that is smaller). `WITHCURSOR` may appear anywhere after the query, including between stages. If it is given more than once, the last one is used. See [`FT.CURSOR`](ft.cursor.md) for an example. - -- `APPLY AS ` (optional): An expression is computed and inserted into the record. See [APPLY Stage](#apply-stage) below. See [Search - expressions](../topics/search-expressions.md) for details on the expression syntax. -- `FILTER ` (optional): The filter expression is applied, see [FILTER Stage](#filter-stage) for more details. See [Search - expressions](../topics/search-expressions.md) for details on the expression syntax. -- `GROUPBY [ ...] [REDUCE [ ...] [AS ] ...]` (optional): The working set is grouped into buckets according to the input fields, each written as `@`. `AS ` names the reducer's output; see [Reducers](#reducers) for the default name. One summarization record is generated for each bucket including the outputs of each reducer. See [GROUPBY Stage](#groupby-stage) for details. -- `LIMIT ` (optional): The working set is trimmed, see [LIMIT Stage](#limit-stage) for details. -- `SORTBY [ASC | DESC] [ [ASC | DESC] ...] [MAX ]` (optional): The working set is sorted. See [SORTBY Stage](#sortby-stage) for more details. - -## Processing Stages - -### APPLY Stage - -The `APPLY` stage processes each record of the working set in sequence. For each record the expression is computed with output being set into the record with the provided field name. It is allowed to overwrite an existing field. The apply stage normally keeps every record. With `search.emulate-release` 1.3.0 or later, a record whose expression evaluates to _missing_ is dropped. `exists`, `concat` and `&&` don't produce missing, so `APPLY exists(@f) AS present` keeps the record. See [missing values](../topics/search-expressions.md#primary-values). An expression that fails with an error fails the command. See [COMPATIBILITY.md](https://github.com/valkey-io/valkey-search/blob/main/COMPATIBILITY.md). - -### FILTER Stage - -The `FILTER` stage processes each record of the working set in sequence. For each record the expression is computed. If the expression is false (see [Logical Operators](../topics/search-expressions.md#logical-operators)) the record is discarded, else the record remains. An expression that fails with an error fails the command. - -### LIMIT Stage - -The `LIMIT` stage discards records from the working set based on the provided offset and count. - -### SORTBY Stage - -The `SORTBY` stage reorders the records in accordance with a sort key. A sort key can be constructed using a number of expressions optionally combined with a direction. `` counts the arguments that follow, including each `ASC` or `DESC`, so `SORTBY 2 @price DESC` sorts by one key. - -`SORTBY` keeps at most `MAX` records; without `MAX` it keeps 10. With `search.emulate-release` 1.3.0 or later, `MAX 0` is the same as omitting it, and a `LIMIT ` stage directly before or after the `SORTBY` raises this bound to at least ``+``, so `SORTBY 2 @price ASC LIMIT 100 10` returns records 101-110. Below 1.3.0 only `MAX` sets the bound, so a following `LIMIT` sees at most `MAX` (by default 10) records. See [COMPATIBILITY.md](https://github.com/valkey-io/valkey-search/blob/main/COMPATIBILITY.md). - -### GROUPBY Stage - -The `GROUPBY` stage organizes the input records into buckets based on the values of the specified fields. -For each unique combination of values a separate bucket is created to hold all records that have that combination of values. A field whose value is an array (such as a multi-value JSON field or the output of `TOLIST`) puts the record into one bucket per element, or one per combination when several fields hold arrays; an empty array groups as nil. A record that would go into more than `search.max-group-key-expansion` buckets fails the command. - -Each bucket of records is processed into a single output record, discarding the bucket contents. That output record has two sections. The first section has one value for each of the specified `GROUPBY` fields. This section provides the values that formed (named) this unique bucket. - -The second section is the output of the reducers for that bucket. Reducers provide an efficient mechanism for reducing (summarizing) the contents of a bucket. Each reducer function processes each record of the bucket and generates a single output value which is inserted into the second section of `GROUPBY` output record for this bucket. - -The output of the `GROUPBY` stage is one record for each unique bucket. - -With a `` of 0 (`GROUPBY 0`) no fields are specified and all records go into a single bucket, so the output is one record holding only the reducer outputs, or no record if the working set is empty. - -#### Reducers - -The following reducer functions are available. SUM, AVG, STDDEV and QUANTILE convert their input to a number. A group with no numeric value gives `0` for SUM and AVG, or `nan` with `search.emulate-release` 1.3.0 or later. MIN and MAX do so only with `search.emulate-release` 1.3.0 or later: values that are not numbers are skipped, and a group with no numeric value gives `inf` for MIN and `-inf` for MAX. Below 1.3.0, MIN and MAX compare values as they are, so a `TAG` or text field gives a string, and a group with no value has no MIN or MAX entry in its output record. The other reducers operate on the values as they are. - -Without `AS `, the reducer's output is named from the reducer and its argument. For a reducer whose argument is a single field, such as `REDUCE SUM 1 @Price`, the name is `__generated_aliassumprice` with `search.emulate-release` 1.3.0 or later: `__generated_alias` followed by the reducer name and the field name without `@`, all lowercased. Below 1.3.0 it is `SUM(@Price)`. `FIRST_VALUE` always uses the `FIRST_VALUE()` form. Use `AS` to give the output a stable name for later stages. See [COMPATIBILITY.md](https://github.com/valkey-io/valkey-search/blob/main/COMPATIBILITY.md). - -| Syntax | Function | -| :---------------------------- | :--------------------------------------------------------------------------------------------------------------------------------- | -| COUNT 0 | Number of records | -| COUNT_DISTINCT 1 | The exact number of distinct values of the expression. Caution: this consumes memory proportional to the number of distinct values. | -| COUNT_DISTINCTISH 1 | Approximate number of distinct values using HyperLogLog (P=14), with ~0.81% standard error. Uses at most ~12KB memory per group. Preferred over COUNT_DISTINCT for large groups. Nil values are excluded. | -| SUM 1 | The numerical sum of the values of the expression. | -| MIN 1 | The smallest value of the expression (see above for values that are not numbers). | -| MAX 1 | The largest value of the expression (see above for values that are not numbers). | -| AVG 1 | The numerical average of the values of the expression. | -| STDDEV 1 | The standard deviation the values of the expression. | -| FIRST_VALUE 1 | The first value of the expression encountered in the group. Order depends on record retrieval order. Use only when order does not matter. | -| FIRST_VALUE 3 BY | The value of the first expression from the record with the smallest comparison expression (ascending). Ties broken by first-encountered order. | -| FIRST_VALUE 4 BY ASC\|DESC | The value of the first expression from the record with the minimum (ASC) or maximum (DESC) comparison expression. Ties broken by first-encountered order. Invalid keyword arguments (e.g., wrong BY token or unrecognized direction) produce a parse-time error. | -| RANDOM_SAMPLE 2 | A random sample of values from the expression using reservoir sampling. Returns an array of up to sample_size elements (maximum 1000). Nil values are excluded. Output is non-deterministic. | -| TOLIST 1 | An array of the distinct values of the expression in the group, in first-encountered order. Nil values are skipped; an array value contributes its elements. | -| QUANTILE 2 | An approximation of the value at the given quantile of the expression. `` is a numeric literal from 0 to 1; 0 returns the smallest value and 1 the largest. Nil, NaN and non-numeric strings are ignored. The result is always one of the remaining values: with n values, its position in sorted order (1 for the smallest) differs from `` × n, rounded up and at least 1, by at most 1% of n. For groups of more than 500 values the result can depend on the order in which records are processed. If a group has no remaining numeric values, the result is `nan`. | - -## Reply - -There are two reply formats depending on whether the `WITHCURSOR` option was specified. - -If `WITHCURSOR` was not specified, then the output is an array of N+1 elements, where N is the number of records output by the final processing stage: - -| Element | Type | Contents | -| :------ | :------ | :--------------------------------------- | -| `[0]` | Integer | N, the number of records that follow. | -| `[1]` | Array | The first record: its field/value pairs. | -| ... | | | -| `[N]` | Array | The last record: its field/value pairs. | - -If `WITHCURSOR` was specified, then the output is an array of two elements: - -| Element | Type | Contents | -| :------- | :------ | :---------------------------------------------------------------------------------------------------------------------------------------------------- | -| `[0]` | Array | The records returned by this reply, in N+1 elements: | -| `[0][0]` | Integer | N, the number of records returned. | -| `[0][1]` | Array | The first record: its field/value pairs. | -| ... | | | -| `[0][N]` | Array | The last record: its field/value pairs. | -| `[1]` | Integer | The cursor id to pass to [`FT.CURSOR READ`](ft.cursor.md), or 0 if this reply contains all the remaining records, in which case no cursor is created. | - -## Examples - -Count the products in each category and total their prices, most numerous category first: - -``` -> FT.AGGREGATE idx * GROUPBY 1 @category REDUCE COUNT 0 AS count REDUCE SUM 1 @price AS total SORTBY 2 @count DESC -1) (integer) 2 -2) 1) "category" - 2) "books" - 3) "count" - 4) "3" - 5) "total" - 6) "60" -3) 1) "category" - 2) "toys" - 3) "count" - 4) "2" - 5) "total" - 6) "25" -``` diff --git a/commands/ft.create.md b/commands/ft.create.md deleted file mode 100644 index 0591baea..00000000 --- a/commands/ft.create.md +++ /dev/null @@ -1,198 +0,0 @@ -The `FT.CREATE` command creates an empty index and may initiate the backfill process. Each index consists of a number of -field definitions. Each field definition specifies a field name, a field type and a path within each indexed key to -locate a value of the declared type. Some field type definitions have additional sub-type specifiers. - -For indexes on `HASH` keys, the default path is the same as the hash member name. The optional `AS` clause can be used to rename -the field if desired. - -For indexes on `JSON` keys, the path is a `JSON` path to the data of the declared type. The `AS` clause is required in order to provide a field name without the special characters of a `JSON` path. - -The same source field may be indexed more than once, for example as both `TEXT` and `TAG`, as long as each entry has a distinct `AS` alias. Aliases must be unique within an index. An alias, or the field identifier when `AS` is omitted, may not contain any of the characters `,.<>{}[]"':;!@#$%^&*()-+=~/\|?` (`_` is allowed). - -``` -FT.CREATE - [ON HASH | ON JSON] - [PREFIX [...]] - [FILTER ] - [SCORE ] - [SCORE_FIELD ] - [LANGUAGE ] - [SKIPINITIALSCAN] - [MINSTEMSIZE ] - [NOSTEM] - [WITHOFFSETS | NOOFFSETS] - [NOHL] - [NOSTOPWORDS | STOPWORDS word ...] - [PUNCTUATION ] - SCHEMA - ( - [AS ] - NUMERIC - | TAG [SEPARATOR ] [CASESENSITIVE] - | TEXT [NOSTEM] [WITHSUFFIXTRIE | NOSUFFIXTRIE] [WEIGHT ] - | VECTOR [HNSW | FLAT] [ ]+ - [SORTABLE [UNF]] - )+ -``` - -`ON`, if given, must immediately follow the index name. The other options before `SCHEMA` may appear in any order. `PREFIX` may be given only once. - -- `` (required): This is the name you give to your index. If an index with the same name exists already, an error is returned. - -- `ON HASH | ON JSON` (optional): Only keys that match the specified type are included into this index. If omitted, HASH is assumed. - -- `PREFIX ` (optional): If this clause is specified, then only keys that begin with the same bytes as one or more of the specified prefixes will be included into this index. If this clause is omitted, all keys of the correct type will be included. A zero-length prefix would also match all keys of the correct type. - -- `FILTER ` (optional): A boolean expression evaluated for each candidate key during ingestion; only keys for which it evaluates to true are included in the index. An empty expression is rejected. A comparison that involves a missing field is **false**. So a key with no `status` field matches neither `@status == 'active'` nor `@status != 'active'`. Use `!(@status == 'active')` to include such keys. The number of keys excluded by the filter is reported by `FT.INFO` as `filter_rejected_keys`. - - FILTER expressions always use 1.3.0 expression semantics, regardless of `search.emulate-release`. An index with a `FILTER` records a minimum module version of 1.3.0, so a module older than 1.3.0 refuses to load it. - - ``` - FT.CREATE fr ON HASH PREFIX 1 product: FILTER "@lang == 'french'" LANGUAGE FRENCH SCHEMA title TEXT - ``` - - See [Search - expressions](../topics/search-expressions.md) for details on the expression syntax. - - For a `HASH` index, a field's value reaches the expression as its stored bytes, whatever type the `SCHEMA` declares — a `NUMERIC` field is not a number to a `FILTER`. For a `JSON` index, a `NUMERIC` field is a number, so `@price > @cost` compares numerically; the rest of this paragraph describes `HASH` indexes. A comparison is numeric only when one side really is a number, meaning a bare numeric literal such as `5` or a number-returning function such as `strlen()`. So `@price > 100` compares numerically, while `@price > '100'` and `@price > @cost` compare the values as strings, byte by byte. If one side is a number and the other is a string that is not a number, `==` is false and `!=` is true. `<`, `<=`, `>` and `>=` are an evaluation error, which rejects the key even when the comparison is negated: `!(@price > 100)` does not admit a key whose `price` is not a number. - - Field references use the `@` syntax. For a `HASH` index the expression may reference a field that is **not** declared in the `SCHEMA`; its value is read directly off the key at ingestion time (an absent field makes the comparison false). Because an undeclared field name is read verbatim from the key, a **misspelled** field name does not produce an error — watch `filter_rejected_keys` in `FT.INFO` to detect this. For a `JSON` index every field referenced by the expression must be declared in the `SCHEMA`; referencing an undeclared field is rejected when the index is created. - -- `LANGUAGE ` (optional): For `TEXT` fields, the language used to control lexical parsing and stemming. It selects the stemmer and the default punctuation and stop words. Supported values: `ENGLISH` (default), `ARABIC`, `DUTCH`, `FRENCH`, `GERMAN`, `INDONESIAN`, `ITALIAN`, `PORTUGUESE`, `RUSSIAN`, `SPANISH`, `SWEDISH`, `TURKISH`. Languages other than English require 1.3.0 or later: an index with a non-English `LANGUAGE` cannot be loaded by, or replicated to, modules before 1.3.0. `LANGUAGE_FIELD` is not supported and is rejected. - -- `MINSTEMSIZE ` (optional): For text fields with stemming enabled. This controls the minimum length of a word, in characters (Unicode code points), required for it to be subjected to stemming. The value must be positive; the default value is 4. On English indexes with `search.emulate-release` below 1.3.0, the length is counted in bytes (see COMPATIBILITY.md). - -- `NOSTEM` (optional): Before `SCHEMA`, disables stemming for every `TEXT` field of the index. - -- `WITHOFFSETS | NOOFFSETS` (optional): Enables/Disables the retention of per-word offsets within a text field. Offsets are required to perform exact phrase matching and slop-based proximity matching. Thus if offsets are disabled, those query operations will be rejected with an error. The default is `WITHOFFSETS`. - -- `NOHL` (optional): This parameter is accepted for compatibility, but has no effect. - -- `NOSTOPWORDS | STOPWORDS ...` (optional): Stop words are words which are not put into the indexes. The default value of `STOPWORDS` is language dependent. For `LANGUAGE ENGLISH` the default is: [a, an, and, are, as, at, be, but, by, for, if, in, into, is, it, no, not, of, on, or, such, that, the, their, then, there, these, they, this, to, was, will, with]. Run `FT.INFO` to see the effective `stop_words` and `punctuation` of an index. - -- `PUNCTUATION ` (optional): A string of characters that define the separation points between words, in addition to whitespace characters (spaces, tabs, newlines, carriage returns, and control characters) which always break words. Each character, including a multi-byte one such as `—`, is matched as a whole Unicode code point; before 1.3 each byte of a multi-byte character was matched separately, which also split unrelated characters sharing those bytes. The default value depends on `LANGUAGE`; for English it is `,.<>{}[]"':;!@#$%^&*()-+=~/\|?`. - -- `SKIPINITIALSCAN` (optional): If specified, this option skips the normal backfill operation for an index. If this option is specified, pre-existing keys which match the `PREFIX` clause will not be loaded into the index during a backfill operation. This clause has no effect on processing of key mutations _after_ an index is created, i.e., keys which are mutated after an index is created and satisfy the data type and `PREFIX` clause will be inserted into that index. - -- `SCORE ` (optional): Sets the default document score used for text search ranking. The value must be between 0.0 and 1.0 inclusive (default 1.0). When `SCORE_FIELD` is configured, this value is used as the fallback if a document's score field is missing or cannot be parsed. - -- `SCORE_FIELD ` (optional): Specifies the field whose numeric value is used as the per-document score: a hash field name for a `HASH` index, or a JSON path for a `JSON` index. The field need not be declared in `SCHEMA`. When configured, the value of this field is read during ingestion and stored as the document's relevance score for text search ranking. If the field is missing or cannot be parsed as a valid number, the index-level `SCORE` default is used. The raw value is stored without clamping. See [Search - scoring](../topics/search-scoring.md) for how it is used at query time. - -## Field types - -`TAG`: A tag field is a string that contains one or more tag values. - -- `SEPARATOR ` (optional): A single byte (one ASCII character) used to delimit individual tags. A multi-byte character is rejected. If omitted the default value is `,`. -- `CASESENSITIVE` (optional): If present, tag comparisons will be case sensitive. The default is that tag comparisons are NOT case sensitive. - -See [Tag Field Format](../topics/search-data-formats.md#tag-fields) for more details and examples. - -`TEXT`: A text field is a string that contains words - -- `NOSTEM` (optional): If specified, stemming of words on ingestion is disabled. -- `WITHSUFFIXTRIE | NOSUFFIXTRIE` (optional): Enables/Disables the use of a suffix trie to implement suffix-based wildcard queries. If `NOSUFFIXTRIE` is specified, query strings which specify suffix-based wildcard matching will be rejected with an error. The default is `NOSUFFIXTRIE`; specify `WITHSUFFIXTRIE` to enable suffix (`*word`) queries. -- `WEIGHT ` (optional): The current implementation only allows the value to be 1.0. This parameter is accepted to make valkey-search more interoperable with RediSearch. (default: 1.0) - -See [Text Field Format](../topics/search-data-formats.md#text-fields) for more details and examples. - -`NUMERIC`: A numeric field contains a number. - -See [Numeric Field Format](../topics/search-data-formats.md#numeric-fields) for details and examples. - -`VECTOR`: A vector field contains a vector. Two vector indexing algorithms are currently supported: HNSW (Hierarchical Navigable Small World) and FLAT (brute force). Each algorithm has a set of additional attributes, some required and other optional. - -- `FLAT:` This algorithm provides exact answers, but has runtime proportional to the number of indexed vectors and thus may not be appropriate for large data sets. - - `DIM ` (required): Specifies the number of dimensions in a vector, from 1 to `search.max-vector-dimensions` (default 32768). - - `TYPE [FLOAT32 | FLOAT16 | BFLOAT16]` (required): Element data type. `FLOAT16` and `BFLOAT16` halve the memory used per vector at some cost in precision; see [Supported Data Types](../topics/search-data-formats.md#supported-data-types). - - `DISTANCE_METRIC [L2 | IP | COSINE]` (required): Specifies the distance algorithm - - `INITIAL_CAP ` (optional): Initial index size. The default is 10240; the range is 1 to 10000000. - - `BLOCK_SIZE ` (optional): Number of vectors by which the index capacity grows when it is full. The default is 1024; the range is 1 to 10000000. -- `HNSW:` The HNSW algorithm provides approximate answers, but operates substantially faster than `FLAT`. - - `DIM ` (required): Specifies the number of dimensions in a vector, from 1 to `search.max-vector-dimensions` (default 32768). - - `TYPE [FLOAT32 | FLOAT16 | BFLOAT16]` (required): Element data type. `FLOAT16` and `BFLOAT16` halve the memory used per vector at some cost in precision; see [Supported Data Types](../topics/search-data-formats.md#supported-data-types). - - `INITIAL_CAP ` (optional): Initial index size. The default is 10240; the range is 1 to 10000000. - - `M ` (optional): Number of maximum allowed outgoing edges for each node in the graph in each layer. on layer zero the maximal number of outgoing edges will be 2\*M. Default is 16, the minimum is 2. The maximum is set by `search.max-vector-m`. - - `EF_CONSTRUCTION ` (optional): controls the number of vectors examined during index construction. Higher values for this parameter will improve recall ratio at the expense of longer index creation times. The default value is 200. The maximum is set by `search.max-vector-ef-construction`. - - `EF_RUNTIME ` (optional): Controls HNSW search effort. Higher values can improve recall at the expense of longer query times. The default is 10. The maximum is set by `search.max-vector-ef-runtime`. A query can override the field value. - - `DISTANCE_METRIC [L2 | IP | COSINE]` (required): Specifies the distance algorithm. - -See [Vector Field Format](../topics/search-data-formats.md#vector-fields) for more details and examples. - -The KNN search algorithm finds the vectors nearest to the query vector, which are the vectors with the smallest distance. -For the distance formula of each metric, see [Vector Distance](../topics/search-scoring.md#vector-distance). - -### Field options - -`SORTABLE` (optional): This parameter is not required. Any field may be used with `SORTBY` whether or not it is declared `SORTABLE`. It is recorded on the attribute and reported by [`FT.INFO`](ft.info.md), but does not otherwise affect indexing or query behavior. `SORTABLE` on a `VECTOR` field is accepted but has no effect and is not reported. - -- `UNF` (optional): Only valid immediately after `SORTABLE`. In RediSearch this keeps the sort value of a `SORTABLE` field in its original form instead of converting it to lowercase. `SORTBY` never converts the sort value to lowercase, so this has no effect beyond being reported by [`FT.INFO`](ft.info.md). It is accepted on any field type, but reported by `FT.INFO` only for `TAG` and `TEXT`. - -## Reply - -`OK`. - -If an error occurs during the index creation, an error is returned. - -## Examples - -### HNSW example: - -``` -FT.CREATE my_index_name SCHEMA my_hash_field_key VECTOR HNSW 10 TYPE FLOAT32 DIM 20 DISTANCE_METRIC COSINE M 4 EF_CONSTRUCTION 100 -``` - -Result: - -``` -OK -``` - -### FLAT example: - -``` -FT.CREATE my_index_name SCHEMA my_hash_field_key VECTOR FLAT 8 TYPE FLOAT32 DIM 20 DISTANCE_METRIC COSINE INITIAL_CAP 15000 -``` - -Result: - -``` -OK -``` - -### Same field indexed as TEXT and TAG: - -``` -FT.CREATE my_index_name SCHEMA sku AS sku_text TEXT sku AS sku_tag TAG -``` - -Result: - -``` -OK -``` - -### HNSW example with a numeric field: - -``` -FT.CREATE my_index_name SCHEMA my_vector_field_key VECTOR HNSW 10 TYPE FLOAT32 DIM 20 DISTANCE_METRIC COSINE M 4 EF_CONSTRUCTION 100 my_numeric_field_key NUMERIC -``` - -Result: - -``` -OK -``` - -### HNSW example with multiple tag and numeric fields - -``` -FT.CREATE my_index_name SCHEMA my_vector_field_key VECTOR HNSW \ - 10 TYPE FLOAT32 DIM 20 DISTANCE_METRIC COSINE M 4 EF_CONSTRUCTION \ - 100 my_tag_field_key_1 TAG SEPARATOR '@' CASESENSITIVE \ - my_numeric_field_key_1 NUMERIC my_numeric_field_key_2 NUMERIC my_tag_field_key_2 TAG -``` - -Result: - -``` -OK -``` diff --git a/commands/ft.cursor.md b/commands/ft.cursor.md deleted file mode 100644 index 61e76c0d..00000000 --- a/commands/ft.cursor.md +++ /dev/null @@ -1,64 +0,0 @@ -Reads more rows from, or deletes, a cursor created by the `WITHCURSOR` option of [`FT.AGGREGATE`](ft.aggregate.md), [`FT.HYBRID`](ft.hybrid.md) or [`FT.SEARCH`](ft.search.md). - -``` -FT.CURSOR READ [COUNT ] -FT.CURSOR DEL -``` - -- `` (required): The name of an existing index. As in Redis, it need not be the index the cursor was created on. -- `` (required): The cursor id returned by the command that created the cursor, or by a previous `FT.CURSOR READ`. -- `COUNT ` (optional): The maximum number of rows to return. It must be between 1 and `search.cursor-max-count` (default 100000, see [configurables](../topics/search-configurables.md)). Without it the cursor's current read size is used, which starts as the `COUNT` of the `WITHCURSOR` clause that created the cursor (itself 1000 when that clause gave no `COUNT`). Giving a `COUNT` replaces that read size for later reads of this cursor, as in Redis. - -A cursor holds the rows of a query result that have not yet been returned to the client, as of when the query ran: later changes to the data are not visible. A cursor belongs to the database it was created in: it can only be read or deleted by a connection whose currently selected database is that database. If `SWAPDB` moves the cursor's index to another database, its cursors move with it. In cluster mode a cursor exists only on the node that executed the query. - -Reading or deleting a cursor requires the same key permissions as querying its index: a user who could not run the query that created the cursor cannot read or delete it either. - -A cursor is destroyed when its last row has been read, when it is deleted with `FT.CURSOR DEL`, when it has not been read for longer than its `MAXIDLE` time, or when its index is removed (`FT.DROPINDEX`, `FLUSHDB`, `FLUSHALL`, or a replica synchronizing with its primary). Reading a cursor restarts its idle time. - -## Reply - -`FT.CURSOR READ` returns a two element array. The same format is used for cursors created by `FT.AGGREGATE`, `FT.HYBRID` and `FT.SEARCH`. - -| Element | Type | Contents | -| :------- | :------ | :--------------------------------------------------------------------------------------------------------------------------------------------------- | -| `[0]` | Array | The rows returned by this read, in N+1 elements: | -| `[0][0]` | Integer | N, the number of rows returned by this read. | -| `[0][1]` | Array | The first row. | -| ... | | | -| `[0][N]` | Array | The last row. | -| `[1]` | Integer | The cursor id to use for the next `FT.CURSOR READ`, or 0 if this reply contains all the remaining rows, in which case the cursor has been destroyed. | - -A row of an `FT.AGGREGATE` or `FT.HYBRID` cursor is an array of field/value pairs. A row of an `FT.SEARCH` cursor is an array containing the elements for one key of a non-cursor `FT.SEARCH` response, i.e. the key name followed by the optional score, the optional sort key and the array of field/value pairs. - -`FT.CURSOR DEL` returns OK. It applies the same checks as `FT.CURSOR READ`: `` must name an existing index, which need not be the cursor's own, the cursor must belong to the currently selected database, and the user must have permission to read the cursor's index. - -### Errors - -- `Index with name '' not found in database ` (`READ` and `DEL`): the named index does not exist. -- `Cursor not found, id: ` (`READ`) / `Cursor does not exist` (`DEL`): there is no such cursor in this database, including a cursor discarded because its index was removed. -- `The user does not have permission to access the key prefix...` (`READ` and `DEL`): the user may not read the cursor's index. -- `The index was dropped while the cursor was idle` (`READ` only): the cursor's index was replaced between the cursor's creation and this read. - -## Examples - -``` -> FT.AGGREGATE idx @price:[-inf inf] LOAD 1 @price SORTBY 2 @price ASC WITHCURSOR COUNT 2 -1) 1) (integer) 2 - 2) 1) "price" - 2) "10" - 3) 1) "price" - 2) "20" -2) (integer) 8481957688249417729 -> FT.CURSOR READ idx 8481957688249417729 COUNT 2 -1) 1) (integer) 2 - 2) 1) "price" - 2) "30" - 3) 1) "price" - 2) "40" -2) (integer) 8481957688249417729 -> FT.CURSOR READ idx 8481957688249417729 -1) 1) (integer) 1 - 2) 1) "price" - 2) "50" -2) (integer) 0 -``` diff --git a/commands/ft.dropindex.md b/commands/ft.dropindex.md deleted file mode 100644 index 20cffc54..00000000 --- a/commands/ft.dropindex.md +++ /dev/null @@ -1,13 +0,0 @@ -Drop the index created earlier by `FT.CREATE` command. It is an error if the index doesn't exist. - -``` -FT.DROPINDEX -``` - -- `` (required): The name of the index to delete. - -`RESPONSE` OK or Error. - -## Reply - -`OK`. diff --git a/commands/ft.hybrid.md b/commands/ft.hybrid.md deleted file mode 100644 index d9bc5d63..00000000 --- a/commands/ft.hybrid.md +++ /dev/null @@ -1,225 +0,0 @@ -The `FT.HYBRID` command runs two searches over one index and combines their results into a single ranked list. - -The first search is the `SEARCH` arm: a text, tag or numeric query, scored for relevance the way `FT.SEARCH` scores one. The second is the `VSIM` arm: a vector similarity search, scored by distance. Each arm ranks its own matches independently. - -The two ranked lists are then fused into one. Fusion is what makes this a hybrid search rather than two searches: a document that both arms found is rewarded for appearing in both, and the `COMBINE` clause decides how the two arms' scores are weighed against each other. - -The fused list is then fed through the same processing stages as `FT.AGGREGATE`, so the result can be projected, filtered, grouped, sorted and trimmed before it is returned. - -Unlike `FT.AGGREGATE`, which returns every record, `FT.HYBRID` returns at most 10 records when the command writes no `LIMIT` clause. An explicit `LIMIT` stays where it is written in the pipeline; only the default is appended, so it runs after every other stage. - -`FT.HYBRID` is new in 1.3.0, so it parses the command and runs its processing stages with the 1.3.0 behavior of every fix gated by `search.emulate-release`, whatever that setting is. At the default setting, the same stage can therefore give a different result in `FT.HYBRID` than in `FT.AGGREGATE`: `APPLY 2^3^2` gives 512 in `FT.HYBRID` and 64 in `FT.AGGREGATE`. See [COMPATIBILITY.md](https://github.com/valkey-io/valkey-search/blob/main/COMPATIBILITY.md). - -``` -FT.HYBRID - SEARCH [SCORER ] [YIELD_SCORE_AS ] - VSIM @ $ [KNN [K ] [EF_RUNTIME ] [SHARD_K_RATIO ]] - [FILTER [] - [POLICY (ADHOC | BATCHES [BATCH_SIZE ])]] - [YIELD_SCORE_AS ] - [COMBINE - ( RRF [CONSTANT ] [WINDOW ] [YIELD_SCORE_AS ] - | LINEAR [ALPHA BETA ] [WINDOW ] [YIELD_SCORE_AS ] - | FUNCTION EXPR [WINDOW ] [YIELD_SCORE_AS ] - )] - [DIALECT 2] - [LOAD * | LOAD [AS ] [ [AS ] ...]] - [PARAMS [ ...]] - [TIMEOUT ] - [WITHCURSOR [COUNT ] [MAXIDLE ]] - ( - | APPLY AS - | FILTER - | GROUPBY [ ... ] [REDUCE [ ...] [AS ] [REDUCE ...]] - | LIMIT - | SORTBY [ASC | DESC] [ [ASC | DESC] ...] [MAX ] - )* -``` - -- `` (required): The index to query. Both arms search the same index. -- `SEARCH ` (required): The non-vector arm. `` is any query the search parser accepts, see [Search - query language](../topics/search-query.md). A vector query is rejected here — the vector search is the `VSIM` clause's job. - - `SCORER ` (optional): The relevance scorer for this arm. The only supported scorer now is `BM25STD`, which is also the default. - - `YIELD_SCORE_AS ` (optional): Emits this arm's score under ``, making it available to `COMBINE FUNCTION` and to the processing stages. -- `VSIM @ $` (required): The vector arm. `@` names a vector attribute of the index; the `@` is required. `$` names a `PARAMS` entry that holds the query vector as a binary blob, which must be exactly the size the field's type and dimension call for; the `$` is required. The vector cannot be written inline. - - `KNN [K ] [EF_RUNTIME ] [SHARD_K_RATIO ]` (optional): The vector search parameters. `` is a count of the arguments that follow within the block, not a count of parameters. `K` is the number of nearest neighbors to retrieve, between 1 and `search.max-vector-knn` (default 10000), and defaults to 10. The `VSIM` arm never contributes more than `K` documents to fusion, whatever the `WINDOW`. Omitting the whole block, or writing `KNN 0`, is the same as taking every default. `EF_RUNTIME` tunes the HNSW search breadth. `SHARD_K_RATIO` is accepted for compatibility and ignored. - - `FILTER ` or `FILTER [POLICY ...]` (optional): A pre-filter, written in the [query language](../topics/search-query.md). The vector search considers only documents that match it. The filter decides membership only: this arm's score is still the vector similarity, never a text score. - - `` counts every token after it, the expression included, as in `FILTER 3 "@cat:{shoes}" POLICY ADHOC`. It may be left out when the filter is a bare expression, and is required when `POLICY` is given. - - `POLICY ADHOC`: filter first, then compute exact distances. Cannot be combined with `EF_RUNTIME`. - - `POLICY BATCHES [BATCH_SIZE ]`: run the vector search first and filter inline. `BATCH_SIZE` is allowed only here, and its value is ignored. - - Without `POLICY` the query planner chooses. With a wildcard expression (`FILTER 3 * POLICY ...`) there is nothing to filter, so either policy runs a plain KNN search, as Redis does. - - The policy values are literal tokens, not `PARAMS` references. - - A `FILTER` that directly follows the `VSIM` clause is always this pre-filter, in query syntax, even when it was meant as a processing stage. `VSIM @vec $q FILTER "@price > 10"` is therefore an error. To filter the fused results with an expression, put the `FILTER` stage after `COMBINE`, `LOAD` or another stage. If more than one `FILTER` follows `VSIM`, only the last one is used. - - `YIELD_SCORE_AS ` (optional): As for the `SEARCH` arm. The value is this arm's similarity, as described in [Fusion methods](#fusion-methods), not the raw distance `FT.SEARCH` reports. -- `COMBINE` (optional): How the two arms' results are fused. Defaults to `RRF` with its own defaults when the clause is absent. In every form, `` is a count of the arguments that follow within the clause, not a count of sub-arguments; sub-arguments may appear in any order. See [Fusion methods](#fusion-methods) below. -- `DIALECT 2` (optional): Specifies your dialect. The only supported dialect is 2, which is also the default. -- `LOAD * | LOAD [AS ] [...]` (optional): Which fields of the matched keys are loaded into the working set, exactly as for `FT.AGGREGATE`. Without a `LOAD` clause the result carries the key, the fused score, and any per-arm scores that were named. `AS ` is always honored. -- `PARAMS [...]` (optional): `` is the number of arguments, i.e. twice the number of name/value pairs. Used to supply the `VSIM` query vector. A `$name` reference inside either arm's query text is not substituted — the same limitation `FT.SEARCH` and `FT.AGGREGATE` have. -- `TIMEOUT ` (optional): A timeout for the command, in milliseconds. It must not exceed `search.max-timeout-ms` (default 60000). The default is the value of `search.default-timeout-ms` (50000). -- `WITHCURSOR [COUNT ] [MAXIDLE ]` (optional): Returns at most `` records and saves the remaining records in a cursor, which is read with [`FT.CURSOR`](ft.cursor.md), exactly as for [`FT.AGGREGATE`](ft.aggregate.md). `` must be between 1 and `search.cursor-max-count`, the default is 1000. `` is the number of milliseconds the cursor may go unread before it is destroyed; it must be between 1 and `search.cursor-max-idle-ms`, the default is 300000 (or `search.cursor-max-idle-ms` if that is smaller). `WITHCURSOR` may appear anywhere among the clauses that follow `SEARCH`, `VSIM` and `COMBINE`, and ends any of those three clauses the way `LOAD` does. If it is given more than once, the last one is used. A cursor is no exception to the cancellation rules: a query cancelled by its `TIMEOUT` is an error, as it is without `WITHCURSOR`. The cursor pages through the records the command would have returned without `WITHCURSOR`, so the default `LIMIT` of 10 described above still applies. -- `APPLY`, `FILTER`, `GROUPBY`, `LIMIT`, `SORTBY` (optional): The `FT.AGGREGATE` processing stages, applied to the fused list in the order written. See [FT.AGGREGATE](ft.aggregate.md#processing-stages) for what each stage does. - -## Fusion methods - -Fusion sees each arm's results ranked best-first. The `VSIM` arm's distance, defined in [Vector Distance](../topics/search-scoring.md#vector-distance), is converted to a similarity before fusion: - -- `L2`: the similarity is `1 / (1 + distance)`, so a nearer document scores higher. -- `COSINE`: the similarity is `1 - distance / 2`, so a nearer document scores higher. -- `IP`: the similarity is `(1 + distance) / 2`, so a nearer document scores lower. - -`RRF` uses only the ranks and is not affected. `LINEAR` and `FUNCTION` use the similarity value directly, so on an `IP` index a positive `BETA` favors farther documents. - -### RRF - -``` -COMBINE RRF [CONSTANT ] [WINDOW ] [YIELD_SCORE_AS ] -``` - -Reciprocal Rank Fusion scores a document by its _rank_ in each arm rather than by the arm's score, which makes it insensitive to the two arms producing scores on entirely different scales. A document at position `r` in an arm, counting from 1 for the arm's best result, contributes `1 / (c + r)`, and the contributions from both arms are summed. With the default constant, a document that is first in both arms scores `2/61`. - -- `CONSTANT ` (optional, default `60`): The `c` above. A larger constant flattens the difference between ranks. Must be a non-negative finite number; fractional values are honored. -- `WINDOW ` (optional, default `20`): How many of each arm's top results take part in fusion. - -This is the default method: a command with no `COMBINE` clause fuses with `RRF` using these defaults. - -### LINEAR - -``` -COMBINE LINEAR [ALPHA BETA ] [WINDOW ] [YIELD_SCORE_AS ] -``` - -A weighted sum of the arms' raw scores: `a * search_score + b * vector_similarity`. A document absent from an arm contributes nothing from it. - -- `ALPHA ` (optional, default `0.3`): The weight applied to the `SEARCH` arm. -- `BETA ` (optional, default `0.7`): The weight applied to the `VSIM` arm. -- `WINDOW ` (optional, default `20`): As for `RRF`. - -The two weights are optional together, not individually. Writing neither takes the defaults above, so `COMBINE LINEAR 0` fuses exactly as `COMBINE LINEAR 4 ALPHA 0.3 BETA 0.7` does. Writing exactly one is an error: the other is not defaulted for it, because a half-written pair is much more likely to be a typo than a request for a default. - -Any finite value is accepted, including negative values and values greater than 1. - -The scores are used as they stand, with no per-arm normalization. Normalizing would make a document's fused score depend on which _other_ documents happened to come back in the same arm, so the same document against the same query would score differently as the corpus around it changed. Use `ALPHA` and `BETA` to balance the arms instead. - -### FUNCTION - -``` -COMBINE FUNCTION EXPR [WINDOW ] [YIELD_SCORE_AS ] -``` - -The fused score is whatever your expression computes from the arms' scores. This is a valkey-search extension. - -- `EXPR ` (required): An expression over the per-arm scores. See [Search - expressions](../topics/search-expressions.md) for the syntax. -- `WINDOW ` (optional): Defaults to the widest window allowed rather than to 20, because a user expression is normally expected to see every candidate. - -Each arm's score is reachable from the expression three ways: by the arm's own `YIELD_SCORE_AS` alias, by position as `@__arm0_score` and `@__arm1_score`, and — for the standard two-arm shape — as `@__search_score` and `@__vector_score`. - -``` -FT.HYBRID idx - SEARCH "@title:running shoes" YIELD_SCORE_AS s - VSIM @embedding $q KNN 2 K 10 YIELD_SCORE_AS v - COMBINE FUNCTION 4 EXPR "@s * 10 + @v" YIELD_SCORE_AS score - PARAMS 2 q -``` - -An arm that did not return a given document has no score for it, and an expression that reads a missing arm score evaluates to 0 for that document as a whole — not merely for that term. `@v * 0 + 100` yields 0, not 100, for a document the vector arm did not return. Guard with `exists(@alias)`, which is 0 for a missing score and 1 otherwise, if such a document should keep a non-zero fused score. - -### Defaults - -| Setting | Default | Notes | -|---|---|---| -| Fusion method | `RRF` | Used when there is no `COMBINE` clause. | -| `RRF CONSTANT` | `60` | Non-negative, finite; fractional values allowed. | -| `RRF` and `LINEAR` `WINDOW` | `20` | `WINDOW 0` means as wide as allowed. | -| `FUNCTION` `WINDOW` | As wide as allowed | | -| `LINEAR ALPHA` / `BETA` | `0.3` / `0.7` | Give both or neither. | -| Fused score name | `__score` | Renamed by `COMBINE ... YIELD_SCORE_AS`. | - -### WINDOW - -`WINDOW` bounds how many of each arm's top results take part in fusion. It is a per-arm count, so with two arms the fused list can hold up to twice the window before the processing stages run. The `VSIM` arm returns at most `K` results, so a window larger than `K` does not bring in more vector results: raise `K` together with `WINDOW`. - -## Score naming - -The fused score is emitted under `__score` unless `COMBINE ... YIELD_SCORE_AS` names it otherwise. - -`__key` is reserved and cannot be used as a score alias anywhere. - -An alias cannot be empty. - -`__score` cannot be used by `COMBINE ... YIELD_SCORE_AS` when the command has no `LOAD` clause, because that is already the name of the default score column; give the score a different name, or add a `LOAD` clause. - -A per-arm `YIELD_SCORE_AS` alias must differ from the fused score's name: `__score`, or the `COMBINE ... YIELD_SCORE_AS` alias if one is given. For example, `SEARCH ... YIELD_SCORE_AS fs ... COMBINE RRF 2 YIELD_SCORE_AS fs` is rejected. - -A score alias, per-arm or fused, cannot be the same as a column that a named `LOAD` list emits, including a name given with `AS`. Under `LOAD *`, a document field with the same name as a score alias is replaced by the score. - -A per-arm alias is missing from a record when that arm did not return the document. Under `LOAD *`, per-arm aliases cannot be referenced by the processing stages. - -## Reply - -The reply has the same structure as the [`FT.AGGREGATE` reply](ft.aggregate.md#reply), with and without `WITHCURSOR`; see that page for details. As there, N is the number of records returned, not the total number of matches. - -Without a `LOAD` clause every record carries `__key` and the fused score, under `__score` or under the alias given by `COMBINE ... YIELD_SCORE_AS`. A `LOAD` clause replaces those two implicit columns with the fields it names: load `@__key` to keep the key, and either name the fused score with `COMBINE ... YIELD_SCORE_AS` or list `@__score` in the `LOAD` clause to keep it. Per-arm scores appear under their own `YIELD_SCORE_AS` aliases either way. - -Unless a `SORTBY` stage orders them otherwise, records are returned by fused score, highest first. The fused score is stored as a 32-bit float. - -## Example - -An index with a text field and a 2-dimensional `FLOAT32` vector field, and three documents: - -``` -FT.CREATE idx ON HASH PREFIX 1 doc: SCHEMA title TEXT vec VECTOR FLAT 6 TYPE FLOAT32 DIM 2 DISTANCE_METRIC L2 -HSET doc:1 title "red running shoes" vec "\x00\x00\x00\x00\x00\x00\x00\x00" -HSET doc:2 title "blue sandals" vec "\x00\x00\x80\x3f\x00\x00\x00\x00" -HSET doc:3 title "running shorts" vec "\x00\x00\xa0\x40\x00\x00\xa0\x40" -``` - -The vectors are `[0, 0]`, `[1, 0]` and `[5, 5]`. The query matches `shoes` in the text arm and asks for the two nearest neighbors of `[0, 0]` in the vector arm, fusing with the default `RRF`: - -``` -FT.HYBRID idx SEARCH "@title:shoes" YIELD_SCORE_AS ts VSIM @vec $q KNN 2 K 2 YIELD_SCORE_AS vs PARAMS 2 q "\x00\x00\x00\x00\x00\x00\x00\x00" -``` - -``` -1) (integer) 2 -2) 1) "__key" - 2) "doc:1" - 3) "__score" - 4) "0.0327868834138" - 5) "ts" - 6) "1.75636863708" - 7) "vs" - 8) "1" -3) 1) "__key" - 2) "doc:2" - 3) "__score" - 4) "0.0161290317774" - 5) "vs" - 6) "0.5" -``` - -`doc:1` is first in both arms, so it scores `1/61 + 1/61`. `doc:2` is second in the vector arm only, so it scores `1/62` and has no `ts`. Its `vs` is the L2 similarity `1 / (1 + 1)`. `doc:3` is in neither arm. - -## Cluster behavior - -- `FT.HYBRID` takes no `SOMESHARDS`, `ALLSHARDS`, `CONSISTENT` or `INCONSISTENT` arguments. Partial and consistent results follow the `search.enable-partial-results` and `search.enable-consistent-results` configurations. -- A shard where either arm fails is dropped for both arms: none of that shard's results from the other arm are fused either. An arm that no shard answered is an error, even when partial results are enabled. A cluster consistency failure is always an error. -- Each shard is asked for up to `max(WINDOW, 10)` results for the `SEARCH` arm and `max(K, WINDOW)` for the `VSIM` arm. A `COMBINE FUNCTION` with no `WINDOW` asks each shard for up to the widest window allowed, which can be costly. -- In cluster mode each arm is checked against concurrent writes on its own shard, so on a given shard the two arms can see different write states. -- Text scores are computed per shard; see [Per-Shard Values](../topics/search-scoring.md#per-shard-values). - -## Common errors - -- `VSIM vector field must start with '@', got ...` or `VSIM vector parameter must start with '$', got ...`: write `VSIM @ $`. -- `Parameter not found.`: the `$` named by `VSIM` has no `PARAMS` entry. -- `Error parsing vector similarity parameters: query vector blob size (...) does not match index's expected size (...).`: the blob does not match the field's type and dimension. -- `A vector query is not supported in the SEARCH clause; use VSIM`: the vector search belongs in the `VSIM` clause. -- `Invalid filter expression: ...`: often an expression-language `FILTER` placed directly after `VSIM`, where it is read as the vector pre-filter. See `VSIM` `FILTER` above. -- `COMBINE LINEAR: missing value for BETA` (or `ALPHA`): give both weights or neither. -- `YIELD_SCORE_AS ... collides with ...`: see [Score naming](#score-naming). - -## Notes - -- **`VSIM RANGE` is not implemented.** The clause parses, so a command written for another engine is checked rather than misread, but executing one returns an error. Use `KNN`. -- **`POLICY` is active inside a counted VSIM `FILTER`.** `ADHOC` forces exact filter-first execution and `BATCHES` forces vector-search-first execution with inline filtering. Other values, duplicate declarations, and placement outside the counted FILTER block are rejected. -- **`BATCH_SIZE` is accepted but ignored.** It is valid only after `POLICY BATCHES`; fixed-size batch iteration is tracked separately. -- **`NOCONTENT` is rejected.** `FT.HYBRID` always returns records; a query wanting keys only can ask for no `LOAD` clause. -- **`FT.HYBRID` cannot run inside `MULTI`/`EXEC` or a Lua script**, and is unavailable when the reader thread pool is disabled. All three force synchronous execution, which cannot revalidate the two arms' results against concurrent writes. diff --git a/commands/ft.info.md b/commands/ft.info.md deleted file mode 100644 index 150824f1..00000000 --- a/commands/ft.info.md +++ /dev/null @@ -1,152 +0,0 @@ -The `FT.INFO` command provides information about an index. Variants of the command are available in cluster mode to aggregate index information across the cluster. - -``` -FT.INFO - [LOCAL | PRIMARY | CLUSTER] - [ALLSHARDS | SOMESHARDS] - [CONSISTENT | INCONSISTENT] -``` - -- `` (required): The name of the index to return information about. - -- `LOCAL` (optional): Only the executing (local) node provides index information. This is the default. -- `PRIMARY` (optional): The primary nodes of every shard in the cluster are queried to generate index information. This is only valid when cluster mode is enabled. -- `CLUSTER` (optional): All nodes, primary or replica, are queried to generate index information. This is only valid when cluster mode is enabled. - -- `ALLSHARDS` (optional): If specified, a response is required from every shard in the system. If all responses are not received within a time window the command is terminated with an error. This is the default. -- `SOMESHARDS` (optional): If specified, a response is NOT required from every shard in the system. If all responses are not received within the time window, only the received responses are returned and no error is generated. - -- `CONSISTENT` (optional): If specified, the command is terminated with an error if any received response isn't from a consistent version of the index. This is the default. -- `INCONSISTENT` (optional): If specified, a command result is generated using only the responses from nodes with a consistent version of the index. - -## Reply - -### Response when LOCAL is specified - -The LOCAL response contains both the definition of the index as well as the status of that index on the node that executes the command. - -An array of key value pairs. - -- `index_name` (string) The index name -- `index_definition` (an array of key/value pairs) - - `key_type` (string) `HASH` or `JSON` - - `prefixes` (array of strings) The declared prefixes for this index - - `filter` (string) The index's `FILTER` expression. Only present when the index was created with `FILTER`. - - `default_score` (double) The index's configured `SCORE` value - - `score_field` (string) The index's configured `SCORE_FIELD`, or an empty string if none - - The two fields above require `search.emulate-release` to be `1.3.0` or later. Below that — including at the default setting — `index_definition` omits `score_field` and reports `default_score` as the bulk string `"1"`. See [COMPATIBILITY.md](https://github.com/valkey-io/valkey-search/blob/main/COMPATIBILITY.md). - - The other fields that 1.3.0 adds to this reply, `filter_rejected_keys` and the per-attribute `SORTABLE` and `UNF` pairs, are reported regardless of `search.emulate-release`. - -- `attributes` (array of arrays) One entry per declared attribute of the index. - - `identifier` (string) identifier for this attribute - - `attribute` (string) The name used to refer to this index in query and aggregation expressions. - - `user_indexed_memory` (integer) Number of bytes of user data ingested into this field. - - `type` (string) One of `NUMERIC`, `TAG`, `TEXT` or `VECTOR` - - Type-specific extension (see below) - - `SORTABLE` (string) `1` if the attribute was declared `SORTABLE`, `0` otherwise. Not reported for `VECTOR` attributes; `SORTABLE` on a vector is accepted but has no effect and is not reported. - - `UNF` (string) `1` if the attribute was declared `SORTABLE UNF`, `0` otherwise. Reported only for `TAG` and `TEXT` attributes, the only types whose sort value is normalized. - - Unlike RediSearch, which emits `SORTABLE` and `UNF` as bare tokens only when set, Valkey Search always emits them as key/value pairs. - -- `num_docs` (integer) Total keys in the index -- `num_records` (integer) Total number of fields indexed. -- `total_term_occurrences` (integer) Total number of terms in all text fields in this index. -- `num_terms` (integer) Total number of unique terms in all text fields in this index. -- `hash_indexing_failures` (string) INTEGER. Number of field values that produced nothing to index when a key was first added: malformed values (for example a non-numeric `NUMERIC` value, a wrong-size `VECTOR`, or invalid UTF-8) and values that yield no tags. -- `filter_rejected_keys` (string) INTEGER. Number of filter-rejection events: each time a key is evaluated against the index `FILTER` expression and does not satisfy it, the count increases by one. A key can be rejected more than once (for example, when it is rewritten, or when it is written while the initial backfill is in progress), so this is not a count of distinct keys. For a `HASH` index a `FILTER` may reference a field that is not declared in the schema, so a misspelled field name behaves as a missing field rather than failing the command. A large value can mean that a field name in the `FILTER` is misspelled. -- `backfill_in_progress` (string). "1" if a backfill is currently running. "0" if not. -- `backfill_complete_percent` (string) Estimated progress of background indexing. Percentage is expressed as a fractional value from 0 to 1.0. -- `mutation_queue_size` (string) Number of keys contained in the mutation queue. -- `recent_mutations_queue_delay` (string) `0 sec` if the mutation queue is empty. Otherwise it is the elapsed time, from scheduling through completion of processing, recorded by the last sampled mutation to update this statistic, in whole seconds rounded down, in the form ` sec`. One in every 1000 scheduled mutations is sampled; mutations processed inline are not sampled. -- `state` (string) Current backfill state. `ready` indicates that no backfill is in progress. `backfill_in_progress` backfill operation proceeding normally. `backfill_paused_by_oom` backfill is paused because the Valkey instance is out of memory. - -The following four fields are only present when the index has at least one `TEXT` attribute. - -- `punctuation` (string) list of punctuation characters. -- `stop_words` (array of strings) list of stop words. Empty if the index was created with `NOSTOPWORDS`. -- `with_offsets` (string) "1" if offsets are included. "0" if offsets are not included -- `min_stem_size` (integer) Minimum stemming size for this index. - -The following field is always present: - -- `language` (string) The index's `LANGUAGE`, reported in lowercase (for example, `english`). `english` if the index was created without `LANGUAGE`. - -### NUMERIC Field Type Extension - -- `size` (string) INTEGER. Number of keys that have this numeric attribute present. - -### TAG Field Type Extension - -- `SEPARATOR` (string) The actual separator character. -- `CASESENSITIVE` (string) "0" or "1". -- `size` (string) INTEGER. Number of keys that have this tag attribute present. - -### TEXT Field Type Extension - -- `WITH_SUFFIX_TRIE` (string) "0" or "1". -- `NO_STEM` (string) "0" or "1". -- `WEIGHT` (string) The attribute's `WEIGHT`. Currently always "1". - -### VECTOR Field Type Extension - -- `index` (array) - - `capacity` (integer) The current capacity for the total number of vectors that the index can store. - - `dimensions` (integer) Dimension count - - `distance_metric` (string) Possible values are `L2`, `IP` or `COSINE` - - `size` (string) INTEGER. Number of valid vectors for this attribute - - `data_type` (string) Element data type of the vector. Possible values are `FLOAT32`, `FLOAT16` or `BFLOAT16` - - `algorithm` (array of key/value pairs) Extended information about the vector indexing algorithm for this attribute. - -#### FLAT VECTOR Field Type Extension. - -- `name` (string) `FLAT`. -- `block_size` (number) block size for this attribute. - -#### HNSW VECTOR Field Type Extension. - -- `name` (string) `HNSW`. -- `m` (integer) The count of maximum permitted outgoing edges for each node in the graph in each layer. The maximum number of outgoing edges is 2\*M for layer 0\. The default is 16. The maximum is set by `search.max-vector-m`. -- `ef_construction` (integer) Number of candidate vectors examined while building the index. The default is 200, and the maximum is set by `search.max-vector-ef-construction`. Higher values increase the time needed to create indexes, but improve the recall ratio. -- `ef_runtime` (integer) The configured field-level `EF_RUNTIME` value. - -### Response when the PRIMARY option is specified. - -An array of key value pairs - -Totals are summed over the primaries that responded. With `SOMESHARDS`, a primary that does not respond is omitted, so totals may be lower than the full cluster's. - -Inside `MULTI`/`EXEC` or a Lua script, no other nodes are queried and the LOCAL response is returned instead. - -- `mode` (string) Will have the value `primary`. -- `index_name` (string) The index name -- `num_docs` (string) INTEGER. Total keys in the index -- `num_records` (string) INTEGER. Total records in the index -- `hash_indexing_failures` (string) INTEGER. Number of field values that produced nothing to index when a key was first added: malformed values (for example a non-numeric `NUMERIC` value, a wrong-size `VECTOR`, or invalid UTF-8) and values that yield no tags. -- `attributes` (array of arrays) One entry per declared attribute of the index. - - `identifier` (string) identifier for this attribute - - `attribute` (string) The name used to refer to this index in query and aggregation expressions. - - `user_indexed_memory` (integer) Number of bytes of user data ingested into this field, summed across the primaries. - - `num_records` (integer) Number of records indexed for this attribute, summed across the primaries. -- `index_fingerprint` (integer) Fingerprint of the index definition on the node that executes the command. Only present when `search.info-developer-visible` is `yes`; intended for debugging. -- `index_version` (integer) Version of the index definition on the node that executes the command. Only present when `search.info-developer-visible` is `yes`; intended for debugging. - -### Response when the CLUSTER option is specified - -An array of key value pairs - -Totals, minimums and maximums are computed over the nodes that responded. With `SOMESHARDS`, a node that does not respond is omitted, so totals may be lower than the full cluster's. - -Inside `MULTI`/`EXEC` or a Lua script, no other nodes are queried and the LOCAL response is returned instead. - -- `mode` (string) Will have the value `cluster`. -- `index_name` (string) The index name -- `backfill_in_progress` (string) 0 or 1. Is backfill in progress -- `backfill_complete_percent_max` (string) FLOAT32. Maximum backfill complete percent in all nodes -- `backfill_complete_percent_min` (string) FLOAT32. Minimum backfill complete percent in all nodes -- `state` (string) The current state of the index, one of: `ready`, `backfill_in_progress` or `backfill_paused_by_oom` -- `attributes` (array of arrays) One entry per declared attribute of the index. - - `identifier` (string) identifier for this attribute - - `attribute` (string) The name used to refer to this index in query and aggregation expressions. - - `user_indexed_memory` (integer) Number of bytes of user data ingested into this field, summed across all nodes, primaries and replicas. diff --git a/commands/ft.search.md b/commands/ft.search.md deleted file mode 100644 index b6b65cde..00000000 --- a/commands/ft.search.md +++ /dev/null @@ -1,306 +0,0 @@ -Performs a search of the specified index. The keys which match the query expression are returned. - -``` -FT.SEARCH - [ALLSHARDS | SOMESHARDS] - [CONSISTENT | INCONSISTENT] - [DIALECT 2] - [INKEYS [ ...]] - [INORDER] - [LIMIT ] - [NOCONTENT] - [PARAMS [ ...]] - [RETURN [AS ] [AS ]...] - [SCORER ] - [SLOP ] - [SORTBY [ ASC | DESC]] - [TIMEOUT ] - [VERBATIM] - [WITHCURSOR [COUNT ] [MAXIDLE ]] - [WITHSCORES] - [WITHSORTKEYS] -``` - -- `` (required): This index name you want to query. -- `` (required): The query string, see [Search - query language](../topics/search-query.md) for details, including KNN queries - and the [`VECTOR_RANGE` matcher](../topics/search-query.md#vector-range-match). -- `ALLSHARDS` (Optional): If specified, the command is terminated with a timeout error if a valid response from all shards is not received within the timeout interval. This is the default when `search.enable-partial-results` is `no`; otherwise `SOMESHARDS` is the default. -- `CONSISTENT` (Optional): If specified, the command is terminated with an error if the cluster is in an inconsistent state. This is the default when `search.enable-consistent-results` is `yes`; otherwise `INCONSISTENT` is the default. -- `DIALECT 2` (optional): Specifies your dialect. The only supported dialect is 2, which is also the default. -- `INCONSISTENT` (Optional): If specified, the command will generate a best-effort reply if the cluster remains inconsistent within the timeout interval. -- `INKEYS [ ...]` (optional): Restricts results to the specified set of document keys. `` is the number of keys that follow and must be a non-negative integer. Duplicate keys are deduplicated. If `` is 0, no results are returned. The response count reflects only keys that match both the query and the INKEYS set. On a KNN query, the K nearest neighbors are chosen from the listed keys only. -- `LIMIT ` (optional): Lets you choose a portion of the result. The first `` keys are skipped and only a maximum of `` keys are included. The default is LIMIT 0 10, which returns at most 10 keys. -- `NOCONTENT` (optional): When present, only the resulting key names are returned, no key values are included. -- `PARAMS [ ...]` (optional): `count` is the number of arguments, i.e., twice the number of name/value pairs. Parameters that the query does not use are ignored. See [Search - query language](../topics/search-query.md) for details. -- `RETURN [AS ] [AS ] ...` (optional): Specifies the fields you want to retrieve from your documents, along with any renaming for the returned values. `count` is the number of arguments that follow, including each `AS` and its name. For example, `RETURN 4 color AS c city` returns two fields. By default, all fields are returned unless the `NOCONTENT` option is set, in which case no fields are returned. If `count` is 0, it behaves the same as `NOCONTENT`. If `RETURN` is given more than once, only the last one applies when `search.emulate-release` is 1.3.0 or later; with the default setting (1.0.0), the fields of all the `RETURN` clauses are combined and any `RETURN 0` acts as `NOCONTENT`. See [COMPATIBILITY.md](https://github.com/valkey-io/valkey-search/blob/main/COMPATIBILITY.md). -- `INORDER` (optional): Indicates that proximity matching of text terms in the query must be in order. -- `SLOP ` (Optional): Specifies a slop value for proximity matching of text terms in the query. -- `VERBATIM` (Optional): If specified, stemming is not applied to text terms in the query. -- `SOMESHARDS` (Optional): If specified, the command will generate a best-effort reply if all shards have not responded within the timeout interval. -- `SORTBY [ASC | DESC]` (Optional): If present, results are sorted according to the value of the specified field. `ASC` (the default) sorts in ascending order; `DESC` sorts in descending order. `` is an index attribute name (its `AS` alias if it has one), the KNN distance field (`___score` or the KNN `AS` name), or a `VECTOR_RANGE` distance name. Any other name is an error. Keys that do not have the field, or whose numeric value cannot be parsed, are placed at the end in both directions. On a KNN query, `SORTBY` reorders only the K nearest neighbors. Sorting is applied before the `LIMIT` clause is applied. - - Without `SORTBY`, KNN results are sorted by distance, nearest first, unless the KNN filter contains a text or tag clause. Other results, including KNN results with a text or tag filter, are sorted by relevance score, highest first. See [Search - Scoring](../topics/search-scoring.md). -- `TIMEOUT ` (optional): Lets you set a timeout value for the search command. This must be an integer in milliseconds. The default is the value of `search.default-timeout-ms` (50000), and the value must not exceed `search.max-timeout-ms` (default 60000). -- `SCORER ` (Optional): Selects the relevance scoring function used to rank results. The only supported scorer now is `BM25STD`. The default is the value of `search.default-scorer` (`BM25STD`). See [Search - Scoring](../topics/search-scoring.md). -- `WITHCURSOR [COUNT ] [MAXIDLE ]` (Optional): Returns at most `` of the keys selected by the `LIMIT` clause and saves the remaining keys in a cursor, which is read with [`FT.CURSOR`](ft.cursor.md). `` must be between 1 and `search.cursor-max-count`, the default is 1000. `` is the number of milliseconds the cursor may go unread before it is destroyed; it must be between 1 and `search.cursor-max-idle-ms`, the default is 300000 (or `search.cursor-max-idle-ms` if that is smaller). If `COUNT` or `MAXIDLE` is given more than once, the last value is used. The cursor holds only the keys selected by `LIMIT`, whose default is `LIMIT 0 10`, so give `LIMIT 0 ` to page through more than 10 keys. This option is a Valkey extension. -- `WITHSCORES` (Optional): Augments the output with the relevance score computed for each returned key. For a KNN query without a text or tag filter, the score is 0; use the distance field instead. -- `WITHSORTKEYS` (Optional): Augments the output with the value of the `SORTBY` field for each returned key. It is ignored with `NOCONTENT`. See [WITHSCORES and WITHSORTKEYS](#withscores-or-withsortkeys-was-specified) for the format. - -## Reply - -The shape and contents of the response depend on the options specified in the command. -In all cases, the response is an array with the first element being a count of the number of keys which match the query. -The value of this count is unaffected by the presence of the `LIMIT` clause. For a KNN query the count is at most K. - -The `LIMIT` clause trims the list of matched keys to generate a list of returned keys. The remainder of the response array is for the returned keys. - -### `NOCONTENT` or `RETURN 0` was specified. - -The remainder of the response array is one entry per returned key, consisting of the key name. - -### `RETURN` with arguments was specified. - -The remainder of the response array is two entries per returned key. The first entry is the key name and -the second entry is an array of name/value pairs. The array of name/value pairs is driven by the `RETURN` clause. -Each of the named fields in the `RETURN` clause is returned along with the value of that field for this particular key. If the named field isn't present in this key then it won't be included. -For a KNN query, the distance is included only if the `RETURN` clause lists the distance field (`___score` or the KNN `AS` name) -- see [Search - query language](../topics/search-query.md) for details on how to control the name of that field. -For a vector range query, the distance is included only if the query names it with `AS ` or `$YIELD_DISTANCE_AS: `, and the `RETURN` clause lists that name. - -### Neither `NOCONTENT` nor `RETURN` was specified. - -If the index is on `HASH` keys, then the result is the same as if a `RETURN` clause had been present that listed all of the fields of a key. - -If the index is on `JSON` keys, then one name/value pair is inserted with name `$` and the value being the entire JSON key as a string. -In addition, if this is a vector search, then one additional name/value pair will be included which is the computed vector distance for this returned key -- see [Search - query language](../topics/search-query.md) for details on how to control the name of that field. -For a vector range query, the distance is included only if the query names it with `AS ` or `$YIELD_DISTANCE_AS: `. - -### `WITHSCORES` or `WITHSORTKEYS` was specified. - -With `WITHSCORES`, the relevance score of each key, as a string, follows the key name. This also applies with `NOCONTENT`. -With `WITHSORTKEYS` (ignored with `NOCONTENT`), the sort key follows the score. Then comes the array of name/value pairs, unless `NOCONTENT` was given. - -The format of the sort key depends on `search.emulate-release` (see [COMPATIBILITY.md](https://github.com/valkey-io/valkey-search/blob/main/COMPATIBILITY.md)): - -- 1.3.0 or later: the value is prefixed with `#` for a numeric field or a vector distance, and with `$` for any other field. If the key has no value for the field, or there is no `SORTBY`, the sort key is nil. -- Earlier versions, including the default setting of 1.0.0: the prefix is always `#`. If there is no value, the sort key is the string `#`. - -For example, the reply to `FT.SEARCH index @color:{blue} WITHSCORES WITHSORTKEYS SORTBY city RETURN 1 city` has this layout, with `search.emulate-release` set to 1.3.0 and the hash data from the [examples](#non-vector-queries-on-hash-index): - -``` -1) (integer) 1 -2) "key1" -3) "" -4) "$London" -5) 1) "city" - 2) "London" -``` - -### `WITHCURSOR` was specified. - -The response is a three element array: - -1. The count of the number of keys which match the query, as above. -2. An array with one element per returned key. Each element is an array holding the entries for that key described above, e.g. the key name and its array of name/value pairs. -3. The cursor id to pass to [`FT.CURSOR READ`](ft.cursor.md), or 0 if this reply contains all the remaining keys, in which case no cursor is created. - -### Errors - -If the queue of pending queries has reached `search.max-query-queue-depth` (default 100000; 0 disables the check), the command fails with `Search query queue depth exceeded`. - -## Examples - -### Non-vector Queries On Hash Index - -For these queries the following index and data definitions were used: - -``` -FT.CREATE index on hash SCHEMA color TAG city TAG -hset key1 color blue city London -hset key2 color black city Paris -hset key3 color green city Berlin -hset key4 color white city Tokyo -hset key5 color blend cityextra Unknown -``` - -A simple query returning all data of matched keys - -``` -FT.SEARCH index @color:{bl*} -1) (integer) 3 -2) "key1" -3) 1) "city" - 2) "London" - 3) "color" - 4) "blue" -4) "key5" -5) 1) "color" - 2) "blend" - 3) "cityextra" - 4) "Unknown" -6) "key2" -7) 1) "city" - 2) "Paris" - 3) "color" - 4) "black" -``` - -The same query with the `NOCONTENT` clause. - -``` -FT.SEARCH index @color:{bl*} NOCONTENT -1) (integer) 3 -2) "key1" -3) "key5" -4) "key2" -``` - -The same query with a `RETURN` clause. - -``` -FT.SEARCH index @color:{bl*} RETURN 2 color city -1) (integer) 3 -2) "key1" -3) 1) "color" - 2) "blue" - 3) "city" - 4) "London" -4) "key5" -5) 1) "color" - 2) "blend" -6) "key2" -7) 1) "color" - 2) "black" - 3) "city" - 4) "Paris" -``` - -### Non-vector Queries On JSON Index - -Repeating the queries above, except the data is JSON - -``` -FT.CREATE index on json SCHEMA $.color as color TAG $.city as city TAG -json.set key1 . {"color":"blue","city":"London"} -json.set key2 . {"color":"black","city":"Paris"} -json.set key3 . {"color":"green","city":"Berlin"} -json.set key4 . {"color":"white","city":"Tokyo"} -json.set key5 . {"color":"blend","cityextra":"Unknown"} -``` - -A simple query returning all data of matched keys - -``` -FT.SEARCH index @color:{bl*} -1) (integer) 3 -2) "key2" -3) 1) "$" - 2) "{\"color\":\"black\",\"city\":\"Paris\"}" -4) "key5" -5) 1) "$" - 2) "{\"color\":\"blend\",\"cityextra\":\"Unknown\"}" -6) "key1" -7) 1) "$" - 2) "{\"color\":\"blue\",\"city\":\"London\"}" -``` - -The same query with `NOCONTENT` - -``` -FT.SEARCH index @color:{bl*} NOCONTENT -1) (integer) 3 -2) "key2" -3) "key5" -4) "key1" -``` - -The same query with a `RETURN` clause. - -``` -FT.SEARCH index @color:{bl*} RETURN 2 color city -1) (integer) 3 -2) "key2" -3) 1) "color" - 2) "black" - 3) "city" - 4) "Paris" -4) "key5" -5) 1) "color" - 2) "blend" -6) "key1" -7) 1) "color" - 2) "blue" - 3) "city" - 4) "London" -``` - -### Pure vector search query - -For this example, assume we're building a property searching index where customers can search properties based on some features. -Assume we have a list of properties with the following attributes: - -- Description - vector embedding for given property. -- Other fields - each property can have other metadata as well. However, for simplicity, other fields are ignored in this example. - -At first, we create an `HNSW` index with the description as a vector field using the `FT.CREATE` command: - -``` -FT.CREATE idx SCHEMA description VECTOR HNSW 6 TYPE FLOAT32 DIM 3 DISTANCE_METRIC L2 -``` - -Now we can insert a few properties (this can be done prior to index creation as well) using the `HSET` command: - -``` -HSET p1 description "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80?" -HSET p2 description "\x00\x00\x00\x00\x00\x00\x80?\x00\x00\x00\x00" -HSET p3 description "\x00\x00\x80?\x00\x00\x00\x00\x00\x00\x00\x00" -HSET p4 description "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80?" -HSET p5 description "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80?" -``` - -Now we can perform queries using the `FT.SEARCH` command. The following query returns up to five of the most similar -properties to the provided query vector: - -``` -FT.SEARCH idx "*=>[KNN 5 @description $query_vector]" PARAMS 2 query_vector "\xcd\xccL?\x00\x00\x00\x00\x00\x00\x00\x00" DIALECT 2 -``` - -Returned result: - -``` - 1) (integer) 5 - 2) p3 - 3) 1) __description_score - 2) 0.0399999953806 - 3) description - 4) \x00\x00\x80?\x00\x00\x00\x00\x00\x00\x00\x00 - 4) p5 - 5) 1) __description_score - 2) 1.6400001049 - 3) description - 4) \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80? - 6) p4 - 7) 1) __description_score - 2) 1.6400001049 - 3) description - 4) \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80? - 8) p2 - 9) 1) __description_score - 2) 1.6400001049 - 3) description - 4) \x00\x00\x00\x00\x00\x00\x80?\x00\x00\x00\x00 -10) p1 -11) 1) __description_score - 2) 1.6400001049 - 3) description - 4) \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80? -``` - -### Sorting by the KNN distance - -The same query, returning the three farthest of the five nearest properties, and only their distance: - -``` -FT.SEARCH idx "*=>[KNN 5 @description $query_vector AS dist]" PARAMS 2 query_vector "\xcd\xccL?\x00\x00\x00\x00\x00\x00\x00\x00" SORTBY dist DESC LIMIT 0 3 RETURN 1 dist DIALECT 2 -``` - -`SORTBY` reorders only the five nearest neighbors. diff --git a/commands/function-delete.md b/commands/function-delete.md deleted file mode 100644 index b4f29322..00000000 --- a/commands/function-delete.md +++ /dev/null @@ -1,23 +0,0 @@ -Delete a library and all its functions. - -This command deletes the library called _library-name_ and all functions in it. -If the library doesn't exist, the server returns an error. - -For more information please refer to [Introduction to Valkey Functions](../topics/functions-intro.md). - -## Reply - -`OK`. - -## Examples - -``` -127.0.0.1:6379> FUNCTION LOAD "#!lua name=mylib \n server.register_function('myfunc', function(keys, args) return 'hello' end)" -"mylib" -127.0.0.1:6379> FCALL myfunc 0 -"hello" -127.0.0.1:6379> FUNCTION DELETE mylib -OK -127.0.0.1:6379> FCALL myfunc 0 -(error) ERR Function not found -``` diff --git a/commands/function-dump.md b/commands/function-dump.md deleted file mode 100644 index 22a148b7..00000000 --- a/commands/function-dump.md +++ /dev/null @@ -1,36 +0,0 @@ -Return the serialized payload of loaded libraries. -You can restore the serialized payload later with the [`FUNCTION RESTORE`](function-restore.md) command. - -For more information please refer to [Introduction to Valkey Functions](../topics/functions-intro.md). - -## Reply - -String: the serialized payload - -## Examples - -The following example shows how to dump loaded libraries using `FUNCTION DUMP` and then it calls [`FUNCTION FLUSH`](function-flush.md) deletes all the libraries. -Then, it restores the original libraries from the serialized payload with `FUNCTION RESTORE`. - -``` -127.0.0.1:6379> FUNCTION LOAD "#!lua name=mylib \n server.register_function('myfunc', function(keys, args) return args[1] end)" -"mylib" -127.0.0.1:6379> FUNCTION DUMP -"\xf5\xc3@X@]\x1f#!lua name=mylib \n server.registe\rr_function('my@\x0b\x02', @\x06`\x12\nkeys, args) 6\x03turn`\x0c\a[1] end)\x0c\x00\xba\x98\xc2\xa2\x13\x0e$\a" -127.0.0.1:6379> FUNCTION FLUSH -OK -127.0.0.1:6379> FUNCTION RESTORE "\xf5\xc3@X@]\x1f#!lua name=mylib \n server.registe\rr_function('my@\x0b\x02', @\x06`\x12\nkeys, args) 6\x03turn`\x0c\a[1] end)\x0c\x00\xba\x98\xc2\xa2\x13\x0e$\a" -OK -127.0.0.1:6379> FUNCTION LIST -1) 1) "library_name" - 2) "mylib" - 3) "engine" - 4) "LUA" - 5) "functions" - 6) 1) 1) "name" - 2) "myfunc" - 3) "description" - 4) (nil) - 5) "flags" - 6) (empty array) -``` diff --git a/commands/function-flush.md b/commands/function-flush.md deleted file mode 100644 index 63088c7a..00000000 --- a/commands/function-flush.md +++ /dev/null @@ -1,12 +0,0 @@ -Deletes all the libraries. - -Unless called with the optional mode argument, the `lazyfree-lazy-user-flush` configuration directive sets the effective behavior. Valid modes are: - -* `ASYNC`: Asynchronously flush the libraries. -* `!SYNC`: Synchronously flush the libraries. - -For more information please refer to [Introduction to Valkey Functions](../topics/functions-intro.md). - -## Reply - -`OK`. diff --git a/commands/function-help.md b/commands/function-help.md deleted file mode 100644 index 7fb1c088..00000000 --- a/commands/function-help.md +++ /dev/null @@ -1,5 +0,0 @@ -The `FUNCTION HELP` command returns a helpful text describing the different subcommands. - -## Reply - -Array of sub-commands and their descriptions. diff --git a/commands/function-kill.md b/commands/function-kill.md deleted file mode 100644 index 7f78ea32..00000000 --- a/commands/function-kill.md +++ /dev/null @@ -1,10 +0,0 @@ -Kill a function that is currently executing. - - -The `FUNCTION KILL` command can be used only on functions that did not modify the dataset during their execution (since stopping a read-only function does not violate the scripting engine's guaranteed atomicity). - -For more information please refer to [Introduction to Valkey Functions](../topics/functions-intro.md). - -## Reply - -`OK`. diff --git a/commands/function-list.md b/commands/function-list.md deleted file mode 100644 index 1f82f787..00000000 --- a/commands/function-list.md +++ /dev/null @@ -1,21 +0,0 @@ -Return information about the functions and libraries. - -You can use the optional `LIBRARYNAME` argument to specify a pattern for matching library names. -The optional `WITHCODE` modifier will cause the server to include the libraries source implementation in the reply. - -The following information is provided for each of the libraries in the response: - -* **library_name:** the name of the library. -* **engine:** the engine of the library. -* **functions:** the list of functions in the library. - Each function has the following fields: - * **name:** the name of the function. - * **description:** the function's description. - * **flags:** an array of [function flags](../topics/functions-intro.md#function-flags). -* **library_code:** the library's source code (when given the `WITHCODE` modifier). - -For more information please refer to [Introduction to Valkey Functions](../topics/functions-intro.md). - -## Reply - -Array: information about functions and libraries. diff --git a/commands/function-load.md b/commands/function-load.md deleted file mode 100644 index 59bd597a..00000000 --- a/commands/function-load.md +++ /dev/null @@ -1,36 +0,0 @@ -Load a library to Valkey. - -The command receives a single mandatory parameter which is the source code that implements the library. -The library payload must start with Shebang statement that provides a metadata about the library (like the engine to use and the library name). -Shebang format: `#! name=`. Currently engine name must be `lua`. - -For the Lua engine, the implementation should declare one or more entry points to the library with the [`server.register_function()` API](../topics/lua-api.md#server.register_function). -Once loaded, you can call the functions in the library with the [`FCALL`](fcall.md) (or [`FCALL_RO`](fcall_ro.md) when applicable) command. - -When attempting to load a library with a name that already exists, the Valkey server returns an error. -The `REPLACE` modifier changes this behavior and overwrites the existing library with the new contents. - -The command will return an error in the following circumstances: - -* An invalid _engine-name_ was provided. -* The library's name already exists without the `REPLACE` modifier. -* A function in the library is created with a name that already exists in another library (even when `REPLACE` is specified). -* The engine failed in creating the library's functions (due to a compilation error, for example). -* No functions were declared by the library. - -For more information please refer to [Introduction to Valkey Functions](../topics/functions-intro.md). - -## Reply - -String: the library name that was loaded. - -## Examples - -The following example will create a library named `mylib` with a single function, `myfunc`, that returns the first argument it gets. - -``` -127.0.0.1:6379> FUNCTION LOAD "#!lua name=mylib \n server.register_function('myfunc', function(keys, args) return args[1] end)" -mylib -127.0.0.1:6379> FCALL myfunc 0 hello -"hello" -``` diff --git a/commands/function-restore.md b/commands/function-restore.md deleted file mode 100644 index fc218a05..00000000 --- a/commands/function-restore.md +++ /dev/null @@ -1,15 +0,0 @@ -Restore libraries from the serialized payload. - -You can use the optional _policy_ argument to provide a policy for handling existing libraries. -The following policies are allowed: - -* **APPEND:** appends the restored libraries to the existing libraries and aborts on collision. - This is the default policy. -* **FLUSH:** deletes all existing libraries before restoring the payload. -* **REPLACE:** appends the restored libraries to the existing libraries, replacing any existing ones in case of name collisions. Note that this policy doesn't prevent function name collisions, only libraries. - -For more information please refer to [Introduction to Valkey Functions](../topics/functions-intro.md). - -## Reply - -`OK`. diff --git a/commands/function-stats.md b/commands/function-stats.md deleted file mode 100644 index 9cd8c306..00000000 --- a/commands/function-stats.md +++ /dev/null @@ -1,21 +0,0 @@ -Return information about the function that's currently running and information about the available execution engines. - -The reply is map with two keys: - -1. `running_script`: information about the running script. - If there's no in-flight function, the server replies with a _nil_. - Otherwise, this is a map with the following keys: - * **name:** the name of the function. - * **command:** the command and arguments used for invoking the function. - * **duration_ms:** the function's runtime duration in milliseconds. -2. `engines`: this is a map of maps. Each entry in the map represent a single engine. - Engine map contains statistics about the engine like number of functions and number of libraries. - - -You can use this command to inspect the invocation of a long-running function and decide whether kill it with the [`FUNCTION KILL`](function-kill.md) command. - -For more information please refer to [Introduction to Valkey Functions](../topics/functions-intro.md). - -## Reply - -Map: information about the function that's currently running and information about the available execution engines. diff --git a/commands/function.md b/commands/function.md deleted file mode 100644 index f445c458..00000000 --- a/commands/function.md +++ /dev/null @@ -1,3 +0,0 @@ -This is a container command for function commands. - -To see the list of available commands you can call [`FUNCTION HELP`](function-help.md). diff --git a/commands/geoadd.md b/commands/geoadd.md deleted file mode 100644 index e1b7a7c5..00000000 --- a/commands/geoadd.md +++ /dev/null @@ -1,58 +0,0 @@ -Adds the specified geospatial items (longitude, latitude, name) to the specified key. Data is stored into the key as a sorted set, in a way that makes it possible to query the items with the [`GEOSEARCH`](geosearch.md) command. - -The command takes arguments in the standard format x,y so the longitude must be specified before the latitude. There are limits to the coordinates that can be indexed: areas very near to the poles are not indexable. - -The exact limits, as specified by EPSG:900913 / EPSG:3785 / OSGEO:41001 are the following: - -* Valid longitudes are from -180 to 180 degrees. -* Valid latitudes are from -85.05112878 to 85.05112878 degrees. - -The command will report an error when the user attempts to index coordinates outside the specified ranges. - -**Note:** there is no **GEODEL** command because you can use [`ZREM`](zrem.md) to remove elements. The Geo index structure is just a sorted set. - -## GEOADD options - -`GEOADD` also provides the following options: - -* **XX**: Only update elements that already exist. Never add elements. -* **NX**: Don't update already existing elements. Always add new elements. -* **CH**: Modify the return value from the number of new elements added, to the total number of elements changed (CH is an abbreviation of *changed*). Changed elements are **new elements added** and elements already existing for which **the coordinates was updated**. So elements specified in the command line having the same score as they had in the past are not counted. Note: normally, the return value of `GEOADD` only counts the number of new elements added. - -Note: The **XX** and **NX** options are mutually exclusive. - -How does it work? ---- - -The way the sorted set is populated is using a technique called -[Geohash](https://en.wikipedia.org/wiki/Geohash). Latitude and Longitude -bits are interleaved to form a unique 52-bit integer. We know -that a sorted set double score can represent a 52-bit integer without losing -precision. - -This format allows for bounding box and radius querying by checking the 1+8 areas needed to cover the whole shape and discarding elements outside it. The areas are checked by calculating the range of the box covered, removing enough bits from the less significant part of the sorted set score, and computing the score range to query in the sorted set for each area. - -What Earth model does it use? ---- - -The model assumes that the Earth is a sphere since it uses the Haversine formula to calculate distance. This formula is only an approximation when applied to the Earth, which is not a perfect sphere. -The introduced errors are not an issue when used, for example, by social networks and similar applications requiring this type of querying. -However, in the worst case, the error may be up to 0.5%, so you may want to consider other systems for error-critical applications. - -## Reply - -Integer: When used without optional arguments, the number of elements added to the sorted set (excluding score updates). If the CH option is specified, the number of elements that were changed (added or updated). - -## Examples - -``` -127.0.0.1:6379> GEOADD Sicily 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania" -(integer) 2 -127.0.0.1:6379> GEODIST Sicily Palermo Catania -"166274.1516" -127.0.0.1:6379> GEORADIUS Sicily 15 37 100 km -1) "Catania" -127.0.0.1:6379> GEORADIUS Sicily 15 37 200 km -1) "Palermo" -2) "Catania" -``` diff --git a/commands/geodist.md b/commands/geodist.md deleted file mode 100644 index 0150713b..00000000 --- a/commands/geodist.md +++ /dev/null @@ -1,36 +0,0 @@ -Return the distance between two members in the geospatial index represented by the sorted set. - -Given a sorted set representing a geospatial index, populated using the [`GEOADD`](geoadd.md) command, the command returns the distance between the two specified members in the specified unit. - -If one or both the members are missing, the command returns NULL. - -The unit must be one of the following, and defaults to meters: - -* **m** for meters. -* **km** for kilometers. -* **mi** for miles. -* **ft** for feet. - -The distance is computed assuming that the Earth is a perfect sphere, so errors up to 0.5% are possible in edge cases. - -## Reply - -One of the following: - -* Null: one or both of the elements are missing. -* String: distance as a double (represented as a string) in the specified units. - -## Examples - -``` -127.0.0.1:6379> GEOADD Sicily 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania" -(integer) 2 -127.0.0.1:6379> GEODIST Sicily Palermo Catania -"166274.1516" -127.0.0.1:6379> GEODIST Sicily Palermo Catania km -"166.2742" -127.0.0.1:6379> GEODIST Sicily Palermo Catania mi -"103.3182" -127.0.0.1:6379> GEODIST Sicily Foo Bar -(nil) -``` diff --git a/commands/geohash.md b/commands/geohash.md deleted file mode 100644 index 2c6f803e..00000000 --- a/commands/geohash.md +++ /dev/null @@ -1,33 +0,0 @@ -Return valid [Geohash](https://en.wikipedia.org/wiki/Geohash) strings representing the position of one or more elements in a sorted set value representing a geospatial index (where elements were added using [`GEOADD`](geoadd.md)). - -Normally Valkey represents positions of elements using a variation of the Geohash -technique where positions are encoded using 52 bit integers. The encoding is -also different compared to the standard because the initial min and max -coordinates used during the encoding and decoding process are different. This -command however **returns a standard Geohash** in the form of a string as -described in the [Wikipedia article](https://en.wikipedia.org/wiki/Geohash) and compatible with the [geohash.org](http://geohash.org) web site. - -Geohash string properties ---- - -The command returns 11 characters Geohash strings, so no precision is lost -compared to the Valkey internal 52 bit representation. The returned Geohashes -have the following properties: - -1. They can be shortened removing characters from the right. It will lose precision but will still point to the same area. -2. It is possible to use them in `geohash.org` URLs such as `http://geohash.org/`. This is an [example of such URL](http://geohash.org/sqdtr74hyu0). -3. Strings with a similar prefix are nearby, but the contrary is not true, it is possible that strings with different prefixes are nearby too. - -## Reply - -Array where each element is the Geohash corresponding to each member name passed as an argument to the command. - -## Examples - -``` -127.0.0.1:6379> GEOADD Sicily 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania" -(integer) 2 -127.0.0.1:6379> GEOHASH Sicily Palermo Catania -1) "sqc8b49rny0" -2) "sqdtr74hyu0" -``` diff --git a/commands/geopos.md b/commands/geopos.md deleted file mode 100644 index 039b4fad..00000000 --- a/commands/geopos.md +++ /dev/null @@ -1,22 +0,0 @@ -Return the positions (longitude,latitude) of all the specified members of the geospatial index represented by the sorted set at *key*. - -Given a sorted set representing a geospatial index, populated using the [`GEOADD`](geoadd.md) command, it is often useful to obtain back the coordinates of specified members. When the geospatial index is populated via `GEOADD` the coordinates are converted into a 52 bit geohash, so the coordinates returned may not be exactly the ones used in order to add the elements, but small errors may be introduced. - -The command can accept a variable number of arguments so it always returns an array of positions even when a single element is specified. - -## Reply - -Array where each element is a two elements array representing longitude and latitude (x,y) of each member name passed as argument to the command. Non-existing elements are reported as null elements of the array. - -## Examples - -``` -127.0.0.1:6379> GEOADD Sicily 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania" -(integer) 2 -127.0.0.1:6379> GEOPOS Sicily Palermo Catania NonExisting -1) 1) "13.36138933897018433" - 2) "38.11555639549629859" -2) 1) "15.08726745843887329" - 2) "37.50266842333162032" -3) (nil) -``` diff --git a/commands/georadius.md b/commands/georadius.md deleted file mode 100644 index 2dc5d6c8..00000000 --- a/commands/georadius.md +++ /dev/null @@ -1,86 +0,0 @@ -Return the members of a sorted set populated with geospatial information using `GEOADD`, which are within the borders of the area specified with the center location and the maximum distance from the center (the radius). - -This manual page also covers the `GEORADIUS_RO` and `GEORADIUSBYMEMBER_RO` variants (see the section below for more information). - -The common use case for this command is to retrieve geospatial items near a specified point not farther than a given amount of meters (or other units). This allows, for example, to suggest mobile users of an application nearby places. - -The radius is specified in one of the following units: - -* **m** for meters. -* **km** for kilometers. -* **mi** for miles. -* **ft** for feet. - -The command optionally returns additional information using the following options: - -* `WITHDIST`: Also return the distance of the returned items from the specified center. The distance is returned in the same unit as the unit specified as the radius argument of the command. -* `WITHCOORD`: Also return the longitude,latitude coordinates of the matching items. -* `WITHHASH`: Also return the raw geohash-encoded sorted set score of the item, in the form of a 52 bit unsigned integer. This is only useful for low level hacks or debugging and is otherwise of little interest for the general user. - -The command default is to return unsorted items. Two different sorting methods can be invoked using the following two options: - -* `ASC`: Sort returned items from the nearest to the farthest, relative to the center. -* `DESC`: Sort returned items from the farthest to the nearest, relative to the center. - -By default all the matching items are returned. It is possible to limit the results to the first N matching items by using the **COUNT ``** option. -When `ANY` is provided the command will return as soon as enough matches are found, -so the results may not be the ones closest to the specified point, but on the other hand, the effort invested by the server is significantly lower. -When `ANY` is not provided, the command will perform an effort that is proportional to the number of items matching the specified area and sort them, -so to query very large areas with a very small `COUNT` option may be slow even if just a few results are returned. - -By default the command returns the items to the client. It is possible to store the results with one of these options: - -* `STORE`: Store the items in a sorted set populated with their geospatial information. -* `STOREDIST`: Store the items in a sorted set populated with their distance from the center as a floating point number, in the same unit specified in the radius. - -## Read-only variants - -Since `GEORADIUS` and `GEORADIUSBYMEMBER` have a `STORE` and `STOREDIST` option they are technically flagged as writing commands in the Valkey command table. For this reason read-only replicas will flag them, and Valkey Cluster replicas will redirect them to the primary instance even if the connection is in read-only mode (see the `READONLY` command of Valkey Cluster). - -Two read-only variants of the commands were added. They are exactly like the original commands but refuse the `STORE` and `STOREDIST` options. The two variants are called `GEORADIUS_RO` and `GEORADIUSBYMEMBER_RO`, and can safely be used in replicas. - -## Alternative - -`GEOSEARCH` and `GEOSEARCHSTORE` with the `BYRADIUS` argument. - -## Reply - -One of the following: - -* If no `WITH*` option is specified, an array of matched member names -* If `WITHCOORD`, `WITHDIST`, or `WITHHASH` options are specified, the command returns an array of arrays, where each sub-array represents a single item: - 1. The distance from the center as a floating point number, in the same unit specified in the radius. - 1. The Geohash integer. - 1. The coordinates as a two items x,y array (longitude,latitude). - -For example, the command `GEORADIUS Sicily 15 37 200 km WITHCOORD WITHDIST` will return each item in the following way: - -`["Palermo","190.4424",["13.361389338970184","38.115556395496299"]]` - -## Examples - -``` -127.0.0.1:6379> GEOADD Sicily 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania" -(integer) 2 -127.0.0.1:6379> GEORADIUS Sicily 15 37 200 km WITHDIST -1) 1) "Palermo" - 2) "190.4424" -2) 1) "Catania" - 2) "56.4413" -127.0.0.1:6379> GEORADIUS Sicily 15 37 200 km WITHCOORD -1) 1) "Palermo" - 2) 1) "13.36138933897018433" - 2) "38.11555639549629859" -2) 1) "Catania" - 2) 1) "15.08726745843887329" - 2) "37.50266842333162032" -127.0.0.1:6379> GEORADIUS Sicily 15 37 200 km WITHDIST WITHCOORD -1) 1) "Palermo" - 2) "190.4424" - 3) 1) "13.36138933897018433" - 2) "38.11555639549629859" -2) 1) "Catania" - 2) "56.4413" - 3) 1) "15.08726745843887329" - 2) "37.50266842333162032" -``` diff --git a/commands/georadius_ro.md b/commands/georadius_ro.md deleted file mode 100644 index e646b8b8..00000000 --- a/commands/georadius_ro.md +++ /dev/null @@ -1,17 +0,0 @@ -Read-only variant of the `GEORADIUS` command. - -This command is identical to the `GEORADIUS` command, except that it doesn't support the optional `STORE` and `STOREDIST` parameters. - -## Alternative - -`GEOSEARCH` with the `BYRADIUS` argument. - -## Reply - -One of the following: - -* If no `WITH*` option is specified, an array of matched member names -* If `WITHCOORD`, `WITHDIST`, or `WITHHASH` options are specified, the command returns an array of arrays, where each sub-array represents a single item: - * The distance from the center as a floating point number, in the same unit specified in the radius. - * The Geohash integer. - * The coordinates as a two items x,y array (longitude,latitude). diff --git a/commands/georadiusbymember.md b/commands/georadiusbymember.md deleted file mode 100644 index 90eaee84..00000000 --- a/commands/georadiusbymember.md +++ /dev/null @@ -1,34 +0,0 @@ -This command is exactly like `GEORADIUS` with the sole difference that instead -of taking, as the center of the area to query, a longitude and latitude value, it takes the name of a member already existing inside the geospatial index represented by the sorted set. - -The position of the specified member is used as the center of the query. - -Please check the example below and the `GEORADIUS` documentation for more information about the command and its options. - -Note that `GEORADIUSBYMEMBER_RO` was added to provide a read-only command that can be used in replicas. See the `GEORADIUS` page for more information. - -## Alternative - -`GEOSEARCH` and `GEOSEARCHSTORE` with the `BYRADIUS` and `FROMMEMBER` arguments. - -## Reply - -One of the following: - -* If no `WITH*` option is specified, an array of matched member names -* If `WITHCOORD`, `WITHDIST`, or `WITHHASH` options are specified, the command returns an array of arrays, where each sub-array represents a single item: - * The distance from the center as a floating point number, in the same unit specified in the radius. - * The Geohash integer. - * The coordinates as a two items x,y array (longitude,latitude). - -## Examples - -``` -127.0.0.1:6379> GEOADD Sicily 13.583333 37.316667 "Agrigento" -(integer) 1 -127.0.0.1:6379> GEOADD Sicily 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania" -(integer) 2 -127.0.0.1:6379> GEORADIUSBYMEMBER Sicily Agrigento 100 km -1) "Agrigento" -2) "Palermo" -``` diff --git a/commands/georadiusbymember_ro.md b/commands/georadiusbymember_ro.md deleted file mode 100644 index 3d2558bd..00000000 --- a/commands/georadiusbymember_ro.md +++ /dev/null @@ -1,17 +0,0 @@ -Read-only variant of the `GEORADIUSBYMEMBER` command. - -This command is identical to the `GEORADIUSBYMEMBER` command, except that it doesn't support the optional `STORE` and `STOREDIST` parameters. - -## Alternative - -`GEOSEARCH` with the `BYRADIUS` and `FROMMEMBER` arguments. - -## Reply - -One of the following: - -* If no `WITH*` option is specified, an array of matched member names -* If `WITHCOORD`, `WITHDIST`, or `WITHHASH` options are specified, the command returns an array of arrays, where each sub-array represents a single item: - * The distance from the center as a floating point number, in the same unit specified in the radius. - * The Geohash integer. - * The coordinates as a two items x,y array (longitude,latitude). diff --git a/commands/geosearch.md b/commands/geosearch.md deleted file mode 100644 index 71fba4b0..00000000 --- a/commands/geosearch.md +++ /dev/null @@ -1,84 +0,0 @@ -Return the members of a sorted set populated with geospatial information using [`GEOADD`](geoadd.md), which are within the borders of the area specified by a given shape. This command extends the [`GEORADIUS`](georadius.md) command, so in addition to searching within circular areas, it supports searching within rectangular areas and polygon shaped areas. - -This command should be used in place of the deprecated `GEORADIUS` and [`GEORADIUSBYMEMBER`](georadiusbymember.md) commands. - -The query's shape is provided by one of these mandatory options: - -* `BYRADIUS`: Similar to `GEORADIUS`, search inside circular area according to given ``. -* `BYBOX`: Search inside an axis-aligned rectangle, determined by `` and ``. -* `BYPOLYGON`: Search within an area enclosed by the polygon vertices, determined by ` [ ...]`. - -For `BYBOX` and `BYRADIUS` based queries, the center point is provided by one of these mandatory options: - -* `FROMMEMBER`: Use the position of the given existing `` in the sorted set. -* `FROMLONLAT`: Use the given `` and `` position. - -In case of `BYPOLYGON` based queries, the center point and the bounding box are computed based on the polygon vertices of the command. -With this option, providing `FROMMEMBER` or `FROMLONLAT` is invalid. - -The command optionally returns additional information using the following options: - -* `WITHDIST`: Also return the distance of the returned items from the specified center point. The distance is returned in the same unit as specified for the radius or height and width arguments. -* `WITHCOORD`: Also return the longitude and latitude of the matching items. -* `WITHHASH`: Also return the raw geohash-encoded sorted set score of the item, in the form of a 52 bit unsigned integer. This is only useful for low level hacks or debugging and is otherwise of little interest for the general user. - -Matching items are returned unsorted by default. To sort them, use one of the following two options: - -* `ASC`: Sort returned items from the nearest to the farthest, relative to the center point. -* `DESC`: Sort returned items from the farthest to the nearest, relative to the center point. - -All matching items are returned by default. To limit the results to the first N matching items, use the **COUNT ``** option. -When the `ANY` option is used, the command returns as soon as enough matches are found. This means that the results returned may not be the ones closest to the specified point, but the effort invested by the server to generate them is significantly less. -When `ANY` is not provided, the command will perform an effort that is proportional to the number of items matching the specified area and sort them, -so to query very large areas with a very small `COUNT` option may be slow even if just a few results are returned. - -## Reply - -One of the following: - -* If no `WITH*` option is specified, an array of matched member names -* If `WITHCOORD`, `WITHDIST`, or `WITHHASH` options are specified, the command returns an array of arrays, where each sub-array represents a single item: - * The distance from the center as a floating point number, in the same unit specified in the radius. - * The Geohash integer. - * The coordinates as a two items x,y array (longitude,latitude). - -## Examples - -``` -127.0.0.1:6379> GEOADD Sicily 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania" -(integer) 2 -127.0.0.1:6379> GEOADD Sicily 12.758489 38.788135 "edge1" 17.241510 38.788135 "edge2" -(integer) 2 -127.0.0.1:6379> GEOSEARCH Sicily FROMLONLAT 15 37 BYRADIUS 200 km ASC -1) "Catania" -2) "Palermo" -127.0.0.1:6379> GEOSEARCH Sicily FROMLONLAT 15 37 BYBOX 400 400 km ASC WITHCOORD WITHDIST -1) 1) "Catania" - 2) "56.4413" - 3) 1) "15.08726745843887329" - 2) "37.50266842333162032" -2) 1) "Palermo" - 2) "190.4424" - 3) 1) "13.36138933897018433" - 2) "38.11555639549629859" -3) 1) "edge2" - 2) "279.7403" - 3) 1) "17.24151045083999634" - 2) "38.78813451624225195" -4) 1) "edge1" - 2) "279.7405" - 3) 1) "12.7584877610206604" - 2) "38.78813451624225195" -127.0.0.1:6379> GEOSEARCH Sicily BYPOLYGON 5 12.41098696654226 38.05033923003755 15.107936245794182 38.00616649901906 18.148439288534455 38.63804787603499 17.80831874257693 39.50316813110968 12.458468633214036 38.57719533463012 -1) "Palermo" -2) "edge2" -127.0.0.1:6379> GEOSEARCH Sicily BYPOLYGON 5 12.41098696654226 38.05033923003755 15.107936245794182 38.00616649901906 18.148439288534455 38.63804787603499 17.80831874257693 39.50316813110968 12.458468633214036 38.57719533463012 ASC WITHCOORD WITHDIST -1) 1) "Palermo" - 2) "166482.0159" - 3) 1) "13.36138933897018433" - 2) "38.11555639549629859" -2) 1) "edge2" - 2) "180861.7725" - 3) 1) "17.24151045083999634" - 2) "38.78813451624225195" -``` diff --git a/commands/geosearchstore.md b/commands/geosearchstore.md deleted file mode 100644 index 9b6e2125..00000000 --- a/commands/geosearchstore.md +++ /dev/null @@ -1,47 +0,0 @@ -This command is like [`GEOSEARCH`](geosearch.md), but stores the result in destination key. - -This command replaces the now deprecated [`GEORADIUS`](georadius.md) and [`GEORADIUSBYMEMBER`](georadiusbymember.md). - -By default, it stores the results in the `destination` sorted set with their geospatial information. - -When using the `STOREDIST` option, the command stores the items in a sorted set populated with their distance from the center of the circle, box or polygon, as a floating-point number, in the same unit specified for that shape. - -## Reply - -Integer: the number of elements in the resulting set - -## Examples - -``` -127.0.0.1:6379> GEOADD Sicily 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania" -(integer) 2 -127.0.0.1:6379> GEOADD Sicily 12.758489 38.788135 "edge1" 17.241510 38.788135 "edge2" -(integer) 2 -127.0.0.1:6379> GEOSEARCHSTORE key1 Sicily FROMLONLAT 15 37 BYBOX 400 400 km ASC COUNT 3 -(integer) 3 -127.0.0.1:6379> GEOSEARCH key1 FROMLONLAT 15 37 BYBOX 400 400 km ASC WITHCOORD WITHDIST WITHHASH -1) 1) "Catania" - 2) "56.4413" - 3) (integer) 3479447370796909 - 4) 1) "15.08726745843887329" - 2) "37.50266842333162032" -2) 1) "Palermo" - 2) "190.4424" - 3) (integer) 3479099956230698 - 4) 1) "13.36138933897018433" - 2) "38.11555639549629859" -3) 1) "edge2" - 2) "279.7403" - 3) (integer) 3481342659049484 - 4) 1) "17.24151045083999634" - 2) "38.78813451624225195" -127.0.0.1:6379> GEOSEARCHSTORE key2 Sicily FROMLONLAT 15 37 BYBOX 400 400 km ASC COUNT 3 STOREDIST -(integer) 3 -127.0.0.1:6379> ZRANGE key2 0 -1 WITHSCORES -1) "Catania" -2) "56.4412578701582" -3) "Palermo" -4) "190.44242984775784" -5) "edge2" -6) "279.7403417843143" -``` diff --git a/commands/get.md b/commands/get.md deleted file mode 100644 index 74a2f73a..00000000 --- a/commands/get.md +++ /dev/null @@ -1,22 +0,0 @@ -Get the value of `key`. -If the key does not exist the special value `nil` is returned. -An error is returned if the value stored at `key` is not a string, because `GET` -only handles string values. - -## Reply - -One of the following: - -* String: the value of the key. -* Null: if the key does not exist. - -## Examples - -``` -127.0.0.1:6379> GET nonexisting -(nil) -127.0.0.1:6379> SET mykey "Hello" -OK -127.0.0.1:6379> GET mykey -"Hello" -``` diff --git a/commands/getbit.md b/commands/getbit.md deleted file mode 100644 index 60558834..00000000 --- a/commands/getbit.md +++ /dev/null @@ -1,27 +0,0 @@ -Returns the bit value at _offset_ in the string value stored at _key_. - -When _offset_ is beyond the string length, the string is assumed to be a -contiguous space with 0 bits. -When _key_ does not exist it is assumed to be an empty string, so _offset_ is -always out of range and the value is also assumed to be a contiguous space with -0 bits. - -## Reply - -The bit value stored at _offset_, one of the following: - -* Integer: `0`. -* Integer: `1`. - -## Examples - -``` -127.0.0.1:6379> SETBIT mykey 7 1 -(integer) 0 -127.0.0.1:6379> GETBIT mykey 0 -(integer) 0 -127.0.0.1:6379> GETBIT mykey 7 -(integer) 1 -127.0.0.1:6379> GETBIT mykey 100 -(integer) 0 -``` diff --git a/commands/getdel.md b/commands/getdel.md deleted file mode 100644 index 06a456b8..00000000 --- a/commands/getdel.md +++ /dev/null @@ -1,20 +0,0 @@ -Get the value of `key` and delete the key. -This command is similar to `GET`, except for the fact that it also deletes the key on success (if and only if the key's value type is a string). - -## Reply - -One of the following: - -* String: the value of the key. -* Null: if the key does not exist or if the key's value type is not a string. - -## Examples - -``` -127.0.0.1:6379> SET mykey "Hello" -OK -127.0.0.1:6379> GETDEL mykey -"Hello" -127.0.0.1:6379> GET mykey -(nil) -``` diff --git a/commands/getex.md b/commands/getex.md deleted file mode 100644 index 0b450548..00000000 --- a/commands/getex.md +++ /dev/null @@ -1,33 +0,0 @@ -Get the value of `key` and optionally set its expiration. -`GETEX` is similar to `GET`, but is a write command with additional options. - -## Options - -The `GETEX` command supports a set of options that modify its behavior: - -* `EX` *seconds* -- Set the specified expire time, in seconds. -* `PX` *milliseconds* -- Set the specified expire time, in milliseconds. -* `EXAT` *timestamp-seconds* -- Set the specified Unix time at which the key will expire, in seconds. -* `PXAT` *timestamp-milliseconds* -- Set the specified Unix time at which the key will expire, in milliseconds. -* `PERSIST` -- Remove the time to live associated with the key. - -## Reply - -String: the value of `key` - -Null: if `key` does not exist. - -## Examples - -``` -127.0.0.1:6379> SET mykey "Hello" -OK -127.0.0.1:6379> GETEX mykey -"Hello" -127.0.0.1:6379> TTL mykey -(integer) -1 -127.0.0.1:6379> GETEX mykey EX 60 -"Hello" -127.0.0.1:6379> TTL mykey -(integer) 60 -``` diff --git a/commands/getrange.md b/commands/getrange.md deleted file mode 100644 index 3633f42a..00000000 --- a/commands/getrange.md +++ /dev/null @@ -1,27 +0,0 @@ -Returns the substring of the string value stored at `key`, determined by the -offsets `start` and `end` (both are inclusive). -Negative offsets can be used in order to provide an offset starting from the end -of the string. -So -1 means the last character, -2 the penultimate and so forth. - -The function handles out of range requests by limiting the resulting range to -the actual length of the string. - -## Reply - -String: The substring of the string value stored at key, determined by the offsets start and end (both are inclusive). - -## Examples - -``` -127.0.0.1:6379> SET mykey "This is a string" -OK -127.0.0.1:6379> GETRANGE mykey 0 3 -"This" -127.0.0.1:6379> GETRANGE mykey -3 -1 -"ing" -127.0.0.1:6379> GETRANGE mykey 0 -1 -"This is a string" -127.0.0.1:6379> GETRANGE mykey 10 100 -"string" -``` diff --git a/commands/getset.md b/commands/getset.md deleted file mode 100644 index e030b8c7..00000000 --- a/commands/getset.md +++ /dev/null @@ -1,43 +0,0 @@ -Atomically sets `key` to `value` and returns the old value stored at `key`. -Returns an error when `key` exists but does not hold a string value. Any -previous time to live associated with the key is discarded on successful -`SET` operation. - -## Design pattern - -`GETSET` can be used together with `INCR` for counting with atomic reset. -For example: a process may call `INCR` against the key `mycounter` every time -some event occurs, but from time to time we need to get the value of the counter -and reset it to zero atomically. -This can be done using `GETSET mycounter "0"`: - -``` -127.0.0.1:6379> INCR mycounter -(integer) 1 -127.0.0.1:6379> GETSET mycounter "0" -"1" -127.0.0.1:6379> GET mycounter -"0" -``` - -## Alternative - -`SET` with the `GET` argument. - -## Reply - -One of the following: - -* String: the old value stored at the key. -* Null: if the key does not exist. - -## Examples - -``` -127.0.0.1:6379> SET mykey "Hello" -OK -127.0.0.1:6379> GETSET mykey "World" -"Hello" -127.0.0.1:6379> GET mykey -"World" -``` diff --git a/commands/hdel.md b/commands/hdel.md deleted file mode 100644 index f5851089..00000000 --- a/commands/hdel.md +++ /dev/null @@ -1,19 +0,0 @@ -Removes the specified fields from the hash stored at `key`. -Specified fields that do not exist within this hash are ignored. -If `key` does not exist, it is treated as an empty hash and this command returns -`0`. - -## Reply - -Integer: the number of fields that were removed from the hash, excluding any specified but non-existing fields. - -## Examples - -``` -127.0.0.1:6379> HSET myhash field1 "foo" -(integer) 1 -127.0.0.1:6379> HDEL myhash field1 -(integer) 1 -127.0.0.1:6379> HDEL myhash field2 -(integer) 0 -``` diff --git a/commands/hello.md b/commands/hello.md deleted file mode 100644 index b87dcd59..00000000 --- a/commands/hello.md +++ /dev/null @@ -1,71 +0,0 @@ -Switch to a different protocol, optionally authenticating and setting the -connection's name, or provide a contextual client report. - -Valkey supports two protocols: RESP2 and RESP3. RESP3 has certain advantages since -when the connection is in this mode, Valkey is able to reply with more semantical -replies: for instance, [`HGETALL`](hgetall.md) will return a *map type*, so a client library -implementation no longer requires to know in advance to translate the array into -a hash before returning it to the caller. For a full coverage of RESP3, please -check the [RESP3 specification](https://github.com/redis/redis-specifications/blob/master/protocol/RESP3.md). - -Valkey connections start in RESP2 mode, so clients implementing RESP2 do -not need to updated or changed. There are no short term plans to drop support for -RESP2, although future version may default to RESP3. - -`HELLO` always replies with a list of current server and connection properties, -such as: versions, modules loaded, client ID, replication role and so forth. -The `availability_zone` field only shows up when it is set in the configs, -see `availability-zone` config for more details, added in Valkey 8.1. -Starting with Valkey 8.0, the `server` field is "valkey" and the `version` field is the Valkey version. -When `extended-redis-compatibility` is set to `yes`, they are reported as "redis" and "7.2.4" instead. -In Valkey 7.2, the `server` field is "redis". - -When called without any arguments and its default use of RESP2 -protocol, the reply looks like this: - - > HELLO - 1) "server" - 2) "valkey" - 3) "version" - 4) "9.2.0" - 5) "proto" - 6) (integer) 2 - 7) "id" - 8) (integer) 5 - 9) "mode" - 10) "standalone" - 11) "role" - 12) "master" - 13) "modules" - 14) (empty array) - 15) "availability_zone" - 16) "us-east-1" - -Clients that want to handshake using the RESP3 mode need to call the `HELLO` -command and specify the value "3" as the `protover` argument, like so: - - > HELLO 3 - 1# "server" => "valkey" - 2# "version" => "9.2.0" - 3# "proto" => (integer) 3 - 4# "id" => (integer) 10 - 5# "mode" => "standalone" - 6# "role" => "master" - 7# "modules" => (empty array) - 8# "availability_zone" => "us-east-1" - -Because `HELLO` replies with useful information, and given that `protover` is -optional or can be set to "2", client library authors may consider using this -command instead of the canonical `PING` when setting up the connection. - -When called with the optional `protover` argument, this command switches the -protocol to the specified version and also accepts the following options: - -* `AUTH `: directly authenticate the connection in addition to switching to the specified protocol version. This makes calling [`AUTH`](auth.md) before `HELLO` unnecessary when setting up a new connection. Note that the `username` can be set to "default" to authenticate against a server that does not use ACLs, but rather the simpler `requirepass` mechanism. -* `SETNAME `: this is the equivalent of calling [`CLIENT SETNAME`](client-setname.md). - -## Reply - -Map of server properties. - -Error: if the `protover` requested does not exist. diff --git a/commands/hexists.md b/commands/hexists.md deleted file mode 100644 index b173fff2..00000000 --- a/commands/hexists.md +++ /dev/null @@ -1,19 +0,0 @@ -Returns if `field` is an existing field in the hash stored at `key`. - -## Reply - -One of the following: - -* Integer: `0` if the hash does not contain the field, or the key does not exist. -* Integer: `1` if the hash contains the field. - -## Examples - -``` -127.0.0.1:6379> HSET myhash field1 "foo" -(integer) 1 -127.0.0.1:6379> HEXISTS myhash field1 -(integer) 1 -127.0.0.1:6379> HEXISTS myhash field2 -(integer) 0 -``` diff --git a/commands/hexpire.md b/commands/hexpire.md deleted file mode 100644 index dd75bedd..00000000 --- a/commands/hexpire.md +++ /dev/null @@ -1,35 +0,0 @@ -The `HEXPIRE` command allows manipulating the expiration time for existing hash fields. -When set, the expiration time of a hash field will determine when the field will be automatically deleted. -Note, that providing a millisecond time of '0' will cause immediate expiration and deletion of the field(s). - -## Options - -The `HEXPIRE` command supports a set of options that modify its behavior: - -* NX — For each specified field, set expiration only when the field has no expiration. -* XX — For each specified field, set expiration only when the field has an existing expiration. -* GT — For each specified field, set expiration only when the new expiration is greater than current one. -* LT — For each specified field, set expiration only when the new expiration is less than current one. - -## Reply - -Array of integer codes indicating the result of setting expiry on each specified field, in the same order as the fields are requested. - -* -2: Field does not exist in the HASH, or key does not exist. -* 0: The specified NX | XX | GT | LT condition has not been met. -* 1: The expiration time was applied. -* 2: When called with 0 seconds. - -## Examples - -``` -127.0.0.1:6379> HSET myhash f1 v1 f2 v2 f3 v3 -(integer) 3 -127.0.0.1:6379> HEXPIRE myhash 10 FIELDS 2 f2 f3 -1) (integer) 1 -2) (integer) 1 -127.0.0.1:6379> HTTL myhash FIELDS 3 f1 f2 f3 -1) (integer) -1 -2) (integer) 8 -3) (integer) 8 -``` diff --git a/commands/hexpireat.md b/commands/hexpireat.md deleted file mode 100644 index 96d9ad98..00000000 --- a/commands/hexpireat.md +++ /dev/null @@ -1,39 +0,0 @@ -`HEXPIREAT` has the same effect and semantic as [`HEXPIRE`](hexpire.md), but instead of -specifying the number of seconds representing the TTL (time to live), it takes -an absolute Unix timestamp (seconds since January 1, 1970). A -timestamp in the past will delete the key immediately. - -For the specific semantics of the command refer to the documentation of -[`HEXPIRE`](hexpire.md). - -## Options - -The `HEXPIREAT` command supports a set of options that modify its behavior: - -* NX — For each specified field, set expiration only when the field has no expiration. -* XX — For each specified field, set expiration only when the field has an existing expiration. -* GT — For each specified field, set expiration only when the new expiration is greater than current one. -* LT — For each specified field, set expiration only when the new expiration is less than current one. - -## Reply - -Array of integer codes indicating the result of setting expiry on each specified field, in the same order as the fields are requested. - -* -2: Field does not exist in the HASH, or key does not exist. -* 0: The specified NX | XX | GT | LT condition has not been met. -* 1: The expiration time was applied. -* 2: When called with 0 seconds. - -## Examples - -``` -127.0.0.1:6379> HSET myhash f1 v1 f2 v2 f3 v3 -(integer) 3 -27.0.0.1:6379> HEXPIREAT myhash 1754846600 FIELDS 2 f2 f3 -1) (integer) 1 -2) (integer) 1 -127.0.0.1:6379> HEXPIRETIME myhash FIELDS 3 f1 f2 f3 -1) (integer) -1 -2) (integer) 1754846600 -3) (integer) 1754846600 -``` diff --git a/commands/hexpiretime.md b/commands/hexpiretime.md deleted file mode 100644 index 86198332..00000000 --- a/commands/hexpiretime.md +++ /dev/null @@ -1,26 +0,0 @@ -The `HEXPIRETIME` command returns the absolute Unix timestamp (since January 1, 1970) in seconds at which the given hash field(s) will expire or -1 if the hash field doesn't have expiration time. - -See also the [`HPEXPIRETIME`](hpexpiretime.md) command that returns the same information with milliseconds resolution. - -## Reply - -Array of values associated with the result of getting the absolute expiry timestamp of the specific fields, in the same order as they are requested. - -* -2: Field does not exist in the provided hash key, or the hash key is empty. -* -1: Field exists in the provided hash key, but has no expiration associated with it. -* Integer: The expiration time associated with the hash key field, in seconds. - -## Examples - -``` -127.0.0.1:6379> HSET myhash f1 v1 f2 v2 f3 v3 -(integer) 3 -27.0.0.1:6379> HEXPIREAT myhash 1754846600 FIELDS 2 f2 f3 -1) (integer) 1 -2) (integer) 1 -127.0.0.1:6379> HEXPIRETIME myhash FIELDS 4 f1 f2 f3 non-exist -1) (integer) -1 -2) (integer) 1754846600 -3) (integer) 1754846600 -4) (integer) -2 -``` diff --git a/commands/hget.md b/commands/hget.md deleted file mode 100644 index ce30f77c..00000000 --- a/commands/hget.md +++ /dev/null @@ -1,19 +0,0 @@ -Returns the value associated with `field` in the hash stored at `key`. - -## Reply - -One of the following: - -* String: The value associated with the field. -* Null: If the field is not present in the hash or key does not exist. - -## Examples - -``` -127.0.0.1:6379> HSET myhash field1 "foo" -(integer) 1 -127.0.0.1:6379> HGET myhash field1 -"foo" -127.0.0.1:6379> HGET myhash field2 -(nil) -``` diff --git a/commands/hgetall.md b/commands/hgetall.md deleted file mode 100644 index c5a8d605..00000000 --- a/commands/hgetall.md +++ /dev/null @@ -1,21 +0,0 @@ -Returns all fields and values of the hash stored at `key`. -In the returned value, every field name is followed by its value, so the length -of the reply is twice the size of the hash. - -## Reply - -Map of fields and their values stored in the hash, or an empty map when key does not exist. - -## Examples - -``` -127.0.0.1:6379> HSET myhash field1 "Hello" -(integer) 1 -127.0.0.1:6379> HSET myhash field2 "World" -(integer) 1 -127.0.0.1:6379> HGETALL myhash -1) "field1" -2) "Hello" -3) "field2" -4) "World" -``` diff --git a/commands/hgetdel.md b/commands/hgetdel.md deleted file mode 100644 index 923862fe..00000000 --- a/commands/hgetdel.md +++ /dev/null @@ -1,39 +0,0 @@ -The `HGETDEL` command returns the values associated with the specified `fields` in the hash stored at `key` and deletes those fields from the hash. - -For every `field` that does not exist in the hash, a `nil` value is returned. -Because non-existing keys are treated as empty hashes, running `HGETDEL` against a non-existing `key` will return a list of `nil` values. - -When the last field is deleted, the key is also deleted. - -## Reply - -Array of values associated with the given fields that are deleted or null for the fields that do not exist. These are in same order as requested. - -## Examples - -``` -127.0.0.1:6379> HSET myhash f1 v1 f2 v2 f3 v3 -(integer) 3 -127.0.0.1:6379> HGETDEL myhash FIELDS 1 f2 -1) "v2" -127.0.0.1:6379> HGETDEL myhash FIELDS 1 f2 -1) (nil) -127.0.0.1:6379> HGETALL myhash -1) "f1" -2) "v1" -3) "f3" -4) "v3" -127.0.0.1:6379> HGETDEL myhash FIELDS 2 f2 f3 -1) (nil) -2) "v3" -127.0.0.1:6379> HGETALL myhash -1) "f1" -2) "v1" -127.0.0.1:6379> HGETDEL myhash FIELDS 3 f1 non-exist -(error) ERR numfields should be greater than 0 and match the provided number of fields -127.0.0.1:6379> HGETDEL myhash FIELDS 2 f1 non-exist -1) "v1" -2) (nil) -127.0.0.1:6379> HGETALL myhash -(empty array) -``` diff --git a/commands/hgetex.md b/commands/hgetex.md deleted file mode 100644 index 02838381..00000000 --- a/commands/hgetex.md +++ /dev/null @@ -1,45 +0,0 @@ -The `HGETEX` command returns the value of one or more fields of a given hash key, and optionally manipulates their expiration time. -The command will return an array in the size of the number of requested fields. -Without providing any optional flags, this command behaves exactly like a normal [`HMGET`](hmget.md) command. - -## Options - -The `HGETEX` command supports a set of options that modify its behavior: - -* EX seconds — Set the specified expiration time, in seconds. -* PX milliseconds — Set the specified expiration time, in milliseconds. -* EXAT `unix-time-seconds` — Set the specified Unix time at which the fields will expire, in seconds. -* PXAT `unix-time-milliseconds` — Set the specified Unix time at which the fields will expire, in milliseconds. -* PERSIST — Remove the expiration time associated with the fields. - -Note for the following: - -1. The EX, PX, EXAT, PXAT, and PERSIST options are mutually exclusive. -2. Providing '0' expiration TTL via `EX` or `PX` optional arguments will cause the specified fields to expire immediately and be removed from the hash. -3. Providing past expiration time via `EXAT` or `PXAT` optional arguments will cause the specified fields to expire immediately and be removed from the hash. - -## Reply - -Array of values associated with the given fields, in the same order as they are requested. - -## Examples - -``` -127.0.0.1:6379> HSET myhash f1 v1 f2 v2 f3 v3 -(integer) 3 -127.0.0.1:6379> HGETEX myhash EX 10 FIELDS 2 f2 f3 -1) "v2" -2) "v3" -127.0.0.1:6379> HTTL myhash FIELDS 3 f1 f2 f3 -1) (integer) -1 -2) (integer) 8 -3) (integer) 8 -127.0.0.1:6379> HGETEX myhash EX 0 FIELDS 3 f1 f2 f3 -1) "v1" -2) "v2" -3) "v3" -127.0.0.1:6379> HGETEX myhash FIELDS 3 f1 f2 f3 -1) (nil) -2) (nil) -3) (nil) -``` diff --git a/commands/hincrby.md b/commands/hincrby.md deleted file mode 100644 index 517cb12d..00000000 --- a/commands/hincrby.md +++ /dev/null @@ -1,27 +0,0 @@ -Increments the number stored at `field` in the hash stored at `key` by -`increment`. -If `key` does not exist, a new key holding a hash is created. -If `field` does not exist the value is set to `0` before the operation is -performed. - -The range of values supported by `HINCRBY` is limited to 64 bit signed integers. - -## Reply - -Integer: the value of the field after the increment operation. - -## Examples - -Since the `increment` argument is signed, both increment and decrement -operations can be performed: - -``` -127.0.0.1:6379> HSET myhash field 5 -(integer) 1 -127.0.0.1:6379> HINCRBY myhash field 1 -(integer) 6 -127.0.0.1:6379> HINCRBY myhash field -1 -(integer) 5 -127.0.0.1:6379> HINCRBY myhash field -10 -(integer) -5 -``` diff --git a/commands/hincrbyfloat.md b/commands/hincrbyfloat.md deleted file mode 100644 index de0b2904..00000000 --- a/commands/hincrbyfloat.md +++ /dev/null @@ -1,38 +0,0 @@ -Increment the specified `field` of a hash stored at `key`, and representing a -floating point number, by the specified `increment`. If the increment value -is negative, the result is to have the hash field value **decremented** instead of incremented. -If the field does not exist, it is set to `0` before performing the operation. -An error is returned if one of the following conditions occur: - -* The key contains a value of the wrong type (not a hash). -* The current field content or the specified increment are not parsable as a - double precision floating point number. - -The exact behavior of this command is identical to the one of the `INCRBYFLOAT` -command, please refer to the documentation of [`INCRBYFLOAT`](incrbyfloat.md) for further -information. - -## Reply - -String: the value of the field after the increment operation. - -## Examples - -``` -127.0.0.1:6379> HSET mykey field 10.50 -(integer) 1 -127.0.0.1:6379> HINCRBYFLOAT mykey field 0.1 -"10.6" -127.0.0.1:6379> HINCRBYFLOAT mykey field -5 -"5.6" -127.0.0.1:6379> HSET mykey field 5.0e3 -(integer) 0 -127.0.0.1:6379> HINCRBYFLOAT mykey field 2.0e2 -"5200" -``` - -## Implementation details - -The command is always propagated in the replication link and the Append Only -File as a [`HSET`](hset.md) operation, so that differences in the underlying floating point -math implementation will not be sources of inconsistency. diff --git a/commands/hkeys.md b/commands/hkeys.md deleted file mode 100644 index 11b5cb65..00000000 --- a/commands/hkeys.md +++ /dev/null @@ -1,17 +0,0 @@ -Returns all field names in the hash stored at `key`. - -## Reply - -Array of fields in the hash, or an empty array when the key does not exist. - -## Examples - -``` -127.0.0.1:6379> HSET myhash field1 "Hello" -(integer) 1 -127.0.0.1:6379> HSET myhash field2 "World" -(integer) 1 -127.0.0.1:6379> HKEYS myhash -1) "field1" -2) "field2" -``` diff --git a/commands/hlen.md b/commands/hlen.md deleted file mode 100644 index 170a51b1..00000000 --- a/commands/hlen.md +++ /dev/null @@ -1,16 +0,0 @@ -Returns the number of fields contained in the hash stored at `key`. - -## Reply - -Integer: the number of fields in the hash, or 0 when the key does not exist. - -## Examples - -``` -127.0.0.1:6379> HSET myhash field1 "Hello" -(integer) 1 -127.0.0.1:6379> HSET myhash field2 "World" -(integer) 1 -127.0.0.1:6379> HLEN myhash -(integer) 2 -``` diff --git a/commands/hmget.md b/commands/hmget.md deleted file mode 100644 index a5dd68be..00000000 --- a/commands/hmget.md +++ /dev/null @@ -1,21 +0,0 @@ -Returns the values associated with the specified `fields` in the hash stored at -`key`. - -For every `field` that does not exist in the hash, a `nil` value is returned. -Because non-existing keys are treated as empty hashes, running `HMGET` against -a non-existing `key` will return a list of `nil` values. - -``` -127.0.0.1:6379> HSET myhash field1 "Hello" -(integer) 1 -127.0.0.1:6379> HSET myhash field2 "World" -(integer) 1 -127.0.0.1:6379> HMGET myhash field1 field2 nofield -1) "Hello" -2) "World" -3) (nil) -``` - -## Reply - -Array of values associated with the given fields, in the same order as they are requested. diff --git a/commands/hmset.md b/commands/hmset.md deleted file mode 100644 index 48bb6ada..00000000 --- a/commands/hmset.md +++ /dev/null @@ -1,23 +0,0 @@ -Sets the specified fields to their respective values in the hash stored at -`key`. -This command overwrites any specified fields already existing in the hash. -If `key` does not exist, a new key holding a hash is created. - -## Alternative - -`HSET` with multiple field-value pairs. - -## Reply - -`OK`. - -## Examples - -``` -127.0.0.1:6379> HMSET myhash field1 "Hello" field2 "World" -OK -127.0.0.1:6379> HGET myhash field1 -"Hello" -127.0.0.1:6379> HGET myhash field2 -"World" -``` diff --git a/commands/hotkeys-get.md b/commands/hotkeys-get.md deleted file mode 100644 index bacf52f7..00000000 --- a/commands/hotkeys-get.md +++ /dev/null @@ -1,56 +0,0 @@ -The `HOTKEYS GET` command returns the hottest keys observed during the last -completed tracking window, ordered by estimated queries per second (QPS), from -highest to lowest. It takes no arguments and returns at most `hotkeys-top-k` -entries. - -See [`HOTKEYS`](hotkeys.md) and [Hot key tracking](../topics/hotkeys.md) for how -tracking is enabled and configured, what an empty reply can mean, and how state -is reset. - -Each entry contains: - -* `key`: the key name. -* `db`: the database in which the key was accessed. -* `qps`: the estimated accesses per second over the completed window. - -`qps` is an estimate rather than an exact value, because accesses are sampled -when `hotkeys-sampling-percentage` is below `100` (its default is `1`), and -because only `hotkeys-top-k` keys are tracked at a time. It is a rate over the -span the window actually covered, which can be slightly longer than -`hotkeys-window-seconds`. See -[Choosing the sampling percentage and window](../topics/hotkeys.md#choosing-the-sampling-percentage-and-window) -for how accuracy depends on those two settings. - -A key that is accessed but does not exist is tracked like any other. This -surfaces load against a missing key, for example from a bad key template or a -stampede against a key an eviction just removed. - -The command returns an empty array when there is nothing to report: either hot -key tracking is disabled, or no hot keys were tracked in the last completed -window. - -## Reply - -Array of the hottest keys of the last completed window, ordered by estimated QPS descending. Each element is a map with the fields `key`, `db` and `qps`. - -## Examples - -Enable tracking, then read the hottest keys: - -``` -127.0.0.1:6379> CONFIG SET hotkeys-top-k 16 -OK -127.0.0.1:6379> HOTKEYS GET -1) 1) "key" - 2) "product:8fd21a" - 3) "db" - 4) (integer) 0 - 5) "qps" - 6) (integer) 48200 -2) 1) "key" - 2) "session:2c1f09" - 3) "db" - 4) (integer) 0 - 5) "qps" - 6) (integer) 12700 -``` diff --git a/commands/hotkeys-help.md b/commands/hotkeys-help.md deleted file mode 100644 index b9fe4fdc..00000000 --- a/commands/hotkeys-help.md +++ /dev/null @@ -1,7 +0,0 @@ -The `HOTKEYS HELP` command returns helpful text about the -[`HOTKEYS`](hotkeys.md) subcommands. To learn more about hot key tracking, see -[Hot key tracking](../topics/hotkeys.md). - -## Reply - -Array of sub-commands and their descriptions. diff --git a/commands/hotkeys-reset.md b/commands/hotkeys-reset.md deleted file mode 100644 index dea23486..00000000 --- a/commands/hotkeys-reset.md +++ /dev/null @@ -1,21 +0,0 @@ -The `HOTKEYS RESET` command clears all accumulated hot key statistics on this -node, discarding both the in-progress window and the last completed one. It takes -no arguments. It always replies `OK`, including when hot key tracking is -disabled, in which case there is nothing to clear. - -Use it to start monitoring from a clean baseline, without changing the -configuration. - -Hot key state is also cleared automatically by several server events. See -[Hot key tracking](../topics/hotkeys.md) for the list. - -## Reply - -`OK`. - -## Examples - -``` -127.0.0.1:6379> HOTKEYS RESET -OK -``` diff --git a/commands/hotkeys.md b/commands/hotkeys.md deleted file mode 100644 index bfc482ea..00000000 --- a/commands/hotkeys.md +++ /dev/null @@ -1,6 +0,0 @@ -This is a container command for hot key tracking commands. To see the list of -available subcommands, run [`HOTKEYS HELP`](hotkeys-help.md). - -See [Hot key tracking](../topics/hotkeys.md) for the feature: how tracking -works, how to enable and configure it, what counts as an access, and when state -is cleared. diff --git a/commands/hpersist.md b/commands/hpersist.md deleted file mode 100644 index d395d28e..00000000 --- a/commands/hpersist.md +++ /dev/null @@ -1,32 +0,0 @@ -The `HPERSIST` remove the existing expiration on a hash key's field(s), turning the field(s) from volatile (a field with expiration set) -to persistent (a field that will never expire as no TTL (time to live) is associated). - -## Reply - -Array of integer codes indicating the result of setting expiry on each specified field, in the same order as the fields are requested. - -* -2: Field does not exist in the provided hash key, or the hash key does not exist. -* -1: Field exists in the provided hash key, but has no expiration associated with it. -* 1: The expiration time was removed from the hash key field. - -## Examples - -``` -127.0.0.1:6379> HSET myhash f1 v1 f2 v2 f3 v3 -(integer) 3 -27.0.0.1:6379> HEXPIRE myhash 1000 FIELDS 2 f2 f3 -1) (integer) 1 -2) (integer) 1 -127.0.0.1:6379> HTTL myhash FIELDS 3 f1 f2 f3 -1) (integer) -1 -2) (integer) 998 -3) (integer) 998 -127.0.0.1:6379> HPERSIST myhash FIELDS 3 f1 f2 f3 -1) (integer) -1 -2) (integer) 1 -3) (integer) 1 -127.0.0.1:6379> HTTL myhash FIELDS 3 f1 f2 f3 -1) (integer) -1 -2) (integer) -1 -3) (integer) -1 -``` diff --git a/commands/hpexpire.md b/commands/hpexpire.md deleted file mode 100644 index 5f7fa24a..00000000 --- a/commands/hpexpire.md +++ /dev/null @@ -1,35 +0,0 @@ -This command works exactly like [`HEXPIRE`](hexpire.md) but the time to live of the field(s) is -specified in milliseconds instead of seconds. -Note, that providing a millisecond time of '0' will cause immediate expiration and reclamation of the field(s). - -## Options - -The `HPEXPIRE` command supports a set of options that modify its behavior: - -* NX — For each specified field, set expiration only when the field has no expiration. -* XX — For each specified field, set expiration only when the field has an existing expiration. -* GT — For each specified field, set expiration only when the new expiration is greater than current one. -* LT — For each specified field, set expiration only when the new expiration is less than current one. - -## Reply - -Array of integer codes indicating the result of setting expiry on each specified field, in the same order as the fields are requested. - -* -2: Field does not exist in the HASH, or key does not exist. -* 0: The specified NX | XX | GT | LT condition has not been met. -* 1: The expiration time was applied. -* 2: When called with 0 seconds. - -## Examples - -``` -127.0.0.1:6379> HSET myhash f1 v1 f2 v2 f3 v3 -(integer) 3 -127.0.0.1:6379> HPEXPIRE myhash 10000 FIELDS 2 f2 f3 -1) (integer) 1 -2) (integer) 1 -127.0.0.1:6379> HPTTL myhash FIELDS 3 f1 f2 f3 -1) (integer) -1 -2) (integer) 9597 -3) (integer) 9597 -``` diff --git a/commands/hpexpireat.md b/commands/hpexpireat.md deleted file mode 100644 index d868e126..00000000 --- a/commands/hpexpireat.md +++ /dev/null @@ -1,39 +0,0 @@ -`HEXPIREAT` has the same effect and semantic as [`HPEXPIRE`](hpexpire.md), but instead of -specifying the number of milliseconds representing the TTL (time to live), it takes -an absolute Unix timestamp (milliseconds since January 1, 1970). A -timestamp in the past will delete the key immediately. - -For the specific semantics of the command refer to the documentation of -[`HPEXPIRE`](hpexpire.md). - -## Options - -The `HPEXPIREAT` command supports a set of options that modify its behavior: - -* NX — For each specified field, set expiration only when the field has no expiration. -* XX — For each specified field, set expiration only when the field has an existing expiration. -* GT — For each specified field, set expiration only when the new expiration is greater than current one. -* LT — For each specified field, set expiration only when the new expiration is less than current one. - -## Reply - -Array of integer codes indicating the result of setting expiry on each specified field, in the same order as the fields are requested. - -* -2: Field does not exist in the HASH, or key does not exist. -* 0: The specified NX | XX | GT | LT condition has not been met. -* 1: The expiration time was applied. -* 2: When called with 0 seconds. - -## Examples - -``` -127.0.0.1:6379> HSET myhash f1 v1 f2 v2 f3 v3 -(integer) 3 -127.0.0.1:6379> HPEXPIREAT myhash 1754847944000 FIELDS 2 f2 f3 -1) (integer) 1 -2) (integer) 1 -127.0.0.1:6379> HPEXPIRETIME myhash FIELDS 3 f1 f2 f3 -1) (integer) -1 -2) (integer) 1754847944000 -3) (integer) 1754847944000 -``` diff --git a/commands/hpexpiretime.md b/commands/hpexpiretime.md deleted file mode 100644 index 574c6449..00000000 --- a/commands/hpexpiretime.md +++ /dev/null @@ -1,26 +0,0 @@ -The `HPEXPIRETIME` command returns the absolute Unix timestamp (since January 1, 1970) in milliseconds at which the given hash field(s) will expire. - -See also the [`HEXPIRETIME`](hexpiretime.md) command which returns the same information with seconds resolution. - -## Reply - -Array of values associated with the result of getting the absolute expiry timestamp of the specific fields, in the same order as they are requested. - -* -2: Field does not exist in the provided hash key, or the hash key is empty. -* -1: Field exists in the provided hash key, but has no expiration associated with it. -* Integer: The expiration time associated with the hash key field, in milliseconds. - -## Examples - -``` -127.0.0.1:6379> HSET myhash f1 v1 f2 v2 f3 v3 -(integer) 3 -27.0.0.1:6379> HPEXPIREAT myhash 1754847944000 FIELDS 2 f2 f3 -1) (integer) 1 -2) (integer) 1 -127.0.0.1:6379> HPEXPIRETIME myhash FIELDS 4 f1 f2 f3 non-exist -1) (integer) -1 -2) (integer) 1754847944000 -3) (integer) 1754847944000 -4) (integer) -2 -``` diff --git a/commands/hpttl.md b/commands/hpttl.md deleted file mode 100644 index e52bf40d..00000000 --- a/commands/hpttl.md +++ /dev/null @@ -1,27 +0,0 @@ -Like [`HTTL`](httl.md) this command returns the remaining time to live of hash field(s) that has an associated expiration time, -with the sole difference that `HTTL` returns the amount of remaining -time in seconds while `HPTTL` returns it in milliseconds. - -See also the [`HTTL`](httl.md) command that returns the same information with seconds resolution. - -## Reply - -Array of values associated with the result of getting the remaining time-to-live of the specific fields, in the same order as they are requested. - -* -2: Field does not exist in the provided hash key, or the hash key is empty. -* -1: Field exists in the provided hash key, but has no expiration associated with it. -* Integer: The expiration time associated with the hash key field, in milliseconds. - -## Examples - -``` -127.0.0.1:6379> HSET myhash f1 v1 f2 v2 f3 v3 -(integer) 3 -27.0.0.1:6379> HPEXPIRE myhash 10000 FIELDS 2 f2 f3 -1) (integer) 1 -2) (integer) 1 -127.0.0.1:6379> HPTTL myhash FIELDS 3 f1 f2 f3 -1) (integer) -1 -2) (integer) 9597 -3) (integer) 9597 -``` diff --git a/commands/hrandfield.md b/commands/hrandfield.md deleted file mode 100644 index 346db278..00000000 --- a/commands/hrandfield.md +++ /dev/null @@ -1,54 +0,0 @@ -When called with just the `key` argument, return a random field from the hash value stored at `key`. - -If the provided `count` argument is positive, return an array of **distinct fields**. -The array's length is either `count` or the hash's number of fields ([`HLEN`](hlen.md)), whichever is lower. - -If called with a negative `count`, the behavior changes and the command is allowed to return the **same field multiple times**. -In this case, the number of returned fields is the absolute value of the specified `count`. - -The optional `WITHVALUES` modifier changes the reply so it includes the respective values of the randomly selected hash fields. - -## Reply - -Any of the following: - -* Null: if the key doesn't exist -* String: a single, randomly selected field when the `count` option is not used -* Array containing `count` fields when the `count` option is used, or an empty array if the key does not exists. -* Array of fields and their values when `count` and `WITHVALUES` were both used. - -## Examples - -``` -127.0.0.1:6379> HSET coin heads obverse tails reverse edge null -(integer) 3 -127.0.0.1:6379> HRANDFIELD coin -"heads" -127.0.0.1:6379> HRANDFIELD coin -"heads" -127.0.0.1:6379> HRANDFIELD coin -5 WITHVALUES - 1) "heads" - 2) "obverse" - 3) "tails" - 4) "reverse" - 5) "edge" - 6) "null" - 7) "heads" - 8) "obverse" - 9) "edge" -10) "null" -``` - -## Specification of the behavior when count is passed - -When the `count` argument is a positive value this command behaves as follows: - -* No repeated fields are returned. -* If `count` is bigger than the number of fields in the hash, the command will only return the whole hash without additional fields. -* The order of fields in the reply is not truly random, so it is up to the client to shuffle them if needed. - -When the `count` is a negative value, the behavior changes as follows: - -* Repeating fields are possible. -* Exactly `count` fields, or an empty array if the hash is empty (non-existing key), are always returned. -* The order of fields in the reply is truly random. diff --git a/commands/hscan.md b/commands/hscan.md deleted file mode 100644 index ad4a6910..00000000 --- a/commands/hscan.md +++ /dev/null @@ -1,8 +0,0 @@ -See [`SCAN`](scan.md) for `HSCAN` documentation. - -## Reply - -Two-element array. - -* The first element is a string that represents an unsigned 64-bit number, the cursor. -* The second element is an array of field/value pairs that were scanned. When `NOVALUES` option is on, a list of keys from the hash. diff --git a/commands/hset.md b/commands/hset.md deleted file mode 100644 index d4bd0a56..00000000 --- a/commands/hset.md +++ /dev/null @@ -1,30 +0,0 @@ -Sets the specified fields to their respective values in the hash stored at `key`. - -This command overwrites the values of specified fields that exist in the hash. -If `key` doesn't exist, a new key holding a hash is created. - -## Reply - -Integer: the number of fields that were added. - -## Examples - -``` -127.0.0.1:6379> HSET myhash field1 "Hello" -(integer) 1 -127.0.0.1:6379> HGET myhash field1 -"Hello" -127.0.0.1:6379> HSET myhash field2 "Hi" field3 "World" -(integer) 2 -127.0.0.1:6379> HGET myhash field2 -"Hi" -127.0.0.1:6379> HGET myhash field3 -"World" -127.0.0.1:6379> HGETALL myhash -1) "field1" -2) "Hello" -3) "field2" -4) "Hi" -5) "field3" -6) "World" -``` diff --git a/commands/hsetex.md b/commands/hsetex.md deleted file mode 100644 index bcc6a8fa..00000000 --- a/commands/hsetex.md +++ /dev/null @@ -1,81 +0,0 @@ -The `HSETEX` command allows setting the value of one or more fields of a given hash key, and optionally manipulating their expiration time. -The command will return 1 in case all provided fields have been set or 0 in case `FNX` or `FXX` were provided and none of the specified fields were set. -Without providing any optional flags, this command behaves exactly like a normal [`HSET`](hset.md) command. - -## Options - -The `HSETEX` command supports a set of options that modify its behavior: - -* FNX — Only set the fields if none of them already exist. -* FXX — Only set the fields if all of them already exist. -* EX seconds — Set the specified expiration time in seconds. -* PX milliseconds — Set the specified expiration time in milliseconds. -* EXAT `unix-time-seconds` — Set the specified Unix time in seconds for when the fields will expire. -* PXAT `unix-time-milliseconds` — Set the specified Unix time in milliseconds at which the fields will expire. -* KEEPTTL — Retain the TTL associated with the fields. - -Note for the following: - -1. The EX, PX, EXAT, PXAT, and KEEPTTL options are mutually exclusive. -2. Setting a value on a volatile hash field (A field which has an assigned expiration time) will remove the expiration for that field. -3. Providing '0' expiration TTL via `EX` or `PX` optional arguments will result in the specified fields immediately expiring and being removed from the hash. -4. Providing past expiration time via `EXAT` or `PXAT` optional arguments will result in the specified fields immediately expiring and being removed from the hash. - -## Reply - -One of the following: - -* Integer: `0` if none of the provided fields' values and/or expiration times were set. -* Integer: `1` if all the fields' values and/or expiration times were set. - -## Examples - -Add 3 new items without expiration time to a 'myhash' -``` -127.0.0.1:6379> HSETEX myhash FIELDS 3 f1 v1 f2 v2 f3 v3 -(integer) 1 -``` - -Unsuccessful attempt setting expiration time on EXISTING fields -``` -127.0.0.1:6379> HSETEX myhash FNX EX 10 FIELDS 2 f2 v2 f3 v3 -(integer) 0 -``` - -Successful attempt setting expiration time on EXISTING fields -``` -127.0.0.1:6379> HSETEX myhash FXX EX 10 FIELDS 2 f2 v2 f3 v3 -(integer) 1 -``` - -Verify hash fields expiration time: -``` -127.0.0.1:6379> HTTL myhash FIELDS 3 f1 f2 f3 -1) (integer) -1 -2) (integer) 8 -3) (integer) 8 -``` - -Override all hash items will also persist the fields -``` -127.0.0.1:6379> HSETEX myhash FIELDS 3 f1 v1 f2 v2 f3 v3 -(integer) 1 -127.0.0.1:6379> HTTL myhash FIELDS 3 f1 f2 f3 -1) (integer) -1 -2) (integer) -1 -3) (integer) -1 -``` - -Setting expiration time in the past will remove all the elements in the hash: -``` -127.0.0.1:6379> HSETEX EX 0 myhash FIELDS 3 f1 v1 f2 v2 f3 v3 -(integer) 1 -127.0.0.1:6379> HTTL myhash FIELDS 3 f1 f2 f3 -1) (integer) -2 -2) (integer) -2 -3) (integer) -2 -127.0.0.1:6379> HLEN myhash -(integer) 0 -127.0.0.1:6379> EXISTS myhash -(integer) 0 -``` diff --git a/commands/hsetnx.md b/commands/hsetnx.md deleted file mode 100644 index ad5ff776..00000000 --- a/commands/hsetnx.md +++ /dev/null @@ -1,22 +0,0 @@ -Sets `field` in the hash stored at `key` to `value`, only if `field` does not -yet exist. -If `key` does not exist, a new key holding a hash is created. -If `field` already exists, this operation has no effect. - -## Reply - -One of the following: - -* Integer: `0` if the field already exists in the hash and no operation was performed. -* Integer: `1` if the field is a new field in the hash and the value was set. - -## Examples - -``` -127.0.0.1:6379> HSETNX myhash field "Hello" -(integer) 1 -127.0.0.1:6379> HSETNX myhash field "World" -(integer) 0 -127.0.0.1:6379> HGET myhash field -"Hello" -``` diff --git a/commands/hstrlen.md b/commands/hstrlen.md deleted file mode 100644 index 9a3bd217..00000000 --- a/commands/hstrlen.md +++ /dev/null @@ -1,18 +0,0 @@ -Returns the string length of the value associated with `field` in the hash stored at `key`. If the `key` or the `field` do not exist, 0 is returned. - -## Reply - -Integer: the string length of the value associated with the _field_, or zero when the _field_ isn't present in the hash or the _key_ doesn't exist at all. - -## Examples - -``` -127.0.0.1:6379> HSET myhash f1 HelloWorld f2 99 f3 -256 -(integer) 3 -127.0.0.1:6379> HSTRLEN myhash f1 -(integer) 10 -127.0.0.1:6379> HSTRLEN myhash f2 -(integer) 2 -127.0.0.1:6379> HSTRLEN myhash f3 -(integer) 4 -``` diff --git a/commands/httl.md b/commands/httl.md deleted file mode 100644 index 7f005450..00000000 --- a/commands/httl.md +++ /dev/null @@ -1,28 +0,0 @@ -The `HTTL` command returns the remaining time to live of hash field(s) with associated expiration time(s). -This introspection capability allows a Valkey client to check how many seconds a -given hash field will continue to be part of the hash object. - -See also the [`HPTTL`](hpttl.md) command that returns the same information with milliseconds resolution. - -## Reply - -Array of values associated with the result of getting the remaining time-to-live of the specific fields, in the same order as they are requested. - -* -2: Field does not exist in the provided hash key, or the hash key is empty. -* -1: Field exists in the provided hash key, but has no expiration associated with it. -* Integer: The expiration time associated with the hash key field, in seconds. - -## Examples - -``` -127.0.0.1:6379> HSET myhash f1 v1 f2 v2 f3 v3 -(integer) 3 -27.0.0.1:6379> HEXPIRE myhash 10 FIELDS 2 f2 f3 -1) (integer) 1 -2) (integer) 1 -127.0.0.1:6379> HTTL myhash FIELDS 4 f1 f2 f3 non-exist -1) (integer) -1 -2) (integer) 8 -3) (integer) 8 -4) (integer) -2 -``` diff --git a/commands/hvals.md b/commands/hvals.md deleted file mode 100644 index cca730b7..00000000 --- a/commands/hvals.md +++ /dev/null @@ -1,17 +0,0 @@ -Returns all values in the hash stored at `key`. - -## Reply - -Array of values in the hash, or an empty array when the key does not exist. - -## Examples - -``` -127.0.0.1:6379> HSET myhash field1 "Hello" -(integer) 1 -127.0.0.1:6379> HSET myhash field2 "World" -(integer) 1 -127.0.0.1:6379> HVALS myhash -1) "Hello" -2) "World" -``` diff --git a/commands/incr.md b/commands/incr.md deleted file mode 100644 index 8aa88c6a..00000000 --- a/commands/incr.md +++ /dev/null @@ -1,166 +0,0 @@ -Increments the number stored at `key` by one. -If the key does not exist, it is set to `0` before performing the operation. -An error is returned if the key contains a value of the wrong type or contains a -string that can not be represented as integer. -This operation is limited to 64 bit signed integers. - -**Note**: this is a string operation because Valkey does not have a dedicated -integer type. -The string stored at the key is interpreted as a base-10 **64 bit signed -integer** to execute the operation. - -Valkey stores integers in their integer representation, so for string values -that actually hold an integer, there is no overhead for storing the string -representation of the integer. - -## Reply - -Integer: the value of the key after the increment. - -## Examples - -``` -127.0.0.1:6379> SET mykey "10" -OK -127.0.0.1:6379> INCR mykey -(integer) 11 -127.0.0.1:6379> GET mykey -"11" -``` - -## Pattern: Counter - -The counter pattern is the most obvious thing you can do with Valkey atomic -increment operations. -The idea is simply send an `INCR` command to Valkey every time an operation -occurs. -For instance in a web application we may want to know how many page views this -user did every day of the year. - -To do so the web application may simply increment a key every time the user -performs a page view, creating the key name concatenating the User ID and a -string representing the current date. - -This simple pattern can be extended in many ways: - -* It is possible to use `INCR` and `EXPIRE` together at every page view to have - a counter counting only the latest N page views separated by less than the - specified amount of seconds. -* A client may use GETSET in order to atomically get the current counter value - and reset it to zero. -* Using other atomic increment/decrement commands like `DECR` or `INCRBY` it - is possible to handle values that may get bigger or smaller depending on the - operations performed by the user. - Imagine for instance the score of different users in an online game. - -## Pattern: Rate limiter - -The rate limiter pattern is a special counter that is used to limit the rate at -which an operation can be performed. -The classical materialization of this pattern involves limiting the number of -requests that can be performed against a public API. - -We provide two implementations of this pattern using `INCR`, where we assume -that the problem to solve is limiting the number of API calls to a maximum of -_ten requests per second per IP address_. - -## Pattern: Rate limiter 1 - -The more simple and direct implementation of this pattern is the following: - -``` -FUNCTION LIMIT_API_CALL(ip) -ts = CURRENT_UNIX_TIME() -keyname = ip+":"+ts -MULTI - INCR(keyname) - EXPIRE(keyname,10) -EXEC -current = RESPONSE_OF_INCR_WITHIN_MULTI -IF current > 10 THEN - ERROR "too many requests per second" -ELSE - PERFORM_API_CALL() -END -``` - -Basically we have a counter for every IP, for every different second. -But these counters are always incremented setting an expire of 10 seconds so that -they'll be removed by Valkey automatically when the current second is a different -one. - -Note the used of `MULTI` and `EXEC` in order to make sure that we'll both -increment and set the expire at every API call. - -## Pattern: Rate limiter 2 - -An alternative implementation uses a single counter, but is a bit more complex -to get it right without race conditions. -We'll examine different variants. - -``` -FUNCTION LIMIT_API_CALL(ip): -current = GET(ip) -IF current != NULL AND current > 10 THEN - ERROR "too many requests per second" -ELSE - value = INCR(ip) - IF value == 1 THEN - EXPIRE(ip,1) - END - PERFORM_API_CALL() -END -``` - -The counter is created in a way that it only will survive one second, starting -from the first request performed in the current second. -If there are more than 10 requests in the same second the counter will reach a -value greater than 10, otherwise it will expire and start again from 0. - -**In the above code there is a race condition**. -If for some reason the client performs the `INCR` command but does not perform -the `EXPIRE` the key will be leaked until we'll see the same IP address again. - -This can be fixed easily turning the `INCR` with optional `EXPIRE` into a Lua -script that is send using the `EVAL` command (only available since Valkey version -2.6). - -``` -local current -current = server.call("incr",KEYS[1]) -if current == 1 then - server.call("expire",KEYS[1],1) -end -``` - -There is a different way to fix this issue without using scripting, by using -Lists instead of counters. -The implementation is more complex and uses more advanced features but has the -advantage of remembering the IP addresses of the clients currently performing an -API call, that may be useful or not depending on the application. - -``` -FUNCTION LIMIT_API_CALL(ip) -current = LLEN(ip) -IF current > 10 THEN - ERROR "too many requests per second" -ELSE - IF EXISTS(ip) == FALSE - MULTI - RPUSH(ip,ip) - EXPIRE(ip,1) - EXEC - ELSE - RPUSHX(ip,ip) - END - PERFORM_API_CALL() -END -``` - -The `RPUSHX` command only pushes the element if the key already exists. - -Note that we have a race here, but it is not a problem: `EXISTS` may return -false but the key may be created by another client before we create it inside -the `MULTI` / `EXEC` block. -However this race will just miss an API call under rare conditions, so the rate -limiting will still work correctly. diff --git a/commands/incrby.md b/commands/incrby.md deleted file mode 100644 index 31fc3b7d..00000000 --- a/commands/incrby.md +++ /dev/null @@ -1,20 +0,0 @@ -Increments the number stored at `key` by `increment`. -If the key does not exist, it is set to `0` before performing the operation. -An error is returned if the key contains a value of the wrong type or contains a -string that can not be represented as integer. -This operation is limited to 64 bit signed integers. - -See `INCR` for extra information on increment/decrement operations. - -## Reply - -Integer: the value of the key after the increment. - -## Examples - -``` -127.0.0.1:6379> SET mykey "10" -OK -127.0.0.1:6379> INCRBY mykey 5 -(integer) 15 -``` diff --git a/commands/incrbyfloat.md b/commands/incrbyfloat.md deleted file mode 100644 index aed29a58..00000000 --- a/commands/incrbyfloat.md +++ /dev/null @@ -1,49 +0,0 @@ -Increment the string representing a floating point number stored at `key` by the -specified `increment`. By using a negative `increment` value, the result is -that the value stored at the key is decremented (by the obvious properties -of addition). -If the key does not exist, it is set to `0` before performing the operation. -An error is returned if one of the following conditions occur: - -* The key contains a value of the wrong type (not a string). -* The current key content or the specified increment are not parsable as a - double precision floating point number. - -If the command is successful the new incremented value is stored as the new -value of the key (replacing the old one), and returned to the caller as a -string. - -Both the value already contained in the string key and the increment argument -can be optionally provided in exponential notation, however the value computed -after the increment is stored consistently in the same format, that is, an -integer number followed (if needed) by a dot, and a variable number of digits -representing the decimal part of the number. -Trailing zeroes are always removed. - -The precision of the output is fixed at 17 digits after the decimal point -regardless of the actual internal precision of the computation. - -## Reply - -String: the value of the key after the increment. - -## Examples - -``` -127.0.0.1:6379> SET mykey 10.50 -OK -127.0.0.1:6379> INCRBYFLOAT mykey 0.1 -"10.6" -127.0.0.1:6379> INCRBYFLOAT mykey -5 -"5.6" -127.0.0.1:6379> SET mykey 5.0e3 -OK -127.0.0.1:6379> INCRBYFLOAT mykey 2.0e2 -"5200" -``` - -## Implementation details - -The command is always propagated in the replication link and the Append Only -File as a `SET` operation, so that differences in the underlying floating point -math implementation will not be sources of inconsistency. diff --git a/commands/increx.md b/commands/increx.md deleted file mode 100644 index 8701029f..00000000 --- a/commands/increx.md +++ /dev/null @@ -1,131 +0,0 @@ -Increments the numeric value stored at `key`, optionally setting or updating its expiration in the same atomic operation. -If the key does not exist, its value is treated as `0`. -An error is returned if the key contains a value of the wrong type or contains a -string that cannot be represented as an integer, or as a floating-point number with `BYFLOAT`. - -By default the increment is `1`. Use `BYINT` to increment by a 64 bit signed -integer, or `BYFLOAT` to increment by a floating-point number. - -`INCREX` combines what is usually done with `INCR`/`INCRBY`/`INCRBYFLOAT` plus -`EXPIRE` (or a `MULTI`/`EXEC` block or Lua script) into a single command, and -adds optional lower and upper bounds on the resulting value. - -## Options - -### Condition - -* `NX` -- Only perform the operation if the key does not already exist. -* `XX` -- Only perform the operation if the key already exists. - -### Expiration - -* `EX seconds` -- Set the expire time, in seconds. -* `PX milliseconds` -- Set the expire time, in milliseconds. -* `EXAT unix-time-seconds` -- Set the expire time to a Unix timestamp, in seconds. -* `PXAT unix-time-milliseconds` -- Set the expire time to a Unix timestamp, in milliseconds. -* `PERSIST` -- Remove the existing expiration from the key. -* `ENX` -- Only set the expiration if the key currently has no TTL. - Requires one of `EX`, `PX`, `EXAT` or `PXAT`, and cannot be combined with `PERSIST`. - -Without an expiration option, the key keeps its existing TTL. With `EX`, `PX`, -`EXAT` or `PXAT`, the TTL is set on every applied increment unless `ENX` is given. -A call that is skipped or rejected never changes the TTL. - -### Increment - -* `BYINT increment` -- Increment by a 64 bit signed integer. -* `BYFLOAT increment` -- Increment by a floating-point number. - -### Bounds - -* `LBOUND lowerbound` -- The minimum allowed value of the result. -* `UBOUND upperbound` -- The maximum allowed value of the result. -* `SATURATE` -- If the result would be out of bounds, clamp it to `LBOUND`/`UBOUND` - (or to the limits of the numeric type when no explicit bound is given) instead - of rejecting the operation. - -The bound values are integers by default and with `BYINT`, and floating-point numbers -when used with `BYFLOAT`. - -Without `SATURATE`, an operation that would take the value out of bounds is -rejected: the value is left unchanged and the reply is `[current_value, 0]`. -This includes an increment that would overflow a 64 bit signed integer, which -`INCRBY` reports as an error instead. - -Bounds are checked against the result, not the current value. If the value is -already out of bounds, an increment that leaves it out of bounds is rejected even -if it moves the value toward the range, and with `SATURATE` the value is set to -the bound, so the applied increment can have the opposite sign. For example, if -the value is `50`, `INCREX mykey BYINT 1 UBOUND 20 SATURATE` replies `[20, -30]`. - -## Reply - -Array: a two-element array of Integers, or of Doubles when `BYFLOAT` is used. - -1. The value of the key after the operation. If the increment was not applied, - this is the current value of the key. -2. The increment that was actually applied. This is `0` if the operation was - skipped (for example because of `NX`/`XX`) or rejected because it was out of - bounds, and may differ from the requested increment when `SATURATE` clamps - the result. - -## Examples - -``` -127.0.0.1:6379> SET mykey "10" -OK -127.0.0.1:6379> INCREX mykey -1) (integer) 11 -2) (integer) 1 -127.0.0.1:6379> INCREX myfloat BYFLOAT 2.5 -1) "2.5" -2) "2.5" -127.0.0.1:6379> INCREX mykey BYINT 5 EX 60 -1) (integer) 16 -2) (integer) 5 -127.0.0.1:6379> INCREX mykey BYINT 100 UBOUND 20 -1) (integer) 16 -2) (integer) 0 -127.0.0.1:6379> INCREX mykey BYINT 100 UBOUND 20 SATURATE -1) (integer) 20 -2) (integer) 4 -``` - -## Pattern: Fixed-window rate limiter - -A rate limiter built with `INCR` needs a `MULTI`/`EXEC` block or a Lua script -to make sure the counter always gets an expiration, otherwise the key can be -leaked if the client fails between the two commands. -`INCREX` does this in one atomic command. -With `ENX`, the expiration is set only when the counter is created, so the -window is not extended by later requests: - -``` -FUNCTION LIMIT_API_CALL(ip) -current, applied = INCREX(ip, EX 1, ENX, BYINT 1, UBOUND 10) -IF applied == 0 THEN - ERROR "too many requests per second" -ELSE - PERFORM_API_CALL() -END -``` - -The counter lives for one second from the first request in the window. Once it -reaches the upper bound of `10`, further calls are rejected (the reply is -`[10, 0]`) without modifying the counter. - -## Pattern: Bounded counter - -Use `LBOUND`, `UBOUND` and `SATURATE` to keep a value inside a range, for example -an inventory level or a score that must never go below zero: - -``` -127.0.0.1:6379> SET stock:item42 2 -OK -127.0.0.1:6379> INCREX stock:item42 BYINT -3 LBOUND 0 SATURATE -1) (integer) 0 -2) (integer) -2 -``` - -If only 2 units remain, the key is set to `0` and the second element of the -reply is `-2`, telling the caller how much was actually applied. diff --git a/commands/info.md b/commands/info.md deleted file mode 100644 index aaac113b..00000000 --- a/commands/info.md +++ /dev/null @@ -1,785 +0,0 @@ -The `INFO` command returns information and statistics about the server in a -format that is simple to parse by computers and easy to read by humans. - -The optional parameter can be used to select a specific section of information: - -* `server`: General information about the Valkey server -* `tls`: TLS information -* `clients`: Client connections section -* `memory`: Memory consumption related information -* `persistence`: RDB and AOF related information -* `stats`: General statistics -* `replication`: primary/replica replication information -* `cpu`: CPU consumption statistics -* `commandstats`: Valkey command statistics -* `latencystats`: Valkey command latency percentile distribution statistics -* `sentinel`: Valkey Sentinel section (only applicable to Sentinel instances) -* `cluster`: Valkey Cluster section -* `modules`: Modules section -* `keyspace`: Database related statistics -* `errorstats`: Valkey error statistics -* `throttling`: Throttling statistics - -It can also take the following values: - -* `all`: Return all sections (excluding module generated ones) -* `default`: Return only the default set of sections -* `everything`: Includes `all` and `modules` - -When no parameter is provided, the `default` option is assumed. - -``` -127.0.0.1:6379> INFO -# Server -redis_version:7.2.4 -server_name:valkey -valkey_version:255.255.255 -redis_git_sha1:b0d5a0f5 -redis_git_dirty:1 -redis_build_id:1cadaf78f6168f2d -server_mode:standalone -os:Linux 6.1.0-18-amd64 x86_64 -arch_bits:64 -monotonic_clock:POSIX clock_gettime -multiplexing_api:epoll -atomicvar_api:c11-builtin -gcc_version:12.2.0 -process_id:982599 -process_supervised:no -run_id:e0abe2248cad0c6d9cb2445d8e6b73448f567f74 -tcp_port:6379 -server_time_usec:1714701488527373 -uptime_in_seconds:94798 -uptime_in_days:1 -hz:10 -configured_hz:10 -lru_clock:3425456 -executable:/home/viktor/repos/valkey/src/./valkey-server -config_file: -io_threads_active:0 -availability_zone: -listener0:name=tcp,bind=*,bind=-::*,port=6379 - -# Clients -connected_clients:1 -cluster_connections:0 -maxclients:10000 -client_recent_max_input_buffer:20480 -client_recent_max_output_buffer:0 -blocked_clients:0 -tracking_clients:0 -pubsub_clients:0 -watching_clients:0 -clients_in_timeout_table:0 -total_watched_keys:0 -total_blocking_keys:0 -total_blocking_keys_on_nokey:0 -paused_reason:none -paused_actions:none -paused_timeout_milliseconds:0 - -# Memory -used_memory:4757704 -used_memory_human:4.54M -used_memory_rss:13221888 -used_memory_rss_human:12.61M -used_memory_peak:4777616 -used_memory_peak_human:4.56M -used_memory_peak_perc:99.58% -used_memory_overhead:989344 -used_memory_startup:988648 -used_memory_dataset:3768360 -used_memory_dataset_perc:99.98% -allocator_allocated:4789624 -allocator_active:5042176 -allocator_resident:9252864 -allocator_muzzy:0 -total_system_memory:33280372736 -total_system_memory_human:30.99G -used_memory_lua:31744 -used_memory_vm_eval:31744 -used_memory_lua_human:31.00K -used_memory_scripts_eval:0 -number_of_cached_scripts:0 -number_of_functions:0 -number_of_libraries:0 -used_memory_vm_functions:33792 -used_memory_vm_total:65536 -used_memory_vm_total_human:64.00K -used_memory_functions:184 -used_memory_scripts:184 -used_memory_scripts_human:184B -maxmemory:0 -maxmemory_human:0B -maxmemory_policy:noeviction -allocator_frag_ratio:1.05 -allocator_frag_bytes:252552 -allocator_rss_ratio:1.84 -allocator_rss_bytes:4210688 -rss_overhead_ratio:1.43 -rss_overhead_bytes:3969024 -mem_fragmentation_ratio:2.80 -mem_fragmentation_bytes:8504448 -mem_not_counted_for_evict:0 -mem_replication_backlog:0 -mem_total_replication_buffers:0 -mem_replicas_repl_buffer:0 -mem_clients_slaves:0 -mem_clients_normal:0 -mem_cluster_links:0 -mem_aof_buffer:0 -mem_allocator:jemalloc-5.3.0 -mem_overhead_db_hashtable_rehashing:0 -active_defrag_running:0 -lazyfree_pending_objects:0 -lazyfreed_objects:0 - -# Persistence -loading:0 -async_loading:0 -current_cow_peak:0 -current_cow_size:0 -current_cow_size_age:0 -current_fork_perc:0.00 -current_save_keys_processed:0 -current_save_keys_total:0 -rdb_changes_since_last_save:0 -rdb_bgsave_in_progress:0 -rdb_last_save_time:1714701488 -rdb_last_bgsave_status:ok -rdb_last_bgsave_time_sec:0 -rdb_current_bgsave_time_sec:-1 -rdb_saves:1 -rdb_last_cow_size:229376 -rdb_last_load_keys_expired:0 -rdb_last_load_keys_loaded:0 -aof_enabled:0 -aof_rewrite_in_progress:0 -aof_rewrite_scheduled:0 -aof_last_rewrite_time_sec:-1 -aof_current_rewrite_time_sec:-1 -aof_last_bgrewrite_status:ok -aof_rewrites:0 -aof_rewrites_consecutive_failures:0 -aof_last_write_status:ok -aof_last_cow_size:0 -module_fork_in_progress:0 -module_fork_last_cow_size:0 - -# Stats -total_connections_received:3081 -total_commands_processed:3080 -instantaneous_ops_per_sec:91 -total_net_input_bytes:134722 -total_net_output_bytes:686934 -total_net_repl_input_bytes:0 -total_net_repl_output_bytes:0 -instantaneous_input_kbps:4.14 -instantaneous_output_kbps:1.55 -instantaneous_input_repl_kbps:0.00 -instantaneous_output_repl_kbps:0.00 -rejected_connections:0 -sync_full:0 -sync_partial_ok:0 -sync_partial_err:0 -expired_keys:0 -expired_stale_perc:0.00 -expired_time_cap_reached_count:0 -expire_cycle_cpu_milliseconds:1829 -evicted_keys:0 -evicted_clients:0 -evicted_scripts:0 -total_eviction_exceeded_time:0 -current_eviction_exceeded_time:0 -keyspace_hits:877 -keyspace_misses:98 -pubsub_channels:0 -pubsub_patterns:0 -pubsubshard_channels:0 -latest_fork_usec:832 -total_forks:5 -migrate_cached_sockets:0 -slave_expires_tracked_keys:0 -active_defrag_hits:0 -active_defrag_misses:0 -active_defrag_key_hits:0 -active_defrag_key_misses:0 -total_active_defrag_time:0 -current_active_defrag_time:0 -tracking_total_keys:0 -tracking_total_items:0 -tracking_total_prefixes:0 -unexpected_error_replies:0 -total_error_replies:55 -dump_payload_sanitizations:0 -total_reads_processed:6160 -total_writes_processed:3085 -io_threaded_reads_processed:0 -io_threaded_writes_processed:0 -client_query_buffer_limit_disconnections:0 -client_output_buffer_limit_disconnections:0 -reply_buffer_shrinks:3 -reply_buffer_expands:0 -eventloop_cycles:710861 -eventloop_duration_sum:261482066 -eventloop_duration_cmd_sum:4662723 -instantaneous_eventloop_cycles_per_sec:283 -instantaneous_eventloop_duration_usec:595 -acl_access_denied_auth:0 -acl_access_denied_cmd:0 -acl_access_denied_key:0 -acl_access_denied_channel:0 -acl_access_denied_tls_cert:0 - -# Replication -role:master -connected_slaves:0 -replicas_waiting_psync:0 -master_failover_state:no-failover -master_replid:488d931b7e08f8e091f674ea64480165971a25f1 -master_replid2:0000000000000000000000000000000000000000 -master_repl_offset:0 -second_repl_offset:-1 -repl_backlog_active:0 -repl_backlog_size:1048576 -repl_backlog_first_byte_offset:0 -repl_backlog_histlen:0 - -# CPU -used_cpu_sys:68.476389 -used_cpu_user:219.408941 -used_cpu_sys_children:0.003157 -used_cpu_user_children:0.008264 -used_cpu_sys_main_thread:68.478353 -used_cpu_user_main_thread:219.404508 -used_active_time_main_thread:192.003980 - -# Modules - -# Errorstats -errorstat_ERR:count=55 - -# Cluster -cluster_enabled:0 - -# Keyspace -``` - -## Reply - -Verbatim string: a map of info fields, one field per line in the form of `:` where the value can be a comma separated map like `=`. Also contains section header lines starting with `#` and blank lines. - -Lines can contain a section name (starting with a `#` character) or a property. All the properties are in the form of `field:value` terminated by `\r\n`. - -## Notes - -Please note depending on the version of Valkey some of the fields have been -added or removed. A robust client application should therefore parse the -result of this command by skipping unknown properties, and gracefully handle -missing fields. - -Here is the description of fields. - - -Here is the meaning of all fields in the **server** section: - -* `redis_version`: Redis OSS version this Valkey server is compatible with -* `valkey_version`: Valkey version number (e.g. 7.2.5) -* `valkey_release_stage`: The status of the Valkey version: "ga" for generally available versions; "rc1", "rc2", etc. for release candidates; "dev" for development versions. Added in 8.1. -* `redis_git_sha1`: Git SHA1 -* `redis_git_dirty`: Git dirty flag -* `redis_build_id`: The build id -* `redis_mode`: The server's mode ("standalone", "sentinel" or "cluster") -* `os`: Operating system hosting the Valkey server -* `arch_bits`: Architecture (32 or 64 bits) -* `multiplexing_api`: Event loop mechanism used by Valkey -* `atomicvar_api`: Atomicvar API used by Valkey -* `gcc_version`: Version of the GCC compiler used to compile the Valkey server -* `process_id`: PID of the server process -* `process_supervised`: Supervised system ("upstart", "systemd", "unknown" or "no") -* `run_id`: Random value identifying the Valkey server (to be used by Sentinel - and Cluster) -* `tcp_port`: TCP/IP listen port -* `server_time_usec`: Epoch-based system time with microsecond precision -* `uptime_in_seconds`: Number of seconds since Valkey server start -* `uptime_in_days`: Same value expressed in days -* `hz`: The server's current frequency setting -* `configured_hz`: The server's configured frequency setting -* `clients_hz`: Current frequency for client maintenance -* `lru_clock`: Clock incrementing every minute, for LRU management -* `executable`: The path to the server's executable -* `config_file`: The path to the config file -* `io_threads_active`: Flag indicating if I/O threads are active -* `availability_zone`: Inform Valkey of the Availability zone if running in a cloud environment, see `availability-zone` config for more details. Added in Valkey 8.0. -* `shutdown_in_milliseconds`: The maximum time remaining for replicas to catch up the replication before completing the shutdown sequence. - This field is only present during shutdown. - -Here is the meaning of all fields in the **TLS** section, added in Valkey 9.1: - -* `tls_server_cert_serial`: The server certificate's serial number -* `tls_server_cert_expires_in_seconds`: Time until the server certificate expires -* `tls_server_alt_cert_serial`: The [alternate server certificate](../topics/tls.md)'s serial number. Added in Valkey 9.2 -* `tls_server_alt_cert_expires_in_seconds`: Time until the alternate server certificate expires. Added in Valkey 9.2 -* `tls_client_cert_serial`: The client certificate's serial number -* `tls_client_cert_expires_in_seconds`: Time until the client certificate expires -* `tls_ca_cert_serial`: The Certificate Authority (CA) certificate's serial number -* `tls_ca_cert_expires_in_seconds`: Time until the CA certificate expires - -Here is the meaning of all fields in the **clients** section: - -* `connected_clients`: Number of client connections (excluding connections - from replicas) -* `cluster_connections`: An approximation of the number of sockets used by the - cluster's bus -* `maxclients`: The value of the `maxclients` configuration directive. This is - the upper limit for the sum of `connected_clients`, `connected_slaves` and - `cluster_connections`. -* `client_recent_max_input_buffer`: Biggest input buffer among current client connections -* `client_recent_max_output_buffer`: Biggest output buffer among current client connections -* `blocked_clients`: Number of clients pending on a blocking call ([`BLPOP`](blpop.md)), - [`BRPOP`](brpop.md), [`BRPOPLPUSH`](brpoplpush.md), [`BLMOVE`](blmove.md), [`BZPOPMIN`](bzpopmin.md), [`BZPOPMAX`](bzpopmax.md)) -* `tracking_clients`: Number of clients being tracked ([`CLIENT TRACKING`](client-tracking.md)) -* `pubsub_clients`: Number of clients in pubsub mode ([`SUBSCRIBE`](subscribe.md), [`PSUBSCRIBE`](psubscribe.md), [`SSUBSCRIBE`](ssubscribe.md)). Added in Valkey 8.0 -* `watching_clients`: Number of clients in watching mode ([`WATCH`](watch.md)). Added in Valkey 8.0 -* `clients_in_timeout_table`: Number of clients in the clients timeout table -* `total_watched_keys`: Number of watched keys. Added in Valkey 8.0. -* `total_blocking_keys`: Number of blocking keys. -* `total_blocking_keys_on_nokey`: Number of blocking keys that one or more clients that would like to be unblocked when the key is deleted. -* `paused_reason`: The current paused reason of the instance: "client_pause" means trigger by [`CLIENT PAUSE`](client-pause.md), - "shutdown_in_progress", "failover_in_progress" and "none" means no clients are paused. Added in Valkey 8.1. -* `paused_actions`: The current paused actions of the instance: "all" means all clients are paused, - "write" means clients executing write commands are paused, - and "none" means no clients are paused. Added in Valkey 8.1. -* `paused_timeout_milliseconds`: The remaining time of the paused actions. Added in Valkey 8.1. - -Here is the meaning of all fields in the **memory** section: - -* `used_memory`: Total number of bytes allocated by Valkey using its - allocator (either standard **libc**, **jemalloc**, or an alternative - allocator such as [**tcmalloc**][hcgcpgp]) -* `used_memory_human`: Human readable representation of previous value -* `used_memory_rss`: Number of bytes that Valkey allocated as seen by the - operating system (a.k.a resident set size). This is the number reported by - tools such as `top(1)` and `ps(1)` -* `used_memory_rss_human`: Human readable representation of previous value -* `used_memory_peak`: Peak memory consumed by Valkey (in bytes) -* `used_memory_peak_human`: Human readable representation of previous value -* `used_memory_peak_perc`: The percentage of `used_memory_peak` out of - `used_memory` -* `used_memory_overhead`: The sum in bytes of all overheads that the server - allocated for managing its internal data structures -* `used_memory_startup`: Initial amount of memory consumed by Valkey at startup - in bytes -* `used_memory_dataset`: The size in bytes of the dataset - (`used_memory_overhead` subtracted from `used_memory`) -* `used_memory_dataset_perc`: The percentage of `used_memory_dataset` out of - the net memory usage (`used_memory` minus `used_memory_startup`) -* `total_system_memory`: The total amount of memory that the Valkey host has -* `total_system_memory_human`: Human readable representation of previous value -* `used_memory_lua`: Number of bytes used by the Lua engine for EVAL scripts. Deprecated, renamed to `used_memory_vm_eval` -* `used_memory_vm_eval`: Number of bytes used by the script VM engines for EVAL framework (not part of used_memory). -* `used_memory_lua_human`: Human readable representation of previous value. Deprecated. -* `used_memory_scripts_eval`: Number of bytes overhead by the EVAL scripts (part of used_memory). -* `number_of_cached_scripts`: The number of EVAL scripts cached by the server. -* `number_of_functions`: The number of functions. -* `number_of_libraries`: The number of libraries. -* `used_memory_vm_functions`: Number of bytes used by the script VM engines for Functions framework (not part of used_memory). -* `used_memory_vm_total`: `used_memory_vm_eval` + `used_memory_vm_functions` (not part of used_memory). -* `used_memory_vm_total_human`: Human readable representation of previous value. -* `used_memory_functions`: Number of bytes overhead by Function scripts (part of used_memory). -* `used_memory_scripts`: `used_memory_scripts_eval` + `used_memory_functions` (part of used_memory). -* `used_memory_scripts_human`: Human readable representation of previous value -* `maxmemory`: The value of the `maxmemory` configuration directive -* `maxmemory_human`: Human readable representation of previous value -* `maxmemory_policy`: The value of the `maxmemory-policy` configuration - directive -* `mem_fragmentation_ratio`: Ratio between `used_memory_rss` and `used_memory`. - Note that this doesn't only includes fragmentation, but also other process overheads (see the `allocator_*` metrics), and also overheads like code, shared libraries, stack, etc. -* `mem_fragmentation_bytes`: Delta between `used_memory_rss` and `used_memory`. - Note that when the total fragmentation bytes is low (few megabytes), a high ratio (e.g. 1.5 and above) is not an indication of an issue. -* `allocator_frag_ratio:`: Ratio between `allocator_active` and `allocator_allocated`. This is the true (external) fragmentation metric (not `mem_fragmentation_ratio`). -* `allocator_frag_bytes` Delta between `allocator_active` and `allocator_allocated`. See note about `mem_fragmentation_bytes`. -* `allocator_rss_ratio`: Ratio between `allocator_resident` and `allocator_active`. This usually indicates pages that the allocator can and probably will soon release back to the OS. -* `allocator_rss_bytes`: Delta between `allocator_resident` and `allocator_active` -* `rss_overhead_ratio`: Ratio between `used_memory_rss` (the process RSS) and `allocator_resident`. This includes RSS overheads that are not allocator or heap related. -* `rss_overhead_bytes`: Delta between `used_memory_rss` (the process RSS) and `allocator_resident` -* `allocator_allocated`: Total bytes allocated form the allocator, including internal-fragmentation. Normally the same as `used_memory`. -* `allocator_active`: Total bytes in the allocator active pages, this includes external-fragmentation. -* `allocator_resident`: Total bytes resident (RSS) in the allocator, this includes pages that can be released to the OS (by [`MEMORY PURGE`](memory-purge.md), or just waiting). -* `allocator_muzzy`: Total bytes of 'muzzy' memory (RSS) in the allocator. Muzzy memory is memory that has been freed, but not yet fully returned to the operating system. It can be reused immediately when needed or reclaimed by the OS when system pressure increases. -* `mem_not_counted_for_evict`: Used memory that's not counted for key eviction. This is basically transient replica and AOF buffers. -* `mem_clients_slaves`: Memory used by replica clients - Replica buffers share memory with the replication backlog, so this field can show 0 when replicas don't trigger an increase of memory usage. -* `mem_clients_normal`: Memory used by normal clients -* `mem_cluster_links`: Memory used by links to peers on the cluster bus when cluster mode is enabled. -* `mem_aof_buffer`: Transient memory used for AOF and AOF rewrite buffers -* `mem_replication_backlog`: Memory used by replication backlog -* `mem_total_replication_buffers`: Total memory consumed for replication buffers. Starting with Valkey 9.1, it also includes `mem_replicas_repl_buffer`. -* `mem_replicas_repl_buffer`: Total memory consumed by the replicas replication buffer on replica side during the dual channel replication. Added in Valkey 9.1. -* `mem_allocator`: Memory allocator, chosen at compile time. -* `mem_overhead_db_hashtable_rehashing`: Temporary memory overhead of database dictionaries currently being rehashed - Added in 8.0. -* `active_defrag_running`: When `activedefrag` is enabled, this indicates whether defragmentation is currently active, and the CPU percentage it intends to utilize. -* `lazyfree_pending_objects`: The number of objects waiting to be freed (as a - result of calling [`UNLINK`](unlink.md), or [`FLUSHDB`](flushdb.md) and [`FLUSHALL`](flushall.md) with the **ASYNC** - option) -* `lazyfreed_objects`: The number of objects that have been lazy freed. - -Ideally, the `used_memory_rss` value should be only slightly higher than -`used_memory`. -When rss >> used, a large difference may mean there is (external) memory fragmentation, which can be evaluated by checking -`allocator_frag_ratio`, `allocator_frag_bytes`. -When used >> rss, it means part of Valkey memory has been swapped off by the -operating system: expect some significant latencies. - -Because Valkey does not have control over how its allocations are mapped to -memory pages, high `used_memory_rss` is often the result of a spike in memory -usage. - -When Valkey frees memory, the memory is given back to the allocator, and the -allocator may or may not give the memory back to the system. There may be -a discrepancy between the `used_memory` value and memory consumption as -reported by the operating system. It may be due to the fact memory has been -used and released by Valkey, but not given back to the system. The -`used_memory_peak` value is generally useful to check this point. - -Additional introspective information about the server's memory can be obtained -by referring to the [`MEMORY STATS`](memory-stats.md) command and the [`MEMORY DOCTOR`](memory-doctor.md). - -Here is the meaning of all fields in the **persistence** section: - -* `loading`: Flag indicating if the load of a dump file is on-going -* `async_loading`: Currently loading replication data-set asynchronously while serving old data. This means `repl-diskless-load` is enabled and set to `swapdb`. -* `current_cow_peak`: The peak size in bytes of copy-on-write memory - while a child fork is running -* `current_cow_size`: The size in bytes of copy-on-write memory - while a child fork is running -* `current_cow_size_age`: The age, in seconds, of the `current_cow_size` value. -* `current_fork_perc`: The percentage of progress of the current fork process. For AOF and RDB forks it is the percentage of `current_save_keys_processed` out of `current_save_keys_total`. -* `current_save_keys_processed`: Number of keys processed by the current save operation -* `current_save_keys_total`: Number of keys at the beginning of the current save operation -* `rdb_changes_since_last_save`: Number of changes since the last RDB file save -* `rdb_bgsave_in_progress`: Flag indicating a RDB save is on-going, including a diskless replication RDB save -* `rdb_last_save_time`: Epoch-based timestamp of last successful RDB file save -* `rdb_last_bgsave_status`: Status of the last RDB file save operation -* `rdb_last_bgsave_time_sec`: Duration of the last RDB save operation in seconds, including a diskless replication RDB save -* `rdb_current_bgsave_time_sec`: Duration of the on-going RDB save operation if any, including a diskless replication RDB save -* `rdb_current_bgsave_type`: The method of the on-going RDB save operation, including a diskless replication RDB save: `fork`, `forkless`, or `none` if no save is in progress. See [Forkless operations](../topics/forkless.md). -* `rdb_last_bgsave_type`: The method of the last RDB file save operation: `fork`, `forkless`, or `none` if no save has completed since startup. -* `forkless_estimated_seconds_remaining`: Estimated number of seconds until the on-going forkless save or full sync completes, or -1 if none is in progress. -* `rdb_last_cow_size`: The size in bytes of copy-on-write memory during - the last RDB save operation -* `rdb_last_load_keys_expired`: Number of volatile keys deleted during the last RDB loading. -* `rdb_last_load_keys_loaded`: Number of keys loaded during the last RDB loading. -* `aof_enabled`: Flag indicating AOF logging is activated -* `aof_rewrite_in_progress`: Flag indicating a AOF rewrite operation is - on-going -* `aof_rewrite_scheduled`: Flag indicating an AOF rewrite operation - will be scheduled once the on-going RDB save is complete. -* `aof_last_rewrite_time_sec`: Duration of the last AOF rewrite operation in - seconds -* `aof_current_rewrite_time_sec`: Duration of the on-going AOF rewrite - operation if any -* `aof_last_bgrewrite_status`: Status of the last AOF rewrite operation -* `aof_last_write_status`: Status of the last write operation to the AOF -* `aof_last_cow_size`: The size in bytes of copy-on-write memory during - the last AOF rewrite operation -* `module_fork_in_progress`: Flag indicating a module fork is on-going -* `module_fork_last_cow_size`: The size in bytes of copy-on-write memory - during the last module fork operation -* `aof_rewrites`: Number of AOF rewrites performed since startup -* `rdb_saves`: Number of RDB snapshots performed since startup - -`rdb_changes_since_last_save` refers to the number of operations that produced -some kind of changes in the dataset since the last time either [`SAVE`](save.md) or -[`BGSAVE`](bgsave.md) was called. - -If AOF is activated, these additional fields will be added: - -* `aof_current_size`: AOF current file size -* `aof_base_size`: AOF file size on latest startup or rewrite -* `aof_pending_rewrite`: Flag indicating an AOF rewrite operation - will be scheduled once the on-going RDB save is complete. -* `aof_buffer_length`: Size of the AOF buffer -* `aof_pending_bio_fsync`: Number of fsync pending jobs in background I/O - queue -* `aof_delayed_fsync`: Delayed fsync counter - -If a load operation is on-going, these additional fields will be added: - -* `loading_start_time`: Epoch-based timestamp of the start of the load - operation -* `loading_total_bytes`: Total file size -* `loading_rdb_used_mem`: The memory usage of the server that had generated - the RDB file at the time of the file's creation -* `loading_loaded_bytes`: Number of bytes already loaded -* `loading_loaded_perc`: Same value expressed as a percentage -* `loading_eta_seconds`: ETA in seconds for the load to be complete - -Here is the meaning of all fields in the **stats** section: - -* `total_connections_received`: Total number of connections accepted by the - server -* `total_commands_processed`: Total number of commands processed by the server -* `instantaneous_ops_per_sec`: Number of commands processed per second -* `total_net_input_bytes`: The total number of bytes read from the network -* `total_net_output_bytes`: The total number of bytes written to the network -* `total_net_repl_input_bytes`: The total number of bytes read from the network for replication purposes -* `total_net_repl_output_bytes`: The total number of bytes written to the network for replication purposes -* `instantaneous_input_kbps`: The network's read rate per second in KB/sec -* `instantaneous_output_kbps`: The network's write rate per second in KB/sec -* `instantaneous_input_repl_kbps`: The network's read rate per second in KB/sec for replication purposes -* `instantaneous_output_repl_kbps`: The network's write rate per second in KB/sec for replication purposes -* `rejected_connections`: Number of connections rejected because of - `maxclients` limit -* `sync_full`: The number of full resyncs with replicas -* `sync_partial_ok`: The number of accepted partial resync requests -* `sync_partial_err`: The number of denied partial resync requests -* `expired_keys`: Total number of key expiration events -* `expired_stale_perc`: The percentage of keys probably expired -* `expired_time_cap_reached_count`: The count of times that active expiry cycles have stopped early -* `expire_cycle_cpu_milliseconds`: The cumulative amount of time spent on active expiry cycles -* `evicted_keys`: Number of evicted keys due to `maxmemory` limit -* `evicted_clients`: Number of evicted clients due to `maxmemory-clients` limit. -* `evicted_scripts`: Number of evicted EVAL scripts, see [Script cache semantics](../topics/eval-intro.md#script-cache-semantics). Added in Valkey 8.0. -* `total_eviction_exceeded_time`: Total time `used_memory` was greater than `maxmemory` since server startup, in milliseconds -* `current_eviction_exceeded_time`: The time passed since `used_memory` last rose above `maxmemory`, in milliseconds -* `keyspace_hits`: Number of successful lookup of keys in the main dictionary -* `keyspace_misses`: Number of failed lookup of keys in the main dictionary -* `pubsub_channels`: Global number of pub/sub channels with client - subscriptions -* `pubsub_patterns`: Global number of pub/sub pattern with client - subscriptions -* `pubsubshard_channels`: Global number of pub/sub shard channels with client subscriptions. -* `latest_fork_usec`: Duration of the latest fork operation in microseconds -* `total_forks`: Total number of fork operations since the server start -* `migrate_cached_sockets`: The number of sockets open for `MIGRATE` purposes -* `slave_expires_tracked_keys`: The number of keys tracked for expiry purposes - (applicable only to writable replicas) -* `active_defrag_hits`: Number of value reallocations performed by active the - defragmentation process -* `active_defrag_misses`: Number of aborted value reallocations started by the - active defragmentation process -* `active_defrag_key_hits`: Number of keys that were actively defragmented -* `active_defrag_key_misses`: Number of keys that were skipped by the active - defragmentation process -* `total_active_defrag_time`: Total time memory fragmentation was over the limit, in milliseconds -* `current_active_defrag_time`: The time passed since memory fragmentation last was over the limit, in milliseconds -* `tracking_total_keys`: Number of keys being tracked by the server -* `tracking_total_items`: Number of items, that is the sum of clients number for - each key, that are being tracked -* `tracking_total_prefixes`: Number of tracked prefixes in server's prefix table - (only applicable for broadcast mode) -* `unexpected_error_replies`: Number of unexpected error replies, that are types - of errors from an AOF load or replication -* `total_error_replies`: Total number of issued error replies, that is the sum of - rejected commands (errors prior command execution) and - failed commands (errors within the command execution) -* `dump_payload_sanitizations`: Total number of dump payload deep integrity validations (see `sanitize-dump-payload` config). -* `total_reads_processed`: Total number of read events processed -* `total_writes_processed`: Total number of write events processed -* `io_threaded_reads_processed`: Number of read events processed by the I/O threads. -* `io_threaded_writes_processed`: Number of write events processed by the I/O threads. -* `io_threaded_total_prefetch_batches`: Indicate how many prefetch batches were executed in order to prefetch keys before executing commands. -* `io_threaded_total_prefetch_entries`: The total number of dict entries that were prefetched. Each batch can contain multiple entries, the ratio entries/batches indicates how many entries were prefetched per batch on average. -* `io_threaded_poll_processed`: Total poll system calls performed by the I/O threads. -* `io_threaded_freed_objects`: The total number of objects freed by the I/O threads. -* `client_query_buffer_limit_disconnections`: Total number of disconnections due to client reaching query buffer limit -* `client_output_buffer_limit_disconnections`: Total number of disconnections due to client reaching output buffer limit -* `reply_buffer_shrinks`: Total number of output buffer shrinks -* `reply_buffer_expands`: Total number of output buffer expands -* `eventloop_cycles`: Total number of eventloop cycles -* `eventloop_duration_sum`: Total time spent in the eventloop in microseconds (including I/O and command processing) -* `eventloop_duration_cmd_sum`: Total time spent on executing commands in microseconds -* `instantaneous_eventloop_cycles_per_sec`: Number of eventloop cycles per second -* `instantaneous_eventloop_duration_usec`: Average time spent in a single eventloop cycle in microseconds -* `acl_access_denied_auth`: Number of authentication failures -* `acl_access_denied_cmd`: Number of commands rejected because of access denied to the command -* `acl_access_denied_key`: Number of commands rejected because of access denied to a key -* `acl_access_denied_channel`: Number of commands rejected because of access denied to a channel -* `acl_access_denied_tls_cert`: Number of failed authentications using automatic TLS clients authentication feature. Added in Valkey 9.0. - -Here is the meaning of all fields in the **replication** section: - -* `role`: Value is "master" if the instance is replica of no one, or "slave" if the instance is a replica of some primary instance. - Note that a replica can be primary of another replica (chained replication). -* `replicas_waiting_psync`: The number of replicas waiting for partial resynchronization during the dual-channel replication. Added in Valkey 8.0. -* `master_failover_state`: The state of an ongoing failover, if any. -* `master_replid`: The replication ID of the Valkey server. -* `master_replid2`: The secondary replication ID, used for PSYNC after a failover. -* `master_repl_offset`: The server's current replication offset -* `second_repl_offset`: The offset up to which replication IDs are accepted -* `repl_backlog_active`: Flag indicating replication backlog is active -* `repl_backlog_size`: The value of the replication backlog buffer `repl-backlog-size` configuration item -* `repl_backlog_first_byte_offset`: Replication "primary offset" of first byte in the replication backlog buffer -* `repl_backlog_histlen`: Size in bytes of the data in the replication backlog - buffer - -If the instance is a replica, these additional fields are provided: - -* `master_host`: Host or IP address of the primary -* `master_port`: Primary listening TCP port -* `master_link_status`: Status of the link (up/down) -* `master_last_io_seconds_ago`: Number of seconds since the last interaction - with primary -* `last_successful_sync_duration_ms`: The duration of the last successful full sync in milliseconds, or -1 if no successful sync has occurred -* `master_sync_in_progress`: Indicate the primary is syncing to the replica -* `slave_read_repl_offset`: The read replication offset of the replica instance. -* `slave_repl_offset`: The replication offset of the replica instance -* `replicas_repl_buffer_size`: Currently accumulated replication stream data in bytes during the dual-channel replication. Added in Valkey 8.0. -* `replicas_repl_buffer_peak`: Peak number of bytes accumulated replication stream data during the lifetime of this instance. Added in Valkey 8.0. -* `slave_priority`: The priority of the instance as a candidate for failover -* `slave_read_only`: Flag indicating if the replica is read-only -* `replica_announced`: Flag indicating if the replica is announced by Sentinel. - -If a SYNC operation is on-going, these additional fields are provided: - -* `master_sync_total_bytes`: Total number of bytes that need to be - transferred. this may be 0 when the size is unknown (for example, when - the `repl-diskless-sync` configuration directive is used) -* `master_sync_read_bytes`: Number of bytes already transferred -* `master_sync_left_bytes`: Number of bytes left before syncing is complete - (may be negative when `master_sync_total_bytes` is 0) -* `master_sync_perc`: The percentage `master_sync_read_bytes` from - `master_sync_total_bytes`, or an approximation that uses - `loading_rdb_used_mem` when `master_sync_total_bytes` is 0 -* `master_sync_last_io_seconds_ago`: Number of seconds since last transfer I/O - during a SYNC operation - -If the link between primary and replica is down, an additional field is provided: - -* `master_link_down_since_seconds`: Number of seconds since the link is down - -The following field is always provided: - -* `connected_slaves`: Number of connected replicas - -If the server is configured with the `min-replicas-to-write` directive, an additional field is provided: - -* `min_slaves_good_slaves`: Number of replicas currently considered good - -For each replica, the following line is added: - -* `slaveXXX:ip=xxx,port=xxx,state=xxx,offset=xxx,lag=xxx,type=xxx` - -`state` represents the state of the replica client and can be one of the following strings. - -* `wait_bgsave`: The replica is waiting for the primary to generate the RDB file. -* `send_bulk`: Primary is sending the RDB file to replica. -* `online`: RDB file transmitted, sending just updates. -* `rdb_transmitted`: RDB file transmitted, this state is used for the rdb-channel during dual-channel replication when the RDB transfer is complete but the replica has not yet established its main connection. Added in Valkey 9.1. -* `bg_transfer`: Main channel of a replica during dual-channel replication. Changes to `online` once sync is complete. Added in Valkey 8.0. - -`type` added in Valkey 8.0, represents the type of the replica client and can be one of the following strings. - -* `replica`: Normal replica client. -* `main-channel`: Main channel of a replica which uses dual-channel replication. Once dual channel replication is complete, the type will become `replica`. -* `rdb-channel`: RDB channel of a replica which uses dual-channel replication. Once dual channel replication is complete, the replica client will disconnect. - -Here is the meaning of all fields in the **cpu** section: - -* `used_cpu_sys`: System CPU consumed by the Valkey server, which is the sum of system CPU consumed by all threads of the server process (main thread and background threads) -* `used_cpu_user`: User CPU consumed by the Valkey server, which is the sum of user CPU consumed by all threads of the server process (main thread and background threads) -* `used_cpu_sys_children`: System CPU consumed by the background processes -* `used_cpu_user_children`: User CPU consumed by the background processes -* `used_cpu_sys_main_thread`: System CPU consumed by the Valkey server main thread -* `used_cpu_user_main_thread`: User CPU consumed by the Valkey server main thread -* `used_active_time_main_thread`: Clock time the Valkey server main thread has spent on actual work, - excluding time waiting for work. -* `used_active_time_io_thread_N` (where *N* is a number from 1 to the configured number of I/O threads): - Clock time each I/O thread spends doing actual work, excluding time waiting for work. - -The fields `used_active_time_main_thread` and `used_active_time_io_thread_N` -were added in Valkey 9.1. They are a better indication than the CPU time metrics -of the spare capacity of each thread, because Valkey uses busy-waiting when I/O -threads are used, which makes the CPU time appear to be near 100% even if the -server has spare capacity for handling more commands. - -The active time fields grow linearly with the server load. To understand how to -interpret them, consider this example: If the main thread's used active time -increases 5 seconds between two INFO calls 10 seconds apart, it means the main -thread has spent half of the time executing commands and the other half waiting. -It means that it's running at 50% of its capacity. - -The **commandstats** section provides statistics based on the command type, - including the number of calls that reached command execution (not rejected), - the total CPU time consumed by these commands, the average CPU consumed - per command execution, the number of rejected calls - (errors prior command execution), and the number of failed calls - (errors within the command execution). - -For each command type, the following line is added: - -* `cmdstat_XXX`: `calls=XXX,usec=XXX,usec_per_call=XXX,rejected_calls=XXX,failed_calls=XXX` - -The **latencystats** section provides latency percentile distribution statistics based on the command type. - - By default, the exported latency percentiles are the p50, p99, and p999. - If you need to change the exported percentiles, use `CONFIG SET latency-tracking-info-percentiles "50.0 99.0 99.9"`. - - This section requires the extended latency monitoring feature to be enabled (by default it's enabled). - If you need to enable it, use [`CONFIG SET latency-tracking yes`](config-set.md). - -For each command type, the following line is added: - -* `latency_percentiles_usec_XXX: p=,p=,...` - -The **errorstats** section enables keeping track of the different errors that occurred within Valkey, - based upon the reply error prefix ( The first word after the "-", up to the first space. Example: `ERR` ). - -For each error type, the following line is added: - -* `errorstat_XXX`: `count=XXX` - -The **sentinel** section is only available in Valkey Sentinel instances. It consists of the following fields: - -* `sentinel_masters`: Number of Valkey primaries monitored by this Sentinel instance -* `sentinel_tilt`: A value of 1 means this sentinel is in TILT mode -* `sentinel_tilt_since_seconds`: Duration in seconds of current TILT, or -1 if not TILTed. -* `sentinel_total_tilt`: The number of times this sentinel has been in TILT mode since running. Added in 9.0. -* `sentinel_running_scripts`: The number of scripts this Sentinel is currently executing -* `sentinel_scripts_queue_length`: The length of the queue of user scripts that are pending execution -* `sentinel_simulate_failure_flags`: Flags for the `SENTINEL SIMULATE-FAILURE` command - -The **cluster** section currently only contains a unique field: - -* `cluster_enabled`: Indicate Valkey cluster is enabled - -The **modules** section contains additional information about loaded modules if the modules provide it. The field part of properties lines in this section is always prefixed with the module's name. - -The **keyspace** section provides statistics on the main dictionary of each -database. -The statistics are the number of keys, and the number of keys with an expiration. - -For each database, the following line is added: - -* `dbXXX`: `keys=XXX,expires=XXX` - -The **throttling** section, contains metrics related to client command throttling. - -* `total_throttled_commands`: Total number of commands deferred across all throttlers since the server started. -* `repl_throttle_rate`: Current replication throttle rate in operations per second. `-1` when the throttler is inactive. -* `repl_throttle_activation_events`: Number of times the replication throttler has been activated since the server started. -* `repl_throttle_below_guardrail_secs`: Seconds the throttle rate has been continuously below the minimum rate guardrail. -* `repl_throttle_total_commands`: Number of commands deferred by the replication throttler since the server started. - -The **debug** section contains experimental metrics, which might change or get removed in future versions. -It won't be included when `INFO` or `INFO ALL` are called, and it is returned only when `INFO DEBUG` is used. - -* `used_memory_module_external`: Number of bytes that modules allocated outside the Valkey allocator and reported with `ValkeyModule_IncrExternalMemory` (already included in `used_memory`) -* `eventloop_duration_aof_sum`: Total time spent on flushing AOF in eventloop in microseconds -* `eventloop_duration_cron_sum`: Total time consumption of cron in microseconds (including serverCron and beforeSleep, but excluding IO and AOF flushing) -* `eventloop_duration_max`: The maximal time spent in a single eventloop cycle in microseconds -* `eventloop_cmd_per_cycle_max`: The maximal number of commands processed in a single eventloop cycle -* `repl_throttle_more_events`: Number of times the replication throttle rate was decreased. -* `repl_throttle_less_events`: Number of times the replication throttle rate was increased. -* `repl_throttle_current_clients`: Number of clients currently queued by the replication throttler. -* `forkless_fallbacks_module`: Number of times a save or full sync used `fork()` instead of a forkless operation because a loaded module does not support forkless operations. -* `forkless_fallbacks_slot_import`: Number of times a save or full sync used `fork()` instead of a forkless operation because a slot import was in progress. -* `forkless_fallbacks_exclude_data`: Number of times a full sync used `fork()` instead of a forkless operation because an RDB without keyspace data, such as a functions-only RDB, was requested. -* `forkless_fallbacks_missing_inband_repl`: Number of times a full sync used `fork()` instead of a forkless operation because the replica does not support forkless full sync. -* `forkless_fallbacks_compression`: Number of times a full sync used `fork()` instead of a forkless operation because replication compression was negotiated. - -[hcgcpgp]: http://code.google.com/p/google-perftools/ - -**A note about the word slave used in this man page**: If not for backward compatibility, the Valkey project no longer uses the words "master" and "slave". Unfortunately in the given commands these words are part of the protocol, so we'll be able to remove such occurrences only when this API will be naturally deprecated. - -**Modules generated sections**: Starting with Valkey 6, modules can inject their info into the `INFO` command, these are excluded by default even when the `all` argument is provided (it will include a list of loaded modules but not their generated info fields). To get these you must use either the `modules` argument or `everything`., diff --git a/commands/json.arrappend.md b/commands/json.arrappend.md deleted file mode 100644 index 009e9cb1..00000000 --- a/commands/json.arrappend.md +++ /dev/null @@ -1,39 +0,0 @@ -Append one or more values to the array values at the path. - -## Reply - -* If the path is enhanced syntax: - * Array of integers representing the new length of the array at each path. - * Null: For each path where the value is not an array. -* If the path is restricted syntax: - * Integer: The array's new length. - * Integer: If multiple array values are selected, the command returns the new length of the last updated array. -* Error: - * if the path does not exist. - * if the value at the path is not an array (only for restricted syntax). - -## Examples - -Enhanced path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '[[], ["a"], ["a", "b"]]' -OK -127.0.0.1:6379> JSON.ARRAPPEND k1 $[*] '"c"' -1) (integer) 1 -2) (integer) 2 -3) (integer) 3 -127.0.0.1:6379> JSON.GET k1 -"[[\"c\"],[\"a\",\"c\"],[\"a\",\"b\",\"c\"]]" -``` - -Restricted path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '[[], ["a"], ["a", "b"]]' -OK -127.0.0.1:6379> JSON.ARRAPPEND k1 [-1] '"c"' -(integer) 3 -127.0.0.1:6379> JSON.GET k1 -"[[],[\"a\"],[\"a\",\"b\",\"c\"]]" -``` diff --git a/commands/json.arrindex.md b/commands/json.arrindex.md deleted file mode 100644 index a2431272..00000000 --- a/commands/json.arrindex.md +++ /dev/null @@ -1,39 +0,0 @@ -Search for the first occurrence of a scalar JSON value in the arrays at the path. - - -* Out of range errors are treated by rounding the index to the array's start and end. -* If start > end, return -1 (not found). - -## Reply - -* If the path is enhanced syntax: - * Array of integers. Each value is the index of the matching element in the array at the path. The value is -1 if not found. - * Null: For each path where the value is not an array. -* If the path is restricted syntax: - * Integer: The index of matching element, or -1 if not found. -* Error: - * if the path does not exist. - * if the value at the path is not an array (only for restricted syntax). - -## Examples - -Enhanced path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '[[], ["a"], ["a", "b"], ["a", "b", "c"]]' -OK -127.0.0.1:6379> JSON.ARRINDEX k1 $[*] '"b"' -1) (integer) -1 -2) (integer) -1 -3) (integer) 1 -4) (integer) 1 -``` - -Restricted path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '{"children": ["John", "Jack", "Tom", "Bob", "Mike"]}' -OK -127.0.0.1:6379> JSON.ARRINDEX k1 .children '"Tom"' -(integer) 2 -``` diff --git a/commands/json.arrinsert.md b/commands/json.arrinsert.md deleted file mode 100644 index a77f5a9d..00000000 --- a/commands/json.arrinsert.md +++ /dev/null @@ -1,44 +0,0 @@ -Insert one or more values into the array values at path before the index. - - -* Inserting at index 0 prepends to the array. -* A negative index values is interpreted as starting from the end. -* The index must be in the array's boundary. - -## Reply - -* If the path is enhanced syntax: - * Array of integers representing the new length of the array at each path. - * Null: For each path where the value is an empty array or not an array. -* If the path is restricted syntax: - * Integer: The new length of the array. -* Error: - * if the path does not exist. - * if the value at the path is not an array (only for restricted syntax). - * if the index argument is out of bounds. - -## Examples - -Enhanced path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '[[], ["a"], ["a", "b"]]' -OK -127.0.0.1:6379> JSON.ARRINSERT k1 $[*] 0 '"c"' -1) (integer) 1 -2) (integer) 2 -3) (integer) 3 -127.0.0.1:6379> JSON.GET k1 -"[[\"c\"],[\"c\",\"a\"],[\"c\",\"a\",\"b\"]]" -``` - -Restricted path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '[[], ["a"], ["a", "b"]]' -OK -127.0.0.1:6379> JSON.ARRINSERT k1 . 0 '"c"' -(integer) 4 -127.0.0.1:6379> JSON.GET k1 -"[\"c\",[],[\"a\"],[\"a\",\"b\"]]" -``` diff --git a/commands/json.arrlen.md b/commands/json.arrlen.md deleted file mode 100644 index ac0bf1e5..00000000 --- a/commands/json.arrlen.md +++ /dev/null @@ -1,58 +0,0 @@ -Get length of the array at the path. - -## Reply - -* If the path is enhanced syntax: - * Array of integers representing the array length at each path. - * Null: For each path where the value is not an array. - * Null: If the document key does not exist. -* If the path is restricted syntax: - * Integer: The array length. - * Integer: If multiple objects are selected, returns the first array's length. - * Null: If the document key does not exist. -* Error: - * if the path does not exist. - * if the value at the path is not an array (only for restricted syntax). - -## Examples - -Enhanced path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '[[], [\"a\"], [\"a\", \"b\"], [\"a\", \"b\", \"c\"]]' -(error) SYNTAXERR Failed to parse JSON string due to syntax error -127.0.0.1:6379> JSON.SET k1 . '[[], ["a"], ["a", "b"], ["a", "b", "c"]]' -OK -127.0.0.1:6379> JSON.ARRLEN k1 $[*] -1) (integer) 0 -2) (integer) 1 -3) (integer) 2 -4) (integer) 3 - -127.0.0.1:6379> JSON.SET k2 . '[[], "a", ["a", "b"], ["a", "b", "c"], 4]' -OK -127.0.0.1:6379> JSON.ARRLEN k2 $[*] -1) (integer) 0 -2) (nil) -3) (integer) 2 -4) (integer) 3 -5) (nil) -``` - -```bash -127.0.0.1:6379> JSON.SET k1 . '[[], ["a"], ["a", "b"], ["a", "b", "c"]]' -OK -127.0.0.1:6379> JSON.ARRLEN k1 [*] -(integer) 0 -127.0.0.1:6379> JSON.ARRLEN k1 $[3] -1) (integer) 3 - -127.0.0.1:6379> JSON.SET k2 . '[[], "a", ["a", "b"], ["a", "b", "c"], 4]' -OK -127.0.0.1:6379> JSON.ARRLEN k2 [*] -(integer) 0 -127.0.0.1:6379> JSON.ARRLEN k2 $[1] -1) (nil) -127.0.0.1:6379> JSON.ARRLEN k2 $[2] -1) (integer) 2 -``` diff --git a/commands/json.arrpop.md b/commands/json.arrpop.md deleted file mode 100644 index b85f6f7c..00000000 --- a/commands/json.arrpop.md +++ /dev/null @@ -1,45 +0,0 @@ -Remove and return element at the index from the array. Popping an empty array returns null. - -## Reply - -* If the path is enhanced syntax: - * Array of bulk strings representing popped values at each path. - * Null: For each path where the value is an empty array or not an array. -* If the path is restricted syntax: - * String: The popped JSON value. - * Null: If the array is empty. -* Error: - * if the value at the path is not an array (only for restricted syntax). - -## Examples - -Enhanced path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '[[], ["a"], ["a", "b"]]' -OK -127.0.0.1:6379> JSON.ARRPOP k1 $[*] -1) (nil) -2) "\"a\"" -3) "\"b\"" -127.0.0.1:6379> JSON.GET k1 -"[[],[],[\"a\"]]" -``` - -Restricted path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '[[], ["a"], ["a", "b"]]' -OK -127.0.0.1:6379> JSON.ARRPOP k1 -"[\"a\",\"b\"]" -127.0.0.1:6379> JSON.GET k1 -"[[],[\"a\"]]" - -127.0.0.1:6379> JSON.SET k2 . '[[], ["a"], ["a", "b"]]' -OK -127.0.0.1:6379> JSON.ARRPOP k2 . 0 -"[]" -127.0.0.1:6379> JSON.GET k2 -"[[\"a\"],[\"a\",\"b\"]]" -``` diff --git a/commands/json.arrtrim.md b/commands/json.arrtrim.md deleted file mode 100644 index 72fbdb1d..00000000 --- a/commands/json.arrtrim.md +++ /dev/null @@ -1,46 +0,0 @@ -Trim arrays at the path so that it becomes subarray [start, end], both inclusive. - - -* If the array is empty, do nothing, return 0. -* If start < 0, treat it as 0. -* If end >= size (size of the array), treat it as size-1. -* If start >= size or start > end, empty the array and return 0. - -## Reply - -* If the path is enhanced syntax: - * Array of integers representing the new length of the array at each path. - * Null: For each path where the value is an empty array or not an array. -* If the path is restricted syntax: - * Integer: The new length of the array. - * Null: If the array is empty. -* Error: - * if the value at the path is not an array (only for restricted syntax). - * if an index argument is out of bounds. - -## Examples - -Enhanced path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '[[], ["a"], ["a", "b"], ["a", "b", "c"]]' -OK -127.0.0.1:6379> JSON.ARRTRIM k1 $[*] 0 1 -1) (integer) 0 -2) (integer) 1 -3) (integer) 2 -4) (integer) 2 - 127.0.0.1:6379> JSON.GET k1 - "[[],[\"a\"],[\"a\",\"b\"],[\"a\",\"b\"]]" -``` - -Restricted path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '{"children": ["John", "Jack", "Tom", "Bob", "Mike"]}' -OK -127.0.0.1:6379> JSON.ARRTRIM k1 .children 0 1 -(integer) 2 -127.0.0.1:6379> JSON.GET k1 .children -"[\"John\",\"Jack\"]" -``` diff --git a/commands/json.clear.md b/commands/json.clear.md deleted file mode 100644 index 7709929a..00000000 --- a/commands/json.clear.md +++ /dev/null @@ -1,26 +0,0 @@ -Clear the arrays or objects at the path. - -## Reply - -* Integer: - * The number of containers cleared. - * Returns 0 if clearing an empty array or object. - * Returns 0 if clearing a non-container value. - * Returns 0 if no array or object value is located by the path. - -## Examples - -```bash -127.0.0.1:6379> JSON.SET k1 . '[[], [0], [0,1], [0,1,2], 1, true, null, "d"]' -OK -127.0.0.1:6379> JSON.CLEAR k1 $[*] -(integer) 6 -127.0.0.1:6379> JSON.CLEAR k1 $[*] -(integer) 0 -127.0.0.1:6379> JSON.SET k2 . '{"children": ["John", "Jack", "Tom", "Bob", "Mike"]}' -OK -127.0.0.1:6379> JSON.CLEAR k2 .children -(integer) 1 -127.0.0.1:6379> JSON.GET k2 .children -"[]" -``` diff --git a/commands/json.debug.md b/commands/json.debug.md deleted file mode 100644 index e0c92c5c..00000000 --- a/commands/json.debug.md +++ /dev/null @@ -1,86 +0,0 @@ -Report information. Supported subcommands are: - - -* MEMORY [path] - report memory usage in bytes of a JSON value. Path defaults to the root if not provided. -* DEPTH - report the maximum path depth of the JSON document. -* FIELDS [path] - report the number of fields at the specified document path. Path defaults to the root if not provided. - Each non-container JSON value counts as one field. Objects and arrays recursively count one field for each of their - containing JSON values. Each container value, except the root container, counts as one additional field. -* HELP - print help messages of the command. - -## Reply - -Command response depends on the subcommand: - -* For MEMORY: - * If the path is enhanced syntax: - * Array of integers representing memory size (in bytes) of JSON value at each path. - * Array: Empty array if the Valkey key does not exist. - * If the path is restricted syntax: - * Integer: Memory size of the JSON value in bytes. - * Null: If the Valkey key does not exist. -* For DEPTH: - * Integer: The maximum path depth of the JSON document. - * Null: If the Valkey key does not exist. -* For FIELDS: - * If the path is enhanced syntax: - * Array of integers representing number of fields of JSON value at each path. - * Array: Empty array if the Valkey key does not exist. - * If the path is restricted syntax: - * Integer: Number of fields of the JSON value. - * Null: If the Valkey key does not exist. -* For HELP: - * Array of help messages. - -## Examples - -Enhanced path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '[1, 2.3, "foo", true, null, {}, [], {"a":1, "b":2}, [1,2,3]]' -OK -127.0.0.1:6379> JSON.DEBUG MEMORY k1 $[*] -1) (integer) 16 -2) (integer) 16 -3) (integer) 19 -4) (integer) 16 -5) (integer) 16 -6) (integer) 16 -7) (integer) 16 -8) (integer) 50 -9) (integer) 64 -127.0.0.1:6379> JSON.DEBUG FIELDS k1 $[*] -1) (integer) 1 -2) (integer) 1 -3) (integer) 1 -4) (integer) 1 -5) (integer) 1 -6) (integer) 0 -7) (integer) 0 -8) (integer) 2 -9) (integer) 3 -``` - -Restricted path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '{"firstName":"John","lastName":"Smith","age":27,"weight":135.25,"isAlive":true,"address":{"street":"21 2nd Street","city":"New York","state":"NY","zipcode":"10021-3100"},"phoneNumbers":[{"type":"home","number":"212 555-1234"},{"type":"office","number":"646 555-4567"}],"children":[],"spouse":null}' -OK -127.0.0.1:6379> JSON.DEBUG MEMORY k1 -(integer) 632 -127.0.0.1:6379> JSON.DEBUG MEMORY k1 .phoneNumbers -(integer) 166 - -127.0.0.1:6379> JSON.DEBUG FIELDS k1 -(integer) 19 -127.0.0.1:6379> JSON.DEBUG FIELDS k1 .address -(integer) 4 -``` - -```bash -127.0.0.1:6379> JSON.DEBUG HELP -1) JSON.DEBUG MEMORY [path] - report memory size (bytes) of the JSON element. Path defaults to root if not provided. -2) JSON.DEBUG FIELDS [path] - report number of fields in the JSON element. Path defaults to root if not provided. -3) JSON.DEBUG DEPTH - report depth of JSON doc. -3) JSON.DEBUG HELP - print help message. -``` \ No newline at end of file diff --git a/commands/json.del.md b/commands/json.del.md deleted file mode 100644 index a758c40f..00000000 --- a/commands/json.del.md +++ /dev/null @@ -1,41 +0,0 @@ -Delete the JSON values at the path in a document key. If the path is the root path, it is equivalent to deleting the key from Valkey. - -## Reply - -* Integer: - * The number of elements deleted. - * Returns 0 if the Valkey key does not exist. - * Returns 0 if the JSON path is invalid or does not exist. - -## Examples - -Enhanced path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '{"a":{}, "b":{"a":1}, "c":{"a":1, "b":2}, "d":{"a":1, "b":2, "c":3}, "e": [1,2,3,4,5]}' -OK -127.0.0.1:6379> JSON.DEL k1 $.d.* -(integer) 3 -127.0.0.1:6379> JSON.GET k1 -"{\"a\":{},\"b\":{\"a\":1},\"c\":{\"a\":1,\"b\":2},\"d\":{},\"e\":[1,2,3,4,5]}" -127.0.0.1:6379> JSON.DEL k1 $.e[*] -(integer) 5 -127.0.0.1:6379> JSON.GET k1 -"{\"a\":{},\"b\":{\"a\":1},\"c\":{\"a\":1,\"b\":2},\"d\":{},\"e\":[]}" -``` - -Restricted path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '{"a":{}, "b":{"a":1}, "c":{"a":1, "b":2}, "d":{"a":1, "b":2, "c":3}, "e": [1,2,3,4,5]}' -OK -127.0.0.1:6379> JSON.DEL k1 .d.* -(integer) 3 -127.0.0.1:6379> JSON.GET k1 -"{\"a\":{},\"b\":{\"a\":1},\"c\":{\"a\":1,\"b\":2},\"d\":{},\"e\":[1,2,3,4,5]}" -127.0.0.1:6379> JSON.DEL k1 .e[*] -(integer) 5 -127.0.0.1:6379> JSON.GET k1 -"{\"a\":{},\"b\":{\"a\":1},\"c\":{\"a\":1,\"b\":2},\"d\":{},\"e\":[]}" -``` - diff --git a/commands/json.forget.md b/commands/json.forget.md deleted file mode 100644 index 934bc24a..00000000 --- a/commands/json.forget.md +++ /dev/null @@ -1 +0,0 @@ -An alias of [`JSON.DEL`](json.del.md) diff --git a/commands/json.get.md b/commands/json.get.md deleted file mode 100644 index 8a450488..00000000 --- a/commands/json.get.md +++ /dev/null @@ -1,55 +0,0 @@ -Get the serialized JSON at one or multiple paths. - - -## Reply - -* For enhanced path syntax: - * If one path is given: - * String: Serialized string of an array of values. - * Array: Empty array if no value is selected. - * If multiple paths are given: - * String: JSON object serialized as a string, where each path is a key. - * Result conforms to enhanced syntax if there are mixed enhanced and restricted path syntax. - * Array: Empty array for paths that do not exist. -* For restricted path syntax: - * If one path is given: - * String: Serialized string of the value at the path. - * String: First value if multiple values are selected. - * Error: If the path does not exist. - * If multiple paths are given: - * String: JSON object serialized as a string, where each path is a key. - * Result conforms to restricted syntax only if all paths are restricted. - * Error: If any path does not exist. - -## Examples - -Enhanced path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '{"firstName":"John","lastName":"Smith","age":27,"weight":135.25,"isAlive":true,"address":{"street":"21 2nd Street","city":"New York","state":"NY","zipcode":"10021-3100"},"phoneNumbers":[{"type":"home","number":"212 555-1234"},{"type":"office","number":"646 555-4567"}],"children":[],"spouse":null}' -OK -127.0.0.1:6379> JSON.GET k1 $.address.* -"[\"21 2nd Street\",\"New York\",\"NY\",\"10021-3100\"]" -127.0.0.1:6379> JSON.GET k1 indent "\t" space " " NEWLINE "\n" $.address.* -"[\n\t\"21 2nd Street\",\n\t\"New York\",\n\t\"NY\",\n\t\"10021-3100\"\n]" -127.0.0.1:6379> JSON.GET k1 $.firstName $.lastName $.age -"{\"$.firstName\":[\"John\"],\"$.lastName\":[\"Smith\"],\"$.age\":[27]}" - -127.0.0.1:6379> JSON.SET k2 . '{"a":{}, "b":{"a":1}, "c":{"a":1, "b":2}}' -OK -127.0.0.1:6379> json.get k2 $..* -"[{},{\"a\":1},{\"a\":1,\"b\":2},1,1,2]" -``` - -Restricted path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '{"firstName":"John","lastName":"Smith","age":27,"weight":135.25,"isAlive":true,"address":{"street":"21 2nd Street","city":"New York","state":"NY","zipcode":"10021-3100"},"phoneNumbers":[{"type":"home","number":"212 555-1234"},{"type":"office","number":"646 555-4567"}],"children":[],"spouse":null}' -OK -127.0.0.1:6379> JSON.GET k1 .address -"{\"street\":\"21 2nd Street\",\"city\":\"New York\",\"state\":\"NY\",\"zipcode\":\"10021-3100\"}" -127.0.0.1:6379> JSON.GET k1 indent "\t" space " " NEWLINE "\n" .address -"{\n\t\"street\": \"21 2nd Street\",\n\t\"city\": \"New York\",\n\t\"state\": \"NY\",\n\t\"zipcode\": \"10021-3100\"\n}" -127.0.0.1:6379> JSON.GET k1 .firstName .lastName .age -"{\".firstName\":\"John\",\".lastName\":\"Smith\",\".age\":27}" -``` diff --git a/commands/json.merge.md b/commands/json.merge.md deleted file mode 100644 index 0d77f636..00000000 --- a/commands/json.merge.md +++ /dev/null @@ -1,71 +0,0 @@ -Merge a JSON value into the value at the path using [RFC 7396](https://www.rfc-editor.org/rfc/rfc7396) JSON Merge Patch semantics. - -* If the key does not exist: - * A new key is created when the path is the document root (`.` or `$`). - * Otherwise, the command returns a `SYNTAXERR` error. -* If the key exists: - * If the patch value is an object, its members are merged recursively into the value at the path. A non-object value at the path is treated as an empty object: - * Members present only in the patch are added. - * Members present in both are replaced by the merged result. - * Members set to `null` in the patch are deleted from the target. - * If the patch value is not an object (for example a string, number, boolean, array, or `null`), the value at the path is replaced entirely. - * If the path exists except for the final child, and the parent is an object, the final child is created and set to the patch value with `null` members removed. - * If the parent does not exist, the command returns a `NONEXISTENT` error. - * If the parent exists but is not an object, the command returns an `ERROR` error. - * Arrays are replaced, not merged element-by-element. -* Document nesting is subject to the configured maximum depth (`json.max-path-limit`). - A merge whose result would exceed that depth returns a `LIMIT` error and leaves the document unchanged. - -## Reply - -* `OK` if the operation was successful. -* Error: If the operation failed. - -## Examples - -Restricted path syntax: - -``` -127.0.0.1:6379> JSON.MERGE k1 . '{"a":1,"b":2}' -OK -127.0.0.1:6379> JSON.GET k1 -"{\"a\":1,\"b\":2}" -127.0.0.1:6379> JSON.MERGE k1 . '{"b":3,"c":4}' -OK -127.0.0.1:6379> JSON.GET k1 -"{\"a\":1,\"b\":3,\"c\":4}" - -127.0.0.1:6379> JSON.SET k2 . '{"a":{"x":1,"y":2},"b":10}' -OK -127.0.0.1:6379> JSON.MERGE k2 .a '{"y":3,"z":4}' -OK -127.0.0.1:6379> JSON.GET k2 .a -"{\"x\":1,\"y\":3,\"z\":4}" - -127.0.0.1:6379> JSON.SET k3 . '{"a":1,"b":2,"c":3}' -OK -127.0.0.1:6379> JSON.MERGE k3 . '{"b":null}' -OK -127.0.0.1:6379> JSON.GET k3 -"{\"a\":1,\"c\":3}" - -127.0.0.1:6379> JSON.SET k4 . '{"str":"hello","arr":[1,2,3],"obj":{"x":1}}' -OK -127.0.0.1:6379> JSON.MERGE k4 . '{"str":"world","arr":[4,5],"obj":{"y":2}}' -OK -127.0.0.1:6379> JSON.GET k4 -"{\"str\":\"world\",\"arr\":[4,5],\"obj\":{\"x\":1,\"y\":2}}" -``` - -Enhanced path syntax: - -``` -127.0.0.1:6379> JSON.SET k1 . '{"users":[{"name":"Alice","meta":{"active":false}},{"name":"Bob","meta":{"active":false}}]}' -OK -127.0.0.1:6379> JSON.MERGE k1 '$..meta' '{"active":true,"updated":true}' -OK -127.0.0.1:6379> JSON.GET k1 .users[0].meta -"{\"active\":true,\"updated\":true}" -127.0.0.1:6379> JSON.GET k1 .users[1].meta -"{\"active\":true,\"updated\":true}" -``` diff --git a/commands/json.mget.md b/commands/json.mget.md deleted file mode 100644 index d205a8d8..00000000 --- a/commands/json.mget.md +++ /dev/null @@ -1,42 +0,0 @@ -Get serialized JSON objects from multiple document keys at the specified path. Return null for non-existent keys or JSON paths. - -## Reply - -* Array of Bulk Strings with size equal to the number of keys in the command. - * Each element is either: - * String: Serialized JSON as located by the path. - * Null: If the key does not exist, the path does not exist in the document, or the path is invalid. -* Error: WRONGTYPE error if any specified key exists but is not a JSON key. - -## Examples - -Enhanced path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '{"address":{"street":"21 2nd Street","city":"New York","state":"NY","zipcode":"10021"}}' -OK -127.0.0.1:6379> JSON.SET k2 . '{"address":{"street":"5 main Street","city":"Boston","state":"MA","zipcode":"02101"}}' -OK -127.0.0.1:6379> JSON.SET k3 . '{"address":{"street":"100 Park Ave","city":"Seattle","state":"WA","zipcode":"98102"}}' -OK -127.0.0.1:6379> JSON.MGET k1 k2 k3 $.address.city -1) "[\"New York\"]" -2) "[\"Boston\"]" -3) "[\"Seattle\"]" -``` - -Restricted path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '{"address":{"street":"21 2nd Street","city":"New York","state":"NY","zipcode":"10021"}}' -OK -127.0.0.1:6379> JSON.SET k2 . '{"address":{"street":"5 main Street","city":"Boston","state":"MA","zipcode":"02101"}}' -OK -127.0.0.1:6379> JSON.SET k3 . '{"address":{"street":"100 Park Ave","city":"Seattle","state":"WA","zipcode":"98102"}}' -OK - -127.0.0.1:6379> JSON.MGET k1 k2 k3 .address.city -1) "\"New York\"" -2) "\"Seattle\"" -3) "\"Seattle\"" -``` diff --git a/commands/json.mset.md b/commands/json.mset.md deleted file mode 100644 index 944cda1d..00000000 --- a/commands/json.mset.md +++ /dev/null @@ -1,53 +0,0 @@ -Set JSON values for multiple keys. The operation is atomic. Either all values are set or none is set. - -* If the path calls for an object member: - * If the parent element does not exist, the command will return NONEXISTENT error. - * If the parent element exists but is not an object, the command will return ERROR. - * If the parent element exists and is an object: - * If the member does not exist, a new member will be appended to the parent object if and only if the - parent object is the last child in the path. Otherwise, the command will return NONEXISTENT error. - * If the member exists, its value will be replaced by the JSON value. -* If the path calls for an array index: - * If the parent element does not exist, the command will return a NONEXISTENT error. - * If the parent element exists but is not an array, the command will return ERROR. - * If the parent element exists but the index is out of bounds, the command will return OUTOFBOUNDARIES error. - * If the parent element exists and the index is valid, the element will be replaced by the new JSON value. -* If the path calls for an object or array, the value (object or array) will be replaced by the new JSON value. - -## Reply - -* `OK` if the operation was successful. -* Error: If the operation failed. - -## Examples - -Enhanced path syntax: - -```bash -127.0.0.1:6379> JSON.MSET k1 . '[1,2,3,4,5]' k2 . '{"a":{"a":1, "b":2, "c":3}}' k3 . '{"a": [1,2,3,4,5]}' -OK -127.0.0.1:6379> JSON.GET k1 -"[1,2,3,4,5]" -127.0.0.1:6379> JSON.GET k2 -"{\"a\":{\"a\":1,\"b\":2,\"c\":3}}" -127.0.0.1:6379> JSON.MSET k2 $.a.* '0' k3 $.a[*] '0' -OK -127.0.0.1:6379> JSON.GET k2 -"{\"a\":{\"a\":0,\"b\":0,\"c\":0}}" -127.0.0.1:6379> JSON.GET k3 -"{\"a\":[0,0,0,0,0]}" -``` - -Restricted path syntax: - -```bash -127.0.0.1:6379> JSON.MSET k1 . '{"name": "John","address": {"street": "123 Main St","city": "Springfield"},"phones": ["555-1234","555-5678"]}' -OK -127.0.0.1:6379> JSON.MSET k1 .address.street '"21 2nd Street"' k1 .address.city '"New York"' -OK -127.0.0.1:6379> JSON.GET k1 .address.street -"\"21 2nd Street\"" -127.0.0.1:6379> JSON.GET k1 .address.city -"\"New York\"" - -``` diff --git a/commands/json.numincrby.md b/commands/json.numincrby.md deleted file mode 100644 index 17fea756..00000000 --- a/commands/json.numincrby.md +++ /dev/null @@ -1,123 +0,0 @@ -Increment the number values at the path by a given number. - -## Reply - -* If the path is enhanced syntax: - * Array of bulk strings representing the resulting value at each path. - * Null: For each path where the value is not a number. -* If the path is restricted syntax: - * String: The resulting value. - * String: If multiple values are selected, returns the result of the last updated value. -* Error: - * if the number cannot be parsed. - * if the result is out of the range of double. - * if the document key does not exist. - * if the value at the path is not a number (only for restricted syntax). - -## Examples - -Enhanced path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '{"a":[], "b":[1], "c":[1,2], "d":[1,2,3]}' -OK -127.0.0.1:6379> JSON.NUMINCRBY k1 $.d[*] 10 -"[11,12,13]" -127.0.0.1:6379> JSON.GET k1 -"{\"a\":[],\"b\":[1],\"c\":[1,2],\"d\":[11,12,13]}" - -127.0.0.1:6379> JSON.SET k1 $ '{"a":[], "b":[1], "c":[1,2], "d":[1,2,3]}' -OK -127.0.0.1:6379> JSON.NUMINCRBY k1 $.a[*] 1 -"[]" -127.0.0.1:6379> JSON.NUMINCRBY k1 $.b[*] 1 -"[2]" -127.0.0.1:6379> JSON.NUMINCRBY k1 $.c[*] 1 -"[2,3]" -127.0.0.1:6379> JSON.NUMINCRBY k1 $.d[*] 1 -"[2,3,4]" -127.0.0.1:6379> JSON.GET k1 -"{\"a\":[],\"b\":[2],\"c\":[2,3],\"d\":[2,3,4]}" - -127.0.0.1:6379> JSON.SET k2 $ '{"a":{}, "b":{"a":1}, "c":{"a":1, "b":2}, "d":{"a":1, "b":2, "c":3}}' -OK -127.0.0.1:6379> JSON.NUMINCRBY k2 $.a.* 1 -"[]" -127.0.0.1:6379> JSON.NUMINCRBY k2 $.b.* 1 -"[2]" -127.0.0.1:6379> JSON.NUMINCRBY k2 $.c.* 1 -"[2,3]" -127.0.0.1:6379> JSON.NUMINCRBY k2 $.d.* 1 -"[2,3,4]" -127.0.0.1:6379> JSON.GET k2 -"{\"a\":{},\"b\":{\"a\":2},\"c\":{\"a\":2,\"b\":3},\"d\":{\"a\":2,\"b\":3,\"c\":4}}" - -127.0.0.1:6379> JSON.SET k3 $ '{"a":{"a":"a"}, "b":{"a":"a", "b":1}, "c":{"a":"a", "b":"b"}, "d":{"a":1, "b":"b", "c":3}}' -OK -127.0.0.1:6379> JSON.NUMINCRBY k3 $.a.* 1 -"[null]" -127.0.0.1:6379> JSON.NUMINCRBY k3 $.b.* 1 -"[null,2]" -127.0.0.1:6379> JSON.NUMINCRBY k3 $.c.* 1 -"[null,null]" -127.0.0.1:6379> JSON.NUMINCRBY k3 $.d.* 1 -"[2,null,4]" -127.0.0.1:6379> JSON.GET k3 -"{\"a\":{\"a\":\"a\"},\"b\":{\"a\":\"a\",\"b\":2},\"c\":{\"a\":\"a\",\"b\":\"b\"},\"d\":{\"a\":2,\"b\":\"b\",\"c\":4}}" -``` - -Restricted path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '{"a":[], "b":[1], "c":[1,2], "d":[1,2,3]}' -OK -127.0.0.1:6379> JSON.NUMINCRBY k1 .d[1] 10 -"12" -127.0.0.1:6379> JSON.GET k1 -"{\"a\":[],\"b\":[1],\"c\":[1,2],\"d\":[1,12,3]}" - -127.0.0.1:6379> JSON.SET k1 . '{"a":[], "b":[1], "c":[1,2], "d":[1,2,3]}' -OK -127.0.0.1:6379> JSON.NUMINCRBY k1 .a[*] 1 -(error) NONEXISTENT JSON path does not exist -127.0.0.1:6379> JSON.NUMINCRBY k1 .b[*] 1 -"2" -127.0.0.1:6379> JSON.GET k1 -"{\"a\":[],\"b\":[2],\"c\":[1,2],\"d\":[1,2,3]}" -127.0.0.1:6379> JSON.NUMINCRBY k1 .c[*] 1 -"3" -127.0.0.1:6379> JSON.GET k1 -"{\"a\":[],\"b\":[2],\"c\":[2,3],\"d\":[1,2,3]}" -127.0.0.1:6379> JSON.NUMINCRBY k1 .d[*] 1 -"4" -127.0.0.1:6379> JSON.GET k1 -"{\"a\":[],\"b\":[2],\"c\":[2,3],\"d\":[2,3,4]}" - -127.0.0.1:6379> JSON.SET k2 . '{"a":{}, "b":{"a":1}, "c":{"a":1, "b":2}, "d":{"a":1, "b":2, "c":3}}' -OK -127.0.0.1:6379> JSON.NUMINCRBY k2 .a.* 1 -(error) NONEXISTENT JSON path does not exist -127.0.0.1:6379> JSON.NUMINCRBY k2 .b.* 1 -"2" -127.0.0.1:6379> JSON.GET k2 -"{\"a\":{},\"b\":{\"a\":2},\"c\":{\"a\":1,\"b\":2},\"d\":{\"a\":1,\"b\":2,\"c\":3}}" -127.0.0.1:6379> JSON.NUMINCRBY k2 .c.* 1 -"3" -127.0.0.1:6379> JSON.GET k2 -"{\"a\":{},\"b\":{\"a\":2},\"c\":{\"a\":2,\"b\":3},\"d\":{\"a\":1,\"b\":2,\"c\":3}}" -127.0.0.1:6379> JSON.NUMINCRBY k2 .d.* 1 -"4" -127.0.0.1:6379> JSON.GET k2 -"{\"a\":{},\"b\":{\"a\":2},\"c\":{\"a\":2,\"b\":3},\"d\":{\"a\":2,\"b\":3,\"c\":4}}" - -127.0.0.1:6379> JSON.SET k3 . '{"a":{"a":"a"}, "b":{"a":"a", "b":1}, "c":{"a":"a", "b":"b"}, "d":{"a":1, "b":"b", "c":3}}' -OK -127.0.0.1:6379> JSON.NUMINCRBY k3 .a.* 1 -(error) WRONGTYPE JSON element is not a number -127.0.0.1:6379> JSON.NUMINCRBY k3 .b.* 1 -"2" -127.0.0.1:6379> JSON.NUMINCRBY k3 .c.* 1 -(error) WRONGTYPE JSON element is not a number -127.0.0.1:6379> JSON.NUMINCRBY k3 .d.* 1 -"4" -``` diff --git a/commands/json.nummultby.md b/commands/json.nummultby.md deleted file mode 100644 index 9ff286eb..00000000 --- a/commands/json.nummultby.md +++ /dev/null @@ -1,121 +0,0 @@ -Multiply the number values at the path by a given number. - -## Reply - -* If the path is enhanced syntax: - * Array of bulk strings representing the resulting value at each path. - * Null: For each path where the value is not a number. -* If the path is restricted syntax: - * String: The resulting value. - * String: If multiple values are selected, returns the result of the last updated value. -* Error: - * if the number cannot be parsed. - * if the result is out of the range of double. - * if the document key does not exist. - * if the value at the path is not a number (only for restricted syntax). - -## Examples - -Enhanced path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '{"a":[], "b":[1], "c":[1,2], "d":[1,2,3]}' -OK -127.0.0.1:6379> JSON.NUMMULTBY k1 $.d[*] 2 -"[2,4,6]" -127.0.0.1:6379> JSON.GET k1 -"{\"a\":[],\"b\":[1],\"c\":[1,2],\"d\":[2,4,6]}" - -127.0.0.1:6379> JSON.SET k1 $ '{"a":[], "b":[1], "c":[1,2], "d":[1,2,3]}' -OK -127.0.0.1:6379> JSON.NUMMULTBY k1 $.a[*] 2 -"[]" -127.0.0.1:6379> JSON.NUMMULTBY k1 $.b[*] 2 -"[2]" -127.0.0.1:6379> JSON.NUMMULTBY k1 $.c[*] 2 -"[2,4]" -127.0.0.1:6379> JSON.NUMMULTBY k1 $.d[*] 2 -"[2,4,6]" - -127.0.0.1:6379> JSON.SET k2 $ '{"a":{}, "b":{"a":1}, "c":{"a":1, "b":2}, "d":{"a":1, "b":2, "c":3}}' -OK -127.0.0.1:6379> JSON.NUMMULTBY k2 $.a.* 2 -"[]" -127.0.0.1:6379> JSON.NUMMULTBY k2 $.b.* 2 -"[2]" -127.0.0.1:6379> JSON.NUMMULTBY k2 $.c.* 2 -"[2,4]" -127.0.0.1:6379> JSON.NUMMULTBY k2 $.d.* 2 -"[2,4,6]" - -127.0.0.1:6379> JSON.SET k3 $ '{"a":{"a":"a"}, "b":{"a":"a", "b":1}, "c":{"a":"a", "b":"b"}, "d":{"a":1, "b":"b", "c":3}}' -OK -127.0.0.1:6379> JSON.NUMMULTBY k3 $.a.* 2 -"[null]" -127.0.0.1:6379> JSON.NUMMULTBY k3 $.b.* 2 -"[null,2]" -127.0.0.1:6379> JSON.NUMMULTBY k3 $.c.* 2 -"[null,null]" -127.0.0.1:6379> JSON.NUMMULTBY k3 $.d.* 2 -"[2,null,6]" -``` - -Restricted path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '{"a":[], "b":[1], "c":[1,2], "d":[1,2,3]}' -OK -127.0.0.1:6379> JSON.NUMMULTBY k1 .d[1] 2 -"4" -127.0.0.1:6379> JSON.GET k1 -"{\"a\":[],\"b\":[1],\"c\":[1,2],\"d\":[1,4,3]}" - -127.0.0.1:6379> JSON.SET k1 . '{"a":[], "b":[1], "c":[1,2], "d":[1,2,3]}' -OK -127.0.0.1:6379> JSON.NUMMULTBY k1 .a[*] 2 -(error) NONEXISTENT JSON path does not exist -127.0.0.1:6379> JSON.NUMMULTBY k1 .b[*] 2 -"2" -127.0.0.1:6379> JSON.GET k1 -"{\"a\":[],\"b\":[2],\"c\":[1,2],\"d\":[1,2,3]}" -127.0.0.1:6379> JSON.NUMMULTBY k1 .c[*] 2 -"4" -127.0.0.1:6379> JSON.GET k1 -"{\"a\":[],\"b\":[2],\"c\":[2,4],\"d\":[1,2,3]}" -127.0.0.1:6379> JSON.NUMMULTBY k1 .d[*] 2 -"6" -127.0.0.1:6379> JSON.GET k1 -"{\"a\":[],\"b\":[2],\"c\":[2,4],\"d\":[2,4,6]}" - -127.0.0.1:6379> JSON.SET k2 . '{"a":{}, "b":{"a":1}, "c":{"a":1, "b":2}, "d":{"a":1, "b":2, "c":3}}' -OK -127.0.0.1:6379> JSON.NUMMULTBY k2 .a.* 2 -(error) NONEXISTENT JSON path does not exist -127.0.0.1:6379> JSON.NUMMULTBY k2 .b.* 2 -"2" -127.0.0.1:6379> JSON.GET k2 -"{\"a\":{},\"b\":{\"a\":2},\"c\":{\"a\":1,\"b\":2},\"d\":{\"a\":1,\"b\":2,\"c\":3}}" -127.0.0.1:6379> JSON.NUMMULTBY k2 .c.* 2 -"4" -127.0.0.1:6379> JSON.GET k2 -"{\"a\":{},\"b\":{\"a\":2},\"c\":{\"a\":2,\"b\":4},\"d\":{\"a\":1,\"b\":2,\"c\":3}}" -127.0.0.1:6379> JSON.NUMMULTBY k2 .d.* 2 -"6" -127.0.0.1:6379> JSON.GET k2 -"{\"a\":{},\"b\":{\"a\":2},\"c\":{\"a\":2,\"b\":4},\"d\":{\"a\":2,\"b\":4,\"c\":6}}" - -127.0.0.1:6379> JSON.SET k3 . '{"a":{"a":"a"}, "b":{"a":"a", "b":1}, "c":{"a":"a", "b":"b"}, "d":{"a":1, "b":"b", "c":3}}' -OK -127.0.0.1:6379> JSON.NUMMULTBY k3 .a.* 2 -(error) WRONGTYPE JSON element is not a number -127.0.0.1:6379> JSON.NUMMULTBY k3 .b.* 2 -"2" -127.0.0.1:6379> JSON.GET k3 -"{\"a\":{\"a\":\"a\"},\"b\":{\"a\":\"a\",\"b\":2},\"c\":{\"a\":\"a\",\"b\":\"b\"},\"d\":{\"a\":1,\"b\":\"b\",\"c\":3}}" -127.0.0.1:6379> JSON.NUMMULTBY k3 .c.* 2 -(error) WRONGTYPE JSON element is not a number -127.0.0.1:6379> JSON.NUMMULTBY k3 .d.* 2 -"6" -127.0.0.1:6379> JSON.GET k3 -"{\"a\":{\"a\":\"a\"},\"b\":{\"a\":\"a\",\"b\":2},\"c\":{\"a\":\"a\",\"b\":\"b\"},\"d\":{\"a\":2,\"b\":\"b\",\"c\":6}}" -``` diff --git a/commands/json.objkeys.md b/commands/json.objkeys.md deleted file mode 100644 index e66b9cff..00000000 --- a/commands/json.objkeys.md +++ /dev/null @@ -1,50 +0,0 @@ -Get key names in the object values at the path. - -## Reply - -* If the path is enhanced syntax: - * Array of arrays, each containing bulk strings representing keys in a matching object. - * Array: Empty array for each path where the value is not an object. - * Null: If the document key does not exist. -* If the path is restricted syntax: - * Array of bulk strings, each representing a key name in the object. - * Array: If multiple objects are selected, returns the keys of the first object. - * Null: If the document key does not exist. -* Error: - * if the value at the path is not an object (only for restricted syntax). - * if the path does not exist (only for restricted syntax). - -## Examples - -Enhanced path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 $ '{"a":{}, "b":{"a":"a"}, "c":{"a":"a", "b":"bb"}, "d":{"a":1, "b":"b", "c":{"a":3,"b":4}}, "e":1}' -OK -127.0.0.1:6379> JSON.OBJKEYS k1 $.* -1) (empty array) -2) 1) "a" -3) 1) "a" - 2) "b" -4) 1) "a" - 2) "b" - 3) "c" -5) (empty array) -127.0.0.1:6379> JSON.OBJKEYS k1 $.d -1) 1) "a" - 2) "b" - 3) "c" -``` - -Restricted path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 $ '{"a":{}, "b":{"a":"a"}, "c":{"a":"a", "b":"bb"}, "d":{"a":1, "b":"b", "c":{"a":3,"b":4}}, "e":1}' -OK -127.0.0.1:6379> JSON.OBJKEYS k1 .* -1) "a" -127.0.0.1:6379> JSON.OBJKEYS k1 .d -1) "a" -2) "b" -3) "c" -``` diff --git a/commands/json.objlen.md b/commands/json.objlen.md deleted file mode 100644 index 0da19718..00000000 --- a/commands/json.objlen.md +++ /dev/null @@ -1,74 +0,0 @@ -Get number of keys in the object values at the path. - -## Reply - -* If the path is enhanced syntax: - * Array of integers representing the object length at each path. - * Null: For each path where the value is not an object. - * Null: If the document key does not exist. -* If the path is restricted syntax: - * Integer: Number of keys in the object. - * Integer: If multiple objects are selected, returns the first object's length. - * Null: If the document key does not exist. -* Error: - * if the value at the path is not an object (only for restricted syntax). - * if the path does not exist (only for restricted syntax). - -## Examples - -Enhanced path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 $ '{"a":{}, "b":{"a":"a"}, "c":{"a":"a", "b":"bb"}, "d":{"a":1, "b":"b", "c":{"a":3,"b":4}}, "e":1}' -OK -127.0.0.1:6379> JSON.OBJLEN k1 $.a -1) (integer) 0 -127.0.0.1:6379> JSON.OBJLEN k1 $.a.* -(empty array) -127.0.0.1:6379> JSON.OBJLEN k1 $.b -1) (integer) 1 -127.0.0.1:6379> JSON.OBJLEN k1 $.b.* -1) (nil) -127.0.0.1:6379> JSON.OBJLEN k1 $.c -1) (integer) 2 -127.0.0.1:6379> JSON.OBJLEN k1 $.c.* -1) (nil) -2) (nil) -127.0.0.1:6379> JSON.OBJLEN k1 $.d -1) (integer) 3 -127.0.0.1:6379> JSON.OBJLEN k1 $.d.* -1) (nil) -2) (nil) -3) (integer) 2 -127.0.0.1:6379> JSON.OBJLEN k1 $.* -1) (integer) 0 -2) (integer) 1 -3) (integer) 2 -4) (integer) 3 -5) (nil) -``` - -Restricted path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '{"a":{}, "b":{"a":"a"}, "c":{"a":"a", "b":"bb"}, "d":{"a":1, "b":"b", "c":{"a":3,"b":4}}, "e":1}' -OK -127.0.0.1:6379> JSON.OBJLEN k1 .a -(integer) 0 -127.0.0.1:6379> JSON.OBJLEN k1 .a.* -(error) NONEXISTENT JSON path does not exist -127.0.0.1:6379> JSON.OBJLEN k1 .b -(integer) 1 -127.0.0.1:6379> JSON.OBJLEN k1 .b.* -(error) WRONGTYPE JSON element is not an object -127.0.0.1:6379> JSON.OBJLEN k1 .c -(integer) 2 -127.0.0.1:6379> JSON.OBJLEN k1 .c.* -(error) WRONGTYPE JSON element is not an object -127.0.0.1:6379> JSON.OBJLEN k1 .d -(integer) 3 -127.0.0.1:6379> JSON.OBJLEN k1 .d.* -(integer) 2 -127.0.0.1:6379> JSON.OBJLEN k1 .* -(integer) 0 -``` diff --git a/commands/json.resp.md b/commands/json.resp.md deleted file mode 100644 index 4b23b081..00000000 --- a/commands/json.resp.md +++ /dev/null @@ -1,128 +0,0 @@ -Return the JSON value at the given path in Redis Serialization Protocol (RESP). -If the value is container, the response is RESP array or nested array. - - -* JSON null is mapped to the RESP Null Bulk String. -* JSON boolean values are mapped to the respective RESP Simple Strings. -* Integer numbers are mapped to RESP Integers. -* Floating point numbers are mapped to RESP Bulk Strings. -* JSON Strings are mapped to RESP Bulk Strings. -* JSON Arrays are represented as RESP Arrays, where the first element is the simple string [, followed by the array's elements. -* JSON Objects are represented as RESP Arrays, where the first element is the simple string {, followed by key-value pairs, each of which is a RESP bulk string. - -## Reply - -* If the path is enhanced syntax: - * Array of arrays, each representing the RESP form of the value at one path. - * Array: Empty array if the document key does not exist. -* If the path is restricted syntax: - * Array: Representing the RESP form of the value at the path. - * Null: If the document key does not exist. - -## Examples - -Enhanced path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '{"firstName":"John","lastName":"Smith","age":27,"weight":135.25,"isAlive":true,"address":{"street":"21 2nd Street","city":"New York","state":"NY","zipcode":"10021-3100"},"phoneNumbers":[{"type":"home","number":"212 555-1234"},{"type":"office","number":"646 555-4567"}],"children":[],"spouse":null}' -OK - -127.0.0.1:6379> JSON.RESP k1 $.address -1) 1) { - 2) 1) "street" - 2) "21 2nd Street" - 3) 1) "city" - 2) "New York" - 4) 1) "state" - 2) "NY" - 5) 1) "zipcode" - 2) "10021-3100" - -127.0.0.1:6379> JSON.RESP k1 $.address.* -1) "21 2nd Street" -2) "New York" -3) "NY" -4) "10021-3100" - -127.0.0.1:6379> JSON.RESP k1 $.phoneNumbers -1) 1) [ - 2) 1) { - 2) 1) "type" - 2) "home" - 3) 1) "number" - 2) "212 555-1234" - 3) 1) { - 2) 1) "type" - 2) "office" - 3) 1) "number" - 2) "646 555-4567" - -127.0.0.1:6379> JSON.RESP k1 $.phoneNumbers[*] -1) 1) { - 2) 1) "type" - 2) "home" - 3) 1) "number" - 2) "212 555-1234" -2) 1) { - 2) 1) "type" - 2) "office" - 3) 1) "number" - 2) "646 555-4567" -``` - -Restricted path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '{"firstName":"John","lastName":"Smith","age":27,"weight":135.25,"isAlive":true,"address":{"street":"21 2nd Street","city":"New York","state":"NY","zipcode":"10021-3100"},"phoneNumbers":[{"type":"home","number":"212 555-1234"},{"type":"office","number":"646 555-4567"}],"children":[],"spouse":null}' -OK - -127.0.0.1:6379> JSON.RESP k1 .address -1) { -2) 1) "street" - 2) "21 2nd Street" -3) 1) "city" - 2) "New York" -4) 1) "state" - 2) "NY" -5) 1) "zipcode" - 2) "10021-3100" - -127.0.0.1:6379> JSON.RESP k1 - 1) { - 2) 1) "firstName" - 2) "John" - 3) 1) "lastName" - 2) "Smith" - 4) 1) "age" - 2) (integer) 27 - 5) 1) "weight" - 2) "135.25" - 6) 1) "isAlive" - 2) true - 7) 1) "address" - 2) 1) { - 2) 1) "street" - 2) "21 2nd Street" - 3) 1) "city" - 2) "New York" - 4) 1) "state" - 2) "NY" - 5) 1) "zipcode" - 2) "10021-3100" - 8) 1) "phoneNumbers" - 2) 1) [ - 2) 1) { - 2) 1) "type" - 2) "home" - 3) 1) "number" - 2) "212 555-1234" - 3) 1) { - 2) 1) "type" - 2) "office" - 3) 1) "number" - 2) "646 555-4567" - 9) 1) "children" - 2) 1) [ -10) 1) "spouse" - 2) (nil) -``` diff --git a/commands/json.set.md b/commands/json.set.md deleted file mode 100644 index 0626714d..00000000 --- a/commands/json.set.md +++ /dev/null @@ -1,58 +0,0 @@ -Set JSON values at the path. - - -* If the path calls for an object member: - * If the parent element does not exist, the command will return NONEXISTENT error. - * If the parent element exists but is not an object, the command will return ERROR. - * If the parent element exists and is an object: - * If the member does not exist, a new member will be appended to the parent object if and only if the - parent object is the last child in the path. Otherwise, the command will return NONEXISTENT error. - * If the member exists, its value will be replaced by the JSON value. -* If the path calls for an array index: - * If the parent element does not exist, the command will return a NONEXISTENT error. - * If the parent element exists but is not an array, the command will return ERROR. - * If the parent element exists but the index is out of bounds, the command will return OUTOFBOUNDARIES error. - * If the parent element exists and the index is valid, the element will be replaced by the new JSON value. -* If the path calls for an object or array, the value (object or array) will be replaced by the new JSON value. - -## Reply - -* `OK` on success. -* Null: If the NX or XX condition is not met. - -## Examples - -Enhanced path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '{"a":{"a":1, "b":2, "c":3}}' -OK -127.0.0.1:6379> JSON.SET k1 $.a.* '0' -OK -127.0.0.1:6379> JSON.GET k1 -"{\"a\":{\"a\":0,\"b\":0,\"c\":0}}" - -127.0.0.1:6379> JSON.SET k2 . '{"a": [1,2,3,4,5]}' -OK -127.0.0.1:6379> JSON.SET k2 $.a[*] '0' -OK -127.0.0.1:6379> JSON.GET k2 -"{\"a\":[0,0,0,0,0]}" -``` - -Restricted path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '{"c":{"a":1, "b":2}, "e": [1,2,3,4,5]}' -OK -127.0.0.1:6379> JSON.SET k1 .c.a '0' -OK -127.0.0.1:6379> JSON.GET k1 -"{\"c\":{\"a\":0,\"b\":2},\"e\":[1,2,3,4,5]}" -127.0.0.1:6379> JSON.SET k1 .e[-1] '0' -OK -127.0.0.1:6379> JSON.GET k1 -"{\"c\":{\"a\":0,\"b\":2},\"e\":[1,2,3,4,0]}" -127.0.0.1:6379> JSON.SET k1 .e[5] '0' -(error) OUTOFBOUNDARIES Array index is out of bounds -``` diff --git a/commands/json.strappend.md b/commands/json.strappend.md deleted file mode 100644 index 66813ffc..00000000 --- a/commands/json.strappend.md +++ /dev/null @@ -1,58 +0,0 @@ -Append a string to the JSON strings at the path. - -## Reply - -* If the path is enhanced syntax: - * Array of integers representing the new length of the string at each path. - * Null: For each path where the value is not a string. -* If the path is restricted syntax: - * Integer: The string's new length. - * Integer: If multiple string values are selected, returns the new length of the last updated string. -* Error: - * if the input json argument is not a valid JSON string. - * if the path does not exist. - * if the value at the path is not a string (only for restricted syntax). - -## Examples - -Enhanced path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 $ '{"a":{"a":"a"}, "b":{"a":"a", "b":1}, "c":{"a":"a", "b":"bb"}, "d":{"a":1, "b":"b", "c":3}}' -OK -127.0.0.1:6379> JSON.STRAPPEND k1 $.a.a '"a"' -1) (integer) 2 -127.0.0.1:6379> JSON.STRAPPEND k1 $.a.* '"a"' -1) (integer) 3 -127.0.0.1:6379> JSON.STRAPPEND k1 $.b.* '"a"' -1) (integer) 2 -2) (nil) -127.0.0.1:6379> JSON.STRAPPEND k1 $.c.* '"a"' -1) (integer) 2 -2) (integer) 3 -127.0.0.1:6379> JSON.STRAPPEND k1 $.c.b '"a"' -1) (integer) 4 -127.0.0.1:6379> JSON.STRAPPEND k1 $.d.* '"a"' -1) (nil) -2) (integer) 2 -3) (nil) -```` - -Restricted path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '{"a":{"a":"a"}, "b":{"a":"a", "b":1}, "c":{"a":"a", "b":"bb"}, "d":{"a":1, "b":"b", "c":3}}' -OK -127.0.0.1:6379> JSON.STRAPPEND k1 .a.a '"a"' -(integer) 2 -127.0.0.1:6379> JSON.STRAPPEND k1 .a.* '"a"' -(integer) 3 -127.0.0.1:6379> JSON.STRAPPEND k1 .b.* '"a"' -(integer) 2 -127.0.0.1:6379> JSON.STRAPPEND k1 .c.* '"a"' -(integer) 3 -127.0.0.1:6379> JSON.STRAPPEND k1 .c.b '"a"' -(integer) 4 -127.0.0.1:6379> JSON.STRAPPEND k1 .d.* '"a"' -(integer) 2 -``` diff --git a/commands/json.strlen.md b/commands/json.strlen.md deleted file mode 100644 index a26e5f5d..00000000 --- a/commands/json.strlen.md +++ /dev/null @@ -1,54 +0,0 @@ -Get lengths of the JSON string values at the path. - -## Reply - -* If the path is enhanced syntax: - * Array of integers representing the length of string value at each path. - * Null: For each path where the value is not a string. - * Null: If the document key does not exist. -* If the path is restricted syntax: - * Integer: The string's length. - * Integer: If multiple string values are selected, returns the first string's length. - * Null: If the document key does not exist. -* Error: - * if the value at the path is not a string (only for restricted syntax). - * if the path does not exist (only for restricted syntax). - -## Examples - -Enhanced path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 $ '{"a":{"a":"a"}, "b":{"a":"a", "b":1}, "c":{"a":"a", "b":"bb"}, "d":{"a":1, "b":"b", "c":3}}' -OK -127.0.0.1:6379> JSON.STRLEN k1 $.a.a -1) (integer) 1 -127.0.0.1:6379> JSON.STRLEN k1 $.a.* -1) (integer) 1 -127.0.0.1:6379> JSON.STRLEN k1 $.c.* -1) (integer) 1 -2) (integer) 2 -127.0.0.1:6379> JSON.STRLEN k1 $.c.b -1) (integer) 2 -127.0.0.1:6379> JSON.STRLEN k1 $.d.* -1) (nil) -2) (integer) 1 -3) (nil) -``` - -Restricted path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 $ '{"a":{"a":"a"}, "b":{"a":"a", "b":1}, "c":{"a":"a", "b":"bb"}, "d":{"a":1, "b":"b", "c":3}}' -OK -127.0.0.1:6379> JSON.STRLEN k1 .a.a -(integer) 1 -127.0.0.1:6379> JSON.STRLEN k1 .a.* -(integer) 1 -127.0.0.1:6379> JSON.STRLEN k1 .c.* -(integer) 1 -127.0.0.1:6379> JSON.STRLEN k1 .c.b -(integer) 2 -127.0.0.1:6379> JSON.STRLEN k1 .d.* -(integer) 1 -``` diff --git a/commands/json.toggle.md b/commands/json.toggle.md deleted file mode 100644 index cedc7b49..00000000 --- a/commands/json.toggle.md +++ /dev/null @@ -1,55 +0,0 @@ -Toggle boolean values between true and false at the path. - -## Reply - -* If the path is enhanced syntax: - * Array of integers (0 for false, 1 for true) representing the resulting boolean value at each path. - * Null: For each path where the value is not a boolean. -* If the path is restricted syntax: - * String: 'true' or 'false' representing the resulting boolean value. -* Error: - * if the document key does not exist. - * if the value at the path is not a boolean (only for restricted syntax). - -## Examples - -Enhanced path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '{"a":true, "b":false, "c":1, "d":null, "e":"foo", "f":[], "g":{}}' -OK -127.0.0.1:6379> JSON.TOGGLE k1 $.* -1) (integer) 0 -2) (integer) 1 -3) (nil) -4) (nil) -5) (nil) -6) (nil) -7) (nil) -127.0.0.1:6379> JSON.TOGGLE k1 $.* -1) (integer) 1 -2) (integer) 0 -3) (nil) -4) (nil) -5) (nil) -6) (nil) -7) (nil) -``` - -Restricted path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . true -OK -127.0.0.1:6379> JSON.TOGGLE k1 -"false" -127.0.0.1:6379> JSON.TOGGLE k1 -"true" - -127.0.0.1:6379> JSON.SET k2 . '{"isAvailable": false}' -OK -127.0.0.1:6379> JSON.TOGGLE k2 .isAvailable -"true" -127.0.0.1:6379> JSON.TOGGLE k2 .isAvailable -"false" -``` diff --git a/commands/json.type.md b/commands/json.type.md deleted file mode 100644 index 46074b5d..00000000 --- a/commands/json.type.md +++ /dev/null @@ -1,50 +0,0 @@ -Report type of the values at the given path. - -## Reply - -* If the path is enhanced syntax: - * Array of strings representing type of the value at each path (one of: 'null', 'boolean', 'string', 'number', 'integer', 'object', 'array'). - * Null: For each path that does not exist. - * Array: Empty array if the document key does not exist. -* If the path is restricted syntax: - * String: Type of the value. - * Null: If the document key does not exist. - * Null: If the JSON path is invalid or does not exist. - -## Examples - -Enhanced path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '[1, 2.3, "foo", true, null, {}, []]' -OK -127.0.0.1:6379> JSON.TYPE k1 $[*] -1) integer -2) number -3) string -4) boolean -5) null -6) object -7) array -``` - -Restricted path syntax: - -```bash -127.0.0.1:6379> JSON.SET k1 . '{"firstName":"John","lastName":"Smith","age":27,"weight":135.25,"isAlive":true,"address":{"street":"21 2nd Street","city":"New York","state":"NY","zipcode":"10021-3100"},"phoneNumbers":[{"type":"home","number":"212 555-1234"},{"type":"office","number":"646 555-4567"}],"children":[],"spouse":null}' -OK -127.0.0.1:6379> JSON.TYPE k1 -object -127.0.0.1:6379> JSON.TYPE k1 .children -array -127.0.0.1:6379> JSON.TYPE k1 .firstName -string -127.0.0.1:6379> JSON.TYPE k1 .age -integer -127.0.0.1:6379> JSON.TYPE k1 .weight -number -127.0.0.1:6379> JSON.TYPE k1 .isAlive -boolean -127.0.0.1:6379> JSON.TYPE k1 .spouse -null -``` diff --git a/commands/keys.md b/commands/keys.md deleted file mode 100644 index 78bf233a..00000000 --- a/commands/keys.md +++ /dev/null @@ -1,54 +0,0 @@ -Returns all keys matching `pattern`. - -While the time complexity for this operation is O(N), the constant times are -fairly low. -For example, Valkey running on an entry level laptop can scan a 1 million key -database in 40 milliseconds. - -**Warning**: consider `KEYS` as a command that should only be used in production -environments with extreme care. -It may ruin performance when it is executed against large databases. -This command is intended for debugging and special operations, such as changing -your keyspace layout. -Don't use `KEYS` in your regular application code. -If you're looking for a way to find keys in a subset of your keyspace, consider -using [`SCAN`](scan.md) or [sets][tdts]. - -[tdts]: ../topics/data-types.md#sets - -Supported glob-style patterns: - -* `h?llo` matches `hello`, `hallo` and `hxllo` -* `h*llo` matches `hllo` and `heeeello` -* `h[ae]llo` matches `hello` and `hallo,` but not `hillo` -* `h[^e]llo` matches `hallo`, `hbllo`, ... but not `hello` -* `h[a-b]llo` matches `hallo` and `hbllo` - -Use `\` to escape special characters if you want to match them verbatim. - -When using [Valkey Cluster](../topics/cluster-tutorial.md), the search is optimized for patterns that imply a single slot. -If a pattern can only match keys of one slot, -Valkey only iterates over keys in that slot, rather than the whole database, -when searching for keys matching the pattern. -For example, with the pattern `{a}h*llo`, Valkey would only try to match it with the keys in slot 15495, which hash tag `{a}` implies. -To use pattern with hash tag, see [Hash tags](../topics/cluster-spec.md#hash-tags) in the Cluster specification for more information. - -## Reply - -Array of keys matching _pattern_. - -## Examples - -``` -127.0.0.1:6379> MSET firstname Jack lastname Stuntman age 35 -OK -127.0.0.1:6379> KEYS *name* -1) "lastname" -2) "firstname" -127.0.0.1:6379> KEYS a?? -1) "age" -127.0.0.1:6379> KEYS * -1) "age" -2) "lastname" -3) "firstname" -``` diff --git a/commands/lastsave.md b/commands/lastsave.md deleted file mode 100644 index 35dcd3f3..00000000 --- a/commands/lastsave.md +++ /dev/null @@ -1,8 +0,0 @@ -Return the UNIX TIME of the last DB save executed with success. -A client may check if a [`BGSAVE`](bgsave.md) command succeeded reading the `LASTSAVE` value, -then issuing a `BGSAVE` command and checking at regular intervals every N -seconds if `LASTSAVE` changed. Valkey considers the database saved successfully at startup. - -## Reply - -Integer: UNIX TIME of the last DB save executed with success. diff --git a/commands/latency-doctor.md b/commands/latency-doctor.md deleted file mode 100644 index 71f2c219..00000000 --- a/commands/latency-doctor.md +++ /dev/null @@ -1,44 +0,0 @@ -The `LATENCY DOCTOR` command reports about different latency-related issues and advises about possible remedies. - -This command is the most powerful analysis tool in the latency monitoring -framework, and is able to provide additional statistical data like the average -period between latency spikes, the median deviation, and a human-readable -analysis of the event. For certain events, like `fork`, additional information -is provided, like the rate at which the system forks processes. - -This is the output you should provide if you are looking for help about Latency related issues. - -## Reply - -Verbatim string: a human readable latency analysis report. - -## Examples - -``` -127.0.0.1:6379> latency doctor - -Dave, I have observed latency spikes in this Valkey instance. -You don't mind talking about it, do you Dave? - -1. command: 5 latency spikes (average 300ms, mean deviation 120ms, - period 73.40 sec). Worst all time event 500ms. - -I have a few advices for you: - -- Your current Slow Log configuration only logs events that are - slower than your configured latency monitor threshold. Please - use 'CONFIG SET slowlog-log-slower-than 1000'. -- Check your Slow Log to understand what are the commands you are - running which are too slow to execute. Please check - [SLOWLOG](slowlog.md) for more information. -- Deleting, expiring or evicting (because of maxmemory policy) - large objects is a blocking operation. If you have very large - objects that are often deleted, expired, or evicted, try to - fragment those objects into multiple smaller objects. -``` - -**Note:** the doctor has erratic psychological behaviors, so we recommend interacting with it carefully. - -For more information refer to the [Latency Monitoring Framework page][lm]. - -[lm]: ../topics/latency-monitor.md diff --git a/commands/latency-graph.md b/commands/latency-graph.md deleted file mode 100644 index 16babb3f..00000000 --- a/commands/latency-graph.md +++ /dev/null @@ -1,64 +0,0 @@ -Produces an ASCII-art style graph for the specified event. - -`LATENCY GRAPH` lets you intuitively understand the latency trend of an `event` via state-of-the-art visualization. It can be used for quickly grasping the situation before resorting to means such parsing the raw data from [`LATENCY HISTORY`](latency-history.md) or external tooling. - -Valid values for `event` are: -* `active-defrag-cycle` -* `aof-fsync-always` -* `aof-stat` -* `aof-rewrite-diff-write` -* `aof-rename` -* `aof-write` -* `aof-write-active-child` -* `aof-write-alone` -* `aof-write-pending-fsync` -* `command` -* `expire-cycle` -* `eviction-cycle` -* `eviction-del` -* `fast-command` -* `fork` -* `rdb-unlink-temp-file` - -## Reply - -Verbatim string: Latency graph - -## Examples - -``` -127.0.0.1:6379> latency reset command -(integer) 0 -127.0.0.1:6379> debug sleep .1 -OK -127.0.0.1:6379> debug sleep .2 -OK -127.0.0.1:6379> debug sleep .3 -OK -127.0.0.1:6379> debug sleep .5 -OK -127.0.0.1:6379> debug sleep .4 -OK -127.0.0.1:6379> latency graph command -command - high 500 ms, low 101 ms (all time high 500 ms) --------------------------------------------------------------------------------- - #_ - _|| - _||| -_|||| - -11186 -542ss -sss -``` - -The vertical labels under each graph column represent the amount of seconds, -minutes, hours or days ago the event happened. For example "15s" means that the -first graphed event happened 15 seconds ago. - -The graph is normalized in the min-max scale so that the zero (the underscore -in the lower row) is the minimum, and a # in the higher row is the maximum. - -For more information refer to the [Latency Monitoring Framework page][lm]. - -[lm]: ../topics/latency-monitor.md diff --git a/commands/latency-help.md b/commands/latency-help.md deleted file mode 100644 index 0098eb17..00000000 --- a/commands/latency-help.md +++ /dev/null @@ -1,10 +0,0 @@ -The `LATENCY HELP` command returns a helpful text describing the different -subcommands. - -For more information refer to the [Latency Monitoring Framework page][lm]. - -[lm]: ../topics/latency-monitor.md - -## Reply - -Array of sub-commands and their descriptions. diff --git a/commands/latency-histogram.md b/commands/latency-histogram.md deleted file mode 100644 index 71a689c6..00000000 --- a/commands/latency-histogram.md +++ /dev/null @@ -1,40 +0,0 @@ -`LATENCY HISTOGRAM` returns a cumulative distribution of commands' latencies in histogram format. - -By default, all available latency histograms are returned. -You can filter the reply by providing specific command names. - -Each histogram consists of the following fields: - -* Command name -* The total calls for that command -* A map of time buckets: - * Each bucket represents a latency range - * Each bucket covers twice the previous bucket's range - * Empty buckets are excluded from the reply - * The tracked latencies are between 1 microsecond and roughly 1 second - * Everything above 1 second is considered +Inf - * At max, there will be log2(1,000,000,000)=30 buckets - -This command requires the extended latency monitoring feature to be enabled, which is the default. -If you need to enable it, call [`CONFIG SET latency-tracking yes`](config-set.md). - -To delete the latency histograms' data use the [`CONFIG RESETSTAT`](config-resetstat.md) command. - -## Reply - -Map where each key is a command name, and each value is a map with the total calls, and an inner map of the histogram time buckets. - -## Examples - -``` -127.0.0.1:6379> LATENCY HISTOGRAM set -1# "set" => - 1# "calls" => (integer) 100000 - 2# "histogram_usec" => - 1# (integer) 1 => (integer) 99583 - 2# (integer) 2 => (integer) 99852 - 3# (integer) 4 => (integer) 99914 - 4# (integer) 8 => (integer) 99940 - 5# (integer) 16 => (integer) 99968 - 6# (integer) 33 => (integer) 100000 -``` diff --git a/commands/latency-history.md b/commands/latency-history.md deleted file mode 100644 index 6f9761d7..00000000 --- a/commands/latency-history.md +++ /dev/null @@ -1,41 +0,0 @@ -The `LATENCY HISTORY` command returns the raw data of the `event`'s latency spikes time series. - -This is useful to an application that wants to fetch raw data in order to perform monitoring, display graphs, and so forth. - -The command will return up to 160 timestamp-latency pairs for the `event`. - -Valid values for `event` are: -* `active-defrag-cycle` -* `aof-fsync-always` -* `aof-stat` -* `aof-rewrite-diff-write` -* `aof-rename` -* `aof-write` -* `aof-write-active-child` -* `aof-write-alone` -* `aof-write-pending-fsync` -* `command` -* `expire-cycle` -* `eviction-cycle` -* `eviction-del` -* `fast-command` -* `fork` -* `rdb-unlink-temp-file` - -## Reply - -Array where each element is a two elements array representing the timestamp and the latency of the event. - -## Examples - -``` -127.0.0.1:6379> latency history command -1) 1) (integer) 1405067822 - 2) (integer) 251 -2) 1) (integer) 1405067941 - 2) (integer) 1001 -``` - -For more information refer to the [Latency Monitoring Framework page][lm]. - -[lm]: ../topics/latency-monitor.md diff --git a/commands/latency-latest.md b/commands/latency-latest.md deleted file mode 100644 index 40e36981..00000000 --- a/commands/latency-latest.md +++ /dev/null @@ -1,38 +0,0 @@ -The `LATENCY LATEST` command reports the latest latency events logged. - -Each reported event has the following fields: - -* Event name. -* Unix timestamp of the latest latency spike for the event. -* Latest event latency in millisecond. -* All-time maximum latency for this event. -* Sum of the latencies recorded in the time series for this event, added in 8.1. -* The number of latency spikes recorded in the time series for this event, added in 8.1. - -"All-time" means the maximum latency since the Valkey instance was -started, or the time that events were reset [`LATENCY RESET`](latency-reset.md). - -## Reply - -Array where each element is a four elements array representing the event's name, timestamp, latest and all-time latency measurements. - -## Examples - -``` -127.0.0.1:6379> debug sleep 1 -OK -(1.00s) -127.0.0.1:6379> debug sleep .25 -OK -127.0.0.1:6379> latency latest -1) 1) "command" - 2) (integer) 1738651470 - 3) (integer) 254 - 4) (integer) 1005 - 5) (integer) 1259 - 6) (integer) 2 -``` - -For more information refer to the [Latency Monitoring Framework page][lm]. - -[lm]: ../topics/latency-monitor.md diff --git a/commands/latency-reset.md b/commands/latency-reset.md deleted file mode 100644 index 17327d67..00000000 --- a/commands/latency-reset.md +++ /dev/null @@ -1,34 +0,0 @@ -The `LATENCY RESET` command resets the latency spikes time series of all, or only some, events. - -When the command is called without arguments, it resets all the -events, discarding the currently logged latency spike events, and resetting -the maximum event time register. - -It is possible to reset only specific events by providing the `event` names -as arguments. - -Valid values for `event` are: -* `active-defrag-cycle` -* `aof-fsync-always` -* `aof-stat` -* `aof-rewrite-diff-write` -* `aof-rename` -* `aof-write` -* `aof-write-active-child` -* `aof-write-alone` -* `aof-write-pending-fsync` -* `command` -* `expire-cycle` -* `eviction-cycle` -* `eviction-del` -* `fast-command` -* `fork` -* `rdb-unlink-temp-file` - -For more information refer to the [Latency Monitoring Framework page][lm]. - -[lm]: ../topics/latency-monitor.md - -## Reply - -Integer: the number of event time series that were reset. diff --git a/commands/latency.md b/commands/latency.md deleted file mode 100644 index 3e1471eb..00000000 --- a/commands/latency.md +++ /dev/null @@ -1,3 +0,0 @@ -This is a container command for latency diagnostics commands. - -To see the list of available commands you can call [`LATENCY HELP`](latency-help.md). diff --git a/commands/lcs.md b/commands/lcs.md deleted file mode 100644 index 0f800b59..00000000 --- a/commands/lcs.md +++ /dev/null @@ -1,80 +0,0 @@ - -The LCS command implements the longest common subsequence algorithm. Note that this is different than the longest common string algorithm, since matching characters in the string does not need to be contiguous. - -For instance the LCS between "foo" and "fao" is "fo", since scanning the two strings from left to right, the longest common set of characters is composed of the first "f" and then the "o". - -LCS is very useful in order to evaluate how similar two strings are. Strings can represent many things. For instance if two strings are DNA sequences, the LCS will provide a measure of similarity between the two DNA sequences. If the strings represent some text edited by some user, the LCS could represent how different the new text is compared to the old one, and so forth. - -Note that this algorithm runs in `O(N*M)` time, where N is the length of the first string and M is the length of the second string. So either spin a different Valkey instance in order to run this algorithm, or make sure to run it against very small strings. - -``` -> MSET key1 ohmytext key2 mynewtext -OK -> LCS key1 key2 -"mytext" -``` - -Sometimes we need just the length of the match: - -``` -> LCS key1 key2 LEN -(integer) 6 -``` - -However what is often very useful, is to know the match position in each strings: - -``` -> LCS key1 key2 IDX -1) "matches" -2) 1) 1) 1) (integer) 4 - 2) (integer) 7 - 2) 1) (integer) 5 - 2) (integer) 8 - 2) 1) 1) (integer) 2 - 2) (integer) 3 - 2) 1) (integer) 0 - 2) (integer) 1 -3) "len" -4) (integer) 6 -``` - -Matches are produced from the last one to the first one, since this is how -the algorithm works, and it more efficient to emit things in the same order. -The above array means that the first match (second element of the array) -is between positions 2-3 of the first string and 0-1 of the second. -Then there is another match between 4-7 and 5-8. - -To restrict the list of matches to the ones of a given minimal length: - -``` -> LCS key1 key2 IDX MINMATCHLEN 4 -1) "matches" -2) 1) 1) 1) (integer) 4 - 2) (integer) 7 - 2) 1) (integer) 5 - 2) (integer) 8 -3) "len" -4) (integer) 6 -``` - -Finally to also have the match len: - -``` -> LCS key1 key2 IDX MINMATCHLEN 4 WITHMATCHLEN -1) "matches" -2) 1) 1) 1) (integer) 4 - 2) (integer) 7 - 2) 1) (integer) 5 - 2) (integer) 8 - 3) (integer) 4 -3) "len" -4) (integer) 6 -``` - -## Reply - -One of the following: - -* String: the longest common subsequence. -* Integer: the length of the longest common subsequence when _LEN_ is given. -* Map with the LCS length and all the ranges in both the strings when _IDX_ is given. diff --git a/commands/lindex.md b/commands/lindex.md deleted file mode 100644 index 9b2b8435..00000000 --- a/commands/lindex.md +++ /dev/null @@ -1,30 +0,0 @@ -Returns the element at index `index` in the list stored at `key`. -The index is zero-based, so `0` means the first element, `1` the second element -and so on. -Negative indices can be used to designate elements starting at the tail of the -list. -Here, `-1` means the last element, `-2` means the penultimate and so forth. - -When the value at `key` is not a list, an error is returned. - -## Reply - -One of the following: - -* Null: when _index_ is out of range. -* String: the requested element. - -## Examples - -``` -127.0.0.1:6379> LPUSH mylist "World" -(integer) 1 -127.0.0.1:6379> LPUSH mylist "Hello" -(integer) 2 -127.0.0.1:6379> LINDEX mylist 0 -"Hello" -127.0.0.1:6379> LINDEX mylist -1 -"World" -127.0.0.1:6379> LINDEX mylist 3 -(nil) -``` diff --git a/commands/linsert.md b/commands/linsert.md deleted file mode 100644 index 5230bfb4..00000000 --- a/commands/linsert.md +++ /dev/null @@ -1,30 +0,0 @@ -Inserts `element` in the list stored at `key` either before or after the reference -value `pivot`. - -When `key` does not exist, it is considered an empty list and no operation is -performed. - -An error is returned when `key` exists but does not hold a list value. - -## Reply - -One of the following: - -* Integer: the list length after a successful insert operation. -* Integer: `0` when the key doesn't exist. -* Integer: `-1` when the pivot wasn't found. - -## Examples - -``` -127.0.0.1:6379> RPUSH mylist "Hello" -(integer) 1 -127.0.0.1:6379> RPUSH mylist "World" -(integer) 2 -127.0.0.1:6379> LINSERT mylist BEFORE "World" "There" -(integer) 3 -127.0.0.1:6379> LRANGE mylist 0 -1 -1) "Hello" -2) "There" -3) "World" -``` diff --git a/commands/llen.md b/commands/llen.md deleted file mode 100644 index f1c98514..00000000 --- a/commands/llen.md +++ /dev/null @@ -1,18 +0,0 @@ -Returns the length of the list stored at `key`. -If `key` does not exist, it is interpreted as an empty list and `0` is returned. -An error is returned when the value stored at `key` is not a list. - -## Reply - -Integer: the length of the list. - -## Examples - -``` -127.0.0.1:6379> LPUSH mylist "World" -(integer) 1 -127.0.0.1:6379> LPUSH mylist "Hello" -(integer) 2 -127.0.0.1:6379> LLEN mylist -(integer) 2 -``` diff --git a/commands/lmove.md b/commands/lmove.md deleted file mode 100644 index 5eee9ec7..00000000 --- a/commands/lmove.md +++ /dev/null @@ -1,89 +0,0 @@ -Atomically returns and removes the first/last element (head/tail depending on -the `wherefrom` argument) of the list stored at `source`, and pushes the -element at the first/last element (head/tail depending on the `whereto` -argument) of the list stored at `destination`. - -For example: consider `source` holding the list `a,b,c`, and `destination` -holding the list `x,y,z`. -Executing `LMOVE source destination RIGHT LEFT` results in `source` holding -`a,b` and `destination` holding `c,x,y,z`. - -If `source` does not exist, the value `nil` is returned and no operation is -performed. -If `source` and `destination` are the same, the operation is equivalent to -removing the first/last element from the list and pushing it as first/last -element of the list, so it can be considered as a list rotation command (or a -no-op if `wherefrom` is the same as `whereto`). - -This command comes in place of the now deprecated [`RPOPLPUSH`](rpoplpush.md). Doing -`LMOVE RIGHT LEFT` is equivalent. - -## Reply - -String: the element being popped and pushed. - -## Examples - -``` -127.0.0.1:6379> RPUSH mylist "one" -(integer) 1 -127.0.0.1:6379> RPUSH mylist "two" -(integer) 2 -127.0.0.1:6379> RPUSH mylist "three" -(integer) 3 -127.0.0.1:6379> LMOVE mylist myotherlist RIGHT LEFT -"three" -127.0.0.1:6379> LMOVE mylist myotherlist LEFT RIGHT -"one" -127.0.0.1:6379> LRANGE mylist 0 -1 -1) "two" -127.0.0.1:6379> LRANGE myotherlist 0 -1 -1) "three" -2) "one" -``` - -## Pattern: Reliable queue - -Valkey is often used as a messaging server to implement processing of background -jobs or other kinds of messaging tasks. -A simple form of queue is often obtained pushing values into a list in the -producer side, and waiting for this values in the consumer side using [`RPOP`](rpop.md) -(using polling), or [`BRPOP`](brpop.md) if the client is better served by a blocking -operation. - -However in this context the obtained queue is not _reliable_ as messages can -be lost, for example in the case there is a network problem or if the consumer -crashes just after the message is received but it is still to process. - -`LMOVE` (or [`BLMOVE`](blmove.md) for the blocking variant) offers a way to avoid -this problem: the consumer fetches the message and at the same time pushes it -into a _processing_ list. -It will use the [`LREM`](lrem.md) command in order to remove the message from the -_processing_ list once the message has been processed. - -An additional client may monitor the _processing_ list for items that remain -there for too much time, and will push those timed out items into the queue -again if needed. - -## Pattern: Circular list - -Using `LMOVE` with the same source and destination key, a client can visit -all the elements of an N-elements list, one after the other, in O(N) without -transferring the full list from the server to the client using a single [`LRANGE`](lrange.md) -operation. - -The above pattern works even in the following conditions: - -* There are multiple clients rotating the list: they'll fetch different - elements, until all the elements of the list are visited, and the process - restarts. -* Even if other clients are actively pushing new items at the end of the list. - -The above makes it very simple to implement a system where a set of items must -be processed by N workers continuously as fast as possible. -An example is a monitoring system that must check that a set of web sites are -reachable, with the smallest delay possible, using a number of parallel workers. - -Note that this implementation of workers is trivially scalable and reliable, -because even if a message is lost the item is still in the queue and will be -processed at the next iteration. diff --git a/commands/lmpop.md b/commands/lmpop.md deleted file mode 100644 index 0a6c348d..00000000 --- a/commands/lmpop.md +++ /dev/null @@ -1,66 +0,0 @@ -Pops one or more elements from the first non-empty list key from the list of provided key names. - -`LMPOP` and [`BLMPOP`](blmpop.md) are similar to the following, more limited, commands: - -- [`LPOP`](lpop.md) or [`RPOP`](rpop.md) which take only one key, and can return multiple elements. -- [`BLPOP`](blpop.md) or [`BRPOP`](brpop.md) which take multiple keys, but return only one element from just one key. - -See [`BLMPOP`](blmpop.md) for the blocking variant of this command. - -Elements are popped from either the left or right of the first non-empty list based on the passed argument. -The number of returned elements is limited to the lower between the non-empty list's length, and the count argument (which defaults to 1). - -## Reply - -One of the following: - -* Null: if no element could be popped. -* Two-element array with the first element being the name of the key from which elements were popped and the second element being an array of elements. - -## Examples - -``` -127.0.0.1:6379> LMPOP 2 non1 non2 LEFT COUNT 10 -(nil) -127.0.0.1:6379> LPUSH mylist "one" "two" "three" "four" "five" -(integer) 5 -127.0.0.1:6379> LMPOP 1 mylist LEFT -1) "mylist" -2) 1) "five" -127.0.0.1:6379> LRANGE mylist 0 -1 -1) "four" -2) "three" -3) "two" -4) "one" -127.0.0.1:6379> LMPOP 1 mylist RIGHT COUNT 10 -1) "mylist" -2) 1) "one" - 2) "two" - 3) "three" - 4) "four" -127.0.0.1:6379> LPUSH mylist "one" "two" "three" "four" "five" -(integer) 5 -127.0.0.1:6379> LPUSH mylist2 "a" "b" "c" "d" "e" -(integer) 5 -127.0.0.1:6379> LMPOP 2 mylist mylist2 right count 3 -1) "mylist" -2) 1) "one" - 2) "two" - 3) "three" -127.0.0.1:6379> LRANGE mylist 0 -1 -1) "five" -2) "four" -127.0.0.1:6379> LMPOP 2 mylist mylist2 right count 5 -1) "mylist" -2) 1) "four" - 2) "five" -127.0.0.1:6379> LMPOP 2 mylist mylist2 right count 10 -1) "mylist2" -2) 1) "a" - 2) "b" - 3) "c" - 4) "d" - 5) "e" -127.0.0.1:6379> EXISTS mylist mylist2 -(integer) 0 -``` diff --git a/commands/lolwut.md b/commands/lolwut.md deleted file mode 100644 index 83725e56..00000000 --- a/commands/lolwut.md +++ /dev/null @@ -1,26 +0,0 @@ -The LOLWUT command displays the Valkey version: however as a side effect of doing so, -it also creates a piece of generative computer art that is different with each version of Valkey. - -By default the `LOLWUT` command will display the piece corresponding to the current Valkey version, -however it is possible to display a specific version using the following form: - - LOLWUT VERSION 7 ... other optional arguments ... - -Of course the "7" above is an example. Each LOLWUT version takes a different -set of arguments in order to change the output. The user is encouraged to -play with it to discover how the output changes adding more numerical -arguments. - -LOLWUT wants to be a reminder that there is more in programming than just -putting some code together in order to create something useful. Every -LOLWUT version should have the following properties: - -1. It should display some computer art. There are no limits as long as the output works well in a normal terminal display. However the output should not be limited to graphics (like LOLWUT 7 and 8 actually do), but can be generative poetry and other non graphical things. -2. LOLWUT output should be completely useless. Displaying some useful Valkey internal metrics does not count as a valid LOLWUT. -3. LOLWUT output should be fast to generate so that the command can be called in production instances without issues. It should remain fast even when the user experiments with odd parameters. -4. LOLWUT implementations should be safe and carefully checked for security, and resist to untrusted inputs if they take arguments. -5. LOLWUT must always display the Valkey version at the end. - -## Reply - -Verbatim string containing generative computer art and the Valkey version. diff --git a/commands/lpop.md b/commands/lpop.md deleted file mode 100644 index 69a22757..00000000 --- a/commands/lpop.md +++ /dev/null @@ -1,27 +0,0 @@ -By default, the command pops a single element from the beginning of the list. -When provided with the optional `count` argument, the reply will consist of up -to `count` elements, depending on the list's length. -Deletes the list if the last element was popped. - -## Reply - -One of the following: - -* Null: if the key does not exist. -* String: when called without the _count_ argument, the value of the first element. -* Array: when called with the _count_ argument, a list of popped elements. - -## Examples - -``` -127.0.0.1:6379> RPUSH mylist "one" "two" "three" "four" "five" -(integer) 5 -127.0.0.1:6379> LPOP mylist -"one" -127.0.0.1:6379> LPOP mylist 2 -1) "two" -2) "three" -127.0.0.1:6379> LRANGE mylist 0 -1 -1) "four" -2) "five" -``` diff --git a/commands/lpos.md b/commands/lpos.md deleted file mode 100644 index fbcd516a..00000000 --- a/commands/lpos.md +++ /dev/null @@ -1,79 +0,0 @@ -The command returns the index of matching elements inside a List. -By default, when no options are given, it will scan the list from head to tail, -looking for the first match of "element". If the element is found, its index (the zero-based position in the list) is returned. Otherwise, if no match is found, `nil` is returned. - -``` -> RPUSH mylist a b c 1 2 3 c c -> LPOS mylist c -2 -``` - -The optional arguments and options can modify the command's behavior. -The `RANK` option specifies the "rank" of the first element to return, in case there are multiple matches. A rank of 1 means to return the first match, 2 to return the second match, and so forth. - -For instance, in the above example the element "c" is present multiple times, if I want the index of the second match, I'll write: - -``` -> LPOS mylist c RANK 2 -6 -``` - -That is, the second occurrence of "c" is at position 6. -A negative "rank" as the `RANK` argument tells `LPOS` to invert the search direction, starting from the tail to the head. - -So, we want to say, give me the first element starting from the tail of the list: - -``` -> LPOS mylist c RANK -1 -7 -``` - -Note that the indexes are still reported in the "natural" way, that is, considering the first element starting from the head of the list at index 0, the next element at index 1, and so forth. This basically means that the returned indexes are stable whatever the rank is positive or negative. - -Sometimes we want to return not just the Nth matching element, but the position of all the first N matching elements. This can be achieved using the `COUNT` option. - -``` -> LPOS mylist c COUNT 2 -[2,6] -``` - -We can combine `COUNT` and `RANK`, so that `COUNT` will try to return up to the specified number of matches, but starting from the Nth match, as specified by the `RANK` option. - -``` -> LPOS mylist c RANK -1 COUNT 2 -[7,6] -``` - -When `COUNT` is used, it is possible to specify 0 as the number of matches, as a way to tell the command we want all the matches found returned as an array of indexes. This is better than giving a very large `COUNT` option because it is more general. - -``` -> LPOS mylist c COUNT 0 -[2,6,7] -``` - -When `COUNT` is used and no match is found, an empty array is returned. However when `COUNT` is not used and there are no matches, the command returns `nil`. - -Finally, the `MAXLEN` option tells the command to compare the provided element only with a given maximum number of list items. So for instance specifying `MAXLEN 1000` will make sure that the command performs only 1000 comparisons, effectively running the algorithm on a subset of the list (the first part or the last part depending on the fact we use a positive or negative rank). This is useful to limit the maximum complexity of the command. It is also useful when we expect the match to be found very early, but want to be sure that in case this is not true, the command does not take too much time to run. - -When `MAXLEN` is used, it is possible to specify 0 as the maximum number of comparisons, as a way to tell the command we want unlimited comparisons. This is better than giving a very large `MAXLEN` option because it is more general. - -## Reply - -Any of the following: - -* Null: if there is no matching element. -* Integer representing the matching element. -* Array: If the COUNT option is given, an array of integers representing the matching elements (or an empty array if there are no matches). - -## Examples - -``` -127.0.0.1:6379> RPUSH mylist a b c d 1 2 3 4 3 3 3 -(integer) 11 -127.0.0.1:6379> LPOS mylist 3 -(integer) 6 -127.0.0.1:6379> LPOS mylist 3 COUNT 0 RANK 2 -1) (integer) 8 -2) (integer) 9 -3) (integer) 10 -``` diff --git a/commands/lpush.md b/commands/lpush.md deleted file mode 100644 index fbda418e..00000000 --- a/commands/lpush.md +++ /dev/null @@ -1,27 +0,0 @@ -Insert all the specified values at the head of the list stored at `key`. -If `key` does not exist, it is created as empty list before performing the push -operations. -When `key` holds a value that is not a list, an error is returned. - -It is possible to push multiple elements using a single command call just -specifying multiple arguments at the end of the command. -Elements are inserted one after the other to the head of the list, from the -leftmost element to the rightmost element. -So for instance the command `LPUSH mylist a b c` will result into a list -containing `c` as first element, `b` as second element and `a` as third element. - -## Reply - -Integer: the length of the list after the push operation. - -## Examples - -``` -127.0.0.1:6379> LPUSH mylist "world" -(integer) 1 -127.0.0.1:6379> LPUSH mylist "hello" -(integer) 2 -127.0.0.1:6379> LRANGE mylist 0 -1 -1) "hello" -2) "world" -``` diff --git a/commands/lpushx.md b/commands/lpushx.md deleted file mode 100644 index 521b2552..00000000 --- a/commands/lpushx.md +++ /dev/null @@ -1,24 +0,0 @@ -Inserts specified values at the head of the list stored at `key`, only if `key` -already exists and holds a list. -In contrary to [`LPUSH`](lpush.md), no operation will be performed when `key` does not yet -exist. - -## Reply - -Integer: the length of the list after the push operation. - -## Examples - -``` -127.0.0.1:6379> LPUSH mylist "World" -(integer) 1 -127.0.0.1:6379> LPUSHX mylist "Hello" -(integer) 2 -127.0.0.1:6379> LPUSHX myotherlist "Hello" -(integer) 0 -127.0.0.1:6379> LRANGE mylist 0 -1 -1) "Hello" -2) "World" -127.0.0.1:6379> LRANGE myotherlist 0 -1 -(empty array) -``` diff --git a/commands/lrange.md b/commands/lrange.md deleted file mode 100644 index 74999cf5..00000000 --- a/commands/lrange.md +++ /dev/null @@ -1,51 +0,0 @@ -Returns the specified elements of the list stored at `key`. -The offsets `start` and `stop` are zero-based indexes, with `0` being the first -element of the list (the head of the list), `1` being the next element and so -on. - -These offsets can also be negative numbers indicating offsets starting at the -end of the list. -For example, `-1` is the last element of the list, `-2` the penultimate, and so -on. - -## Consistency with range functions in various programming languages - -Note that if you have a list of numbers from 0 to 100, `LRANGE list 0 10` will -return 11 elements, that is, the rightmost item is included. -This **may or may not** be consistent with behavior of range-related functions -in your programming language of choice (think Ruby's `Range.new`, `Array#slice` -or Python's `range()` function). - -## Out-of-range indexes - -Out of range indexes will not produce an error. -If `start` is larger than the end of the list, an empty list is returned. -If `stop` is larger than the actual end of the list, Valkey will treat it like -the last element of the list. - -## Reply - -Array of elements in the specified range, or an empty array if the key doesn't exist. - -## Examples - -``` -127.0.0.1:6379> RPUSH mylist "one" -(integer) 1 -127.0.0.1:6379> RPUSH mylist "two" -(integer) 2 -127.0.0.1:6379> RPUSH mylist "three" -(integer) 3 -127.0.0.1:6379> LRANGE mylist 0 0 -1) "one" -127.0.0.1:6379> LRANGE mylist -3 2 -1) "one" -2) "two" -3) "three" -127.0.0.1:6379> LRANGE mylist -100 100 -1) "one" -2) "two" -3) "three" -127.0.0.1:6379> LRANGE mylist 5 10 -(empty array) -``` diff --git a/commands/lrem.md b/commands/lrem.md deleted file mode 100644 index 67b85c28..00000000 --- a/commands/lrem.md +++ /dev/null @@ -1,35 +0,0 @@ -Removes the first `count` occurrences of elements equal to `element` from the list -stored at `key`. -The `count` argument influences the operation in the following ways: - -* `count > 0`: Remove elements equal to `element` moving from head to tail. -* `count < 0`: Remove elements equal to `element` moving from tail to head. -* `count = 0`: Remove all elements equal to `element`. - -For example, `LREM list -2 "hello"` will remove the last two occurrences of -`"hello"` in the list stored at `list`. - -Note that non-existing keys are treated like empty lists, so when `key` does not -exist, the command will always return `0`. - -## Reply - -Integer: the number of removed elements. - -## Examples - -``` -127.0.0.1:6379> RPUSH mylist "hello" -(integer) 1 -127.0.0.1:6379> RPUSH mylist "hello" -(integer) 2 -127.0.0.1:6379> RPUSH mylist "foo" -(integer) 3 -127.0.0.1:6379> RPUSH mylist "hello" -(integer) 4 -127.0.0.1:6379> LREM mylist -2 "hello" -(integer) 2 -127.0.0.1:6379> LRANGE mylist 0 -1 -1) "hello" -2) "foo" -``` diff --git a/commands/lset.md b/commands/lset.md deleted file mode 100644 index a2d52a89..00000000 --- a/commands/lset.md +++ /dev/null @@ -1,27 +0,0 @@ -Sets the list element at `index` to `element`. -For more information on the `index` argument, see [`LINDEX`](lindex.md). - -An error is returned for out of range indexes. - -## Reply - -`OK`. - -## Examples - -``` -127.0.0.1:6379> RPUSH mylist "one" -(integer) 1 -127.0.0.1:6379> RPUSH mylist "two" -(integer) 2 -127.0.0.1:6379> RPUSH mylist "three" -(integer) 3 -127.0.0.1:6379> LSET mylist 0 "four" -OK -127.0.0.1:6379> LSET mylist -2 "five" -OK -127.0.0.1:6379> LRANGE mylist 0 -1 -1) "four" -2) "five" -3) "three" -``` diff --git a/commands/ltrim.md b/commands/ltrim.md deleted file mode 100644 index e40e4565..00000000 --- a/commands/ltrim.md +++ /dev/null @@ -1,52 +0,0 @@ -Trim an existing list so that it will contain only the specified range of -elements specified. -Both `start` and `stop` are zero-based indexes, where `0` is the first element -of the list (the head), `1` the next element and so on. - -For example: `LTRIM foobar 0 2` will modify the list stored at `foobar` so that -only the first three elements of the list will remain. - -`start` and `end` can also be negative numbers indicating offsets from the end -of the list, where `-1` is the last element of the list, `-2` the penultimate -element and so on. - -Out of range indexes will not produce an error: if `start` is larger than the -end of the list, or `start > end`, the result will be an empty list (which -causes `key` to be removed). -If `end` is larger than the end of the list, Valkey will treat it like the last -element of the list. - -A common use of `LTRIM` is together with [`LPUSH`](lpush.md) / [`RPUSH`](rpush.md). -For example: - -``` -LPUSH mylist someelement -LTRIM mylist 0 99 -``` - -This pair of commands will push a new element on the list, while making sure -that the list will not grow larger than 100 elements. -This is very useful when using Valkey to store logs for example. -It is important to note that when used in this way `LTRIM` is an O(1) operation -because in the average case just one element is removed from the tail of the -list. - -## Reply - -`OK`. - -## Examples - -``` -127.0.0.1:6379> RPUSH mylist "one" -(integer) 1 -127.0.0.1:6379> RPUSH mylist "two" -(integer) 2 -127.0.0.1:6379> RPUSH mylist "three" -(integer) 3 -127.0.0.1:6379> LTRIM mylist 1 -1 -OK -127.0.0.1:6379> LRANGE mylist 0 -1 -1) "two" -2) "three" -``` diff --git a/commands/memory-doctor.md b/commands/memory-doctor.md deleted file mode 100644 index ee575a19..00000000 --- a/commands/memory-doctor.md +++ /dev/null @@ -1,6 +0,0 @@ -The `MEMORY DOCTOR` command reports about different memory-related issues that -the Valkey server experiences, and advises about possible remedies. - -## Reply - -Verbatim string: a memory problems report. diff --git a/commands/memory-help.md b/commands/memory-help.md deleted file mode 100644 index 53a07236..00000000 --- a/commands/memory-help.md +++ /dev/null @@ -1,6 +0,0 @@ -The `MEMORY HELP` command returns a helpful text describing the different -subcommands. - -## Reply - -Array of sub-commands and their descriptions. diff --git a/commands/memory-malloc-stats.md b/commands/memory-malloc-stats.md deleted file mode 100644 index f790113b..00000000 --- a/commands/memory-malloc-stats.md +++ /dev/null @@ -1,9 +0,0 @@ -The `MEMORY MALLOC-STATS` command provides an internal statistics report from -the memory allocator. - -This command is currently implemented only when using **jemalloc** as an -allocator, and evaluates to a benign NOOP for all others. - -## Reply - -Verbatim string: the memory allocator's internal statistics report. diff --git a/commands/memory-purge.md b/commands/memory-purge.md deleted file mode 100644 index e8b48c9b..00000000 --- a/commands/memory-purge.md +++ /dev/null @@ -1,9 +0,0 @@ -The `MEMORY PURGE` command attempts to purge dirty pages so these can be -reclaimed by the allocator. - -This command is currently implemented only when using **jemalloc** as an -allocator, and evaluates to a benign NOOP for all others. - -## Reply - -`OK`. diff --git a/commands/memory-stats.md b/commands/memory-stats.md deleted file mode 100644 index d047ac90..00000000 --- a/commands/memory-stats.md +++ /dev/null @@ -1,61 +0,0 @@ -The `MEMORY STATS` command returns an @array-reply about the memory usage of the -server. - -The information about memory usage is provided as metrics and their respective -values. The following metrics are reported: - -* `peak.allocated`: Peak memory consumed by Valkey in bytes (see `INFO`'s - `used_memory_peak`) -* `total.allocated`: Total number of bytes allocated by Valkey using its - allocator (see [`INFO`](info.md)'s `used_memory`) -* `startup.allocated`: Initial amount of memory consumed by Valkey at startup - in bytes (see `INFO`'s `used_memory_startup`) -* `replication.backlog`: Memory usage by replication backlog (see `INFO`'s `mem_replication_backlog`) -* `replicas.repl.buffer`: Memory usage by replicas replication buffer (see `INFO`'s `mem_replicas_repl_buffer`). Added in Valkey 9.1. -* `clients.slaves`: The total size in bytes of all replicas overheads (output - and query buffers, connection contexts) -* `clients.normal`: The total size in bytes of all clients overheads (output - and query buffers, connection contexts) -* `cluster.links`: Memory usage by cluster links (see `INFO`'s `mem_cluster_links`). -* `aof.buffer`: The summed size in bytes of AOF related buffers. -* `lua.caches`: the summed size in bytes of the overheads of the Lua scripts' - caches -* `functions.caches`: the summed size in bytes of the overheads of the Function scripts' - caches -* `dbXXX`: For each of the server's databases, the overheads of the main and - expiry dictionaries (`overhead.hashtable.main` and - `overhead.hashtable.expires`, respectively) are reported in bytes -* `overhead.db.hashtable.lut`: Total overhead of dictionary buckets in databases (Added in Valkey 8.0) -* `overhead.db.hashtable.rehashing`: Temporary memory overhead of database dictionaries currently being rehashed (Added in Valkey 8.0) -* `overhead.total`: The sum of all overheads, i.e. `startup.allocated`, - `replication.backlog`, `clients.slaves`, `clients.normal`, `aof.buffer` and - those of the internal data structures that are used in managing the - Valkey keyspace (see `INFO`'s `used_memory_overhead`) -* `db.dict.rehashing.count`: Number of DB dictionaries currently being rehashed (Added in Valkey 8.0) -* `keys.count`: The total number of keys stored across all databases in the - server -* `keys.bytes-per-key`: The ratio between `dataset.bytes` and `keys.count` -* `dataset.bytes`: The size in bytes of the dataset, i.e. `overhead.total` - subtracted from `total.allocated` (see `INFO`'s `used_memory_dataset`) -* `dataset.percentage`: The percentage of `dataset.bytes` out of the total - memory usage -* `peak.percentage`: The percentage of `total.allocated` out of - `peak.allocated` -* `allocator.allocated`: See `INFO`'s `allocator_allocated` -* `allocator.active`: See `INFO`'s `allocator_active` -* `allocator.resident`: See `INFO`'s `allocator_resident` -* `allocator.muzzy`: See `INFO`'s `allocator_muzzy` -* `allocator-fragmentation.ratio`: See `INFO`'s `allocator_frag_ratio` -* `allocator-fragmentation.bytes`: See `INFO`'s `allocator_frag_bytes` -* `allocator-rss.ratio`: See `INFO`'s `allocator_rss_ratio` -* `allocator-rss.bytes`: See `INFO`'s `allocator_rss_bytes` -* `rss-overhead.ratio`: See `INFO`'s `rss_overhead_ratio` -* `rss-overhead.bytes`: See `INFO`'s `rss_overhead_bytes` -* `fragmentation`: See `INFO`'s `mem_fragmentation_ratio` -* `fragmentation.bytes`: See `INFO`'s `mem_fragmentation_bytes` - -**A note about the word slave used in this man page**: If not for backward compatibility, the Valkey project no longer uses the words "master" and "slave". Unfortunately in the given commands these words are part of the protocol, so we'll be able to remove such occurrences only when this API will be naturally deprecated. - -## Reply - -Map: memory usage metrics and their values. diff --git a/commands/memory-usage.md b/commands/memory-usage.md deleted file mode 100644 index 4473507e..00000000 --- a/commands/memory-usage.md +++ /dev/null @@ -1,46 +0,0 @@ -The `MEMORY USAGE` command reports the number of bytes that a key and its value -require to be stored in RAM. - -The reported usage is the total of memory allocations for data and -administrative overheads that a key and its value require. - -For nested data types, the optional `SAMPLES` option can be provided, where -`count` is the number of sampled nested values. The samples are averaged to estimate the total size. -By default, this option is set to `5`. To sample the all of the nested values, use `SAMPLES 0`. - -## Reply - -One of the following: - -* Integer: the memory usage in bytes. -* Null: if the key does not exist. - -## Examples - -With Valkey v7.2.4 64-bit and **jemalloc**, the empty string measures as follows: - -``` -> SET "" "" -OK -> MEMORY USAGE "" -(integer) 56 -``` - -These bytes are pure overhead at the moment as no actual data is stored, and are -used for maintaining the internal data structures of the server (include internal allocator fragmentation). Longer keys and -values show asymptotically linear usage. - -``` -> SET foo bar -OK -> MEMORY USAGE foo -(integer) 56 -> SET foo2 mybar -OK -> MEMORY USAGE foo2 -(integer) 64 -> SET foo3 0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789 -OK -> MEMORY USAGE foo3 -(integer) 160 -``` diff --git a/commands/memory.md b/commands/memory.md deleted file mode 100644 index aa8b9bff..00000000 --- a/commands/memory.md +++ /dev/null @@ -1,3 +0,0 @@ -This is a container command for memory introspection and management commands. - -To see the list of available commands you can call [`MEMORY HELP`](memory-help.md). diff --git a/commands/mget.md b/commands/mget.md deleted file mode 100644 index de6042eb..00000000 --- a/commands/mget.md +++ /dev/null @@ -1,21 +0,0 @@ -Returns the values of all specified keys. -For every key that does not hold a string value or does not exist, the special -value `nil` is returned. -Because of this, the operation never fails. - -## Reply - -Array of values at the specified keys. - -## Examples - -``` -127.0.0.1:6379> SET key1 "Hello" -OK -127.0.0.1:6379> SET key2 "World" -OK -127.0.0.1:6379> MGET key1 key2 nonexisting -1) "Hello" -2) "World" -3) (nil) -``` diff --git a/commands/migrate.md b/commands/migrate.md deleted file mode 100644 index caad1115..00000000 --- a/commands/migrate.md +++ /dev/null @@ -1,78 +0,0 @@ -Atomically transfer a key from a source Valkey instance to a destination Valkey -instance. -On success the key is deleted from the original instance and is guaranteed to -exist in the target instance. - -The command is atomic and blocks the two instances for the time required to -transfer the key, at any given time the key will appear to exist in a given -instance or in the other instance, unless a timeout error occurs. In 3.2 and -above, multiple keys can be pipelined in a single call to `MIGRATE` by passing -the empty string ("") as key and adding the `KEYS` clause. - -The command internally uses [`DUMP`](dump.md) to generate the serialized version of the key -value, and [`RESTORE`](restore.md) in order to synthesize the key in the target instance. -The source instance acts as a client for the target instance. -If the target instance returns OK to the `RESTORE` command, the source instance -deletes the key using [`DEL`](del.md). - -The timeout specifies the maximum idle time in any moment of the communication -with the destination instance in milliseconds. -This means that the operation does not need to be completed within the specified -amount of milliseconds, but that the transfer should make progress without -blocking for more than the specified amount of milliseconds. - -`MIGRATE` operates on the database currently selected in the connection. -Before calling `MIGRATE`, you can switch databases using [`SELECT `](select.md), -and the command will migrate keys from that database. - -`MIGRATE` needs to perform I/O operations and to honor the specified timeout. -When there is an I/O error during the transfer or if the timeout is reached the -operation is aborted and the special error - `IOERR` returned. -When this happens the following two cases are possible: - -* The key may be on both the instances. -* The key may be only in the source instance. - -It is not possible for the key to get lost in the event of a timeout, but the -client calling `MIGRATE`, in the event of a timeout error, should check if the -key is _also_ present in the target instance and act accordingly. - -When any other error is returned (starting with `ERR`) `MIGRATE` guarantees that -the key is still only present in the originating instance (unless a key with the -same name was also _already_ present on the target instance). - -If there are no keys to migrate in the source instance `NOKEY` is returned. -Because missing keys are possible in normal conditions, from expiry for example, -`NOKEY` isn't an error. - -## Migrating multiple keys with a single command call - -`MIGRATE` supports a bulk-migration mode that -uses pipelining in order to migrate multiple keys between instances without -incurring in the round trip time latency and other overheads that there are -when moving each key with a single `MIGRATE` call. - -In order to enable this form, the `KEYS` option is used, and the normal *key* -argument is set to an empty string. The actual key names will be provided -after the `KEYS` argument itself, like in the following example: - - MIGRATE 192.168.1.34 6379 "" 0 5000 KEYS key1 key2 key3 - -When this form is used the `NOKEY` status code is only returned when none -of the keys is present in the instance, otherwise the command is executed, even if -just a single key exists. - -## Options - -* `COPY` -- Do not remove the key from the local instance. -* `REPLACE` -- Replace existing key on the remote instance. -* `KEYS` -- If the key argument is an empty string, the command will instead migrate all the keys that follow the `KEYS` option (see the above section for more info). -* `AUTH` -- Authenticate with the given password to the remote instance. -* `AUTH2` -- Authenticate with the given username and password pair. - -## Reply - -One of the following: - -* `OK` on success. -* `NOKEY` when no keys were found in the source instance. diff --git a/commands/module-help.md b/commands/module-help.md deleted file mode 100644 index 0ca2f3c0..00000000 --- a/commands/module-help.md +++ /dev/null @@ -1,5 +0,0 @@ -The `MODULE HELP` command returns a helpful text describing the different subcommands. - -## Reply - -Array of sub-commands and their descriptions. diff --git a/commands/module-list.md b/commands/module-list.md deleted file mode 100644 index a792208c..00000000 --- a/commands/module-list.md +++ /dev/null @@ -1,8 +0,0 @@ -Returns information about the modules loaded to the server. - -## Reply - -Array of loaded modules. Each element in the list represents a represents a module, and is a map of property names and their values. The following properties is reported for each loaded module: - -* name: the name of the module. -* ver: the version of the module. diff --git a/commands/module-load.md b/commands/module-load.md deleted file mode 100644 index 069c5ff9..00000000 --- a/commands/module-load.md +++ /dev/null @@ -1,13 +0,0 @@ -Loads a module from a dynamic library at runtime. - -This command loads and initializes the Valkey module from the dynamic library -specified by the `path` argument. The `path` should be the absolute path of the -library, including the full filename. Any additional arguments are passed -unmodified to the module. - -**Note**: modules can also be loaded at server startup with `loadmodule` -configuration directive in `valkey.conf`. - -## Reply - -`OK` if the module was loaded. diff --git a/commands/module-loadex.md b/commands/module-loadex.md deleted file mode 100644 index fe2a9d50..00000000 --- a/commands/module-loadex.md +++ /dev/null @@ -1,15 +0,0 @@ -Loads a module from a dynamic library at runtime with configuration directives. - -This is an extended version of the `MODULE LOAD` command. - -It loads and initializes the Valkey module from the dynamic library specified by the `path` argument. The `path` should be the absolute path of the library, including the full filename. - -You can use the optional `CONFIG` argument to provide the module with configuration directives. -Any additional arguments that follow the `ARGS` keyword are passed unmodified to the module. - -**Note**: modules can also be loaded at server startup with `loadmodule` -configuration directive in `valkey.conf`. - -## Reply - -`OK` if the module was loaded. diff --git a/commands/module-unload.md b/commands/module-unload.md deleted file mode 100644 index cdea5178..00000000 --- a/commands/module-unload.md +++ /dev/null @@ -1,13 +0,0 @@ -Unloads a module. - -This command unloads the module specified by `name`. Note that the module's name -is reported by the [`MODULE LIST`](module-list.md) command, and may differ from the dynamic -library's filename. - -Known limitations: - -* Modules that register custom data types can not be unloaded. - -## Reply - -`OK` if the module was unloaded. diff --git a/commands/module.md b/commands/module.md deleted file mode 100644 index 4965966d..00000000 --- a/commands/module.md +++ /dev/null @@ -1,3 +0,0 @@ -This is a container command for module management commands. - -To see the list of available commands you can call [`MODULE HELP`](module-help.md). diff --git a/commands/monitor.md b/commands/monitor.md deleted file mode 100644 index 5cd1c296..00000000 --- a/commands/monitor.md +++ /dev/null @@ -1,87 +0,0 @@ -`MONITOR` is a debugging command that streams back every command processed by -the Valkey server. -It can help in understanding what is happening to the database. -This command can both be used via `valkey-cli` and via `telnet`. - -The ability to see all the requests processed by the server is useful in order -to spot bugs in an application both when using Valkey as a database and as a -distributed caching system. - -``` -$ valkey-cli monitor -1339518083.107412 [0 127.0.0.1:60866] "keys" "*" -1339518087.877697 [0 127.0.0.1:60866] "dbsize" -1339518090.420270 [0 127.0.0.1:60866] "set" "x" "6" -1339518096.506257 [0 127.0.0.1:60866] "get" "x" -1339518099.363765 [0 127.0.0.1:60866] "eval" "return server.call('set','x','7')" "0" -1339518100.363799 [0 lua] "set" "x" "7" -1339518100.544926 [0 127.0.0.1:60866] "del" "x" -``` - -Use `SIGINT` (Ctrl-C) to stop a `MONITOR` stream running via `valkey-cli`. - -``` -$ telnet localhost 6379 -Trying 127.0.0.1... -Connected to localhost. -Escape character is '^]'. -MONITOR -+OK -+1339518083.107412 [0 127.0.0.1:60866] "keys" "*" -+1339518087.877697 [0 127.0.0.1:60866] "dbsize" -+1339518090.420270 [0 127.0.0.1:60866] "set" "x" "6" -+1339518096.506257 [0 127.0.0.1:60866] "get" "x" -+1339518099.363765 [0 127.0.0.1:60866] "del" "x" -+1339518100.544926 [0 127.0.0.1:60866] "get" "x" -QUIT -+OK -Connection closed by foreign host. -``` - -Manually issue the [`QUIT`](quit.md) or [`RESET`](reset.md) commands to stop a `MONITOR` stream running -via `telnet`. - -## Commands not logged by MONITOR - -Because of security concerns, no administrative commands are logged -by `MONITOR`'s output, and credentials passed to [`AUTH`](auth.md) and [`HELLO`](hello.md) are shown as `"(redacted)"`. - -## Cost of running MONITOR - -Because `MONITOR` streams back **all** commands, its use comes at a cost. -The following (totally unscientific) benchmark numbers illustrate what the cost -of running `MONITOR` can be. - -Benchmark result **without** `MONITOR` running: - -``` -$ src/valkey-benchmark -c 10 -n 100000 -q -PING_INLINE: 101936.80 requests per second -PING_BULK: 102880.66 requests per second -SET: 95419.85 requests per second -GET: 104275.29 requests per second -INCR: 93283.58 requests per second -``` - -Benchmark result **with** `MONITOR` running (`valkey-cli monitor > /dev/null`): - -``` -$ src/valkey-benchmark -c 10 -n 100000 -q -PING_INLINE: 58479.53 requests per second -PING_BULK: 59136.61 requests per second -SET: 41823.50 requests per second -GET: 45330.91 requests per second -INCR: 41771.09 requests per second -``` - -In this particular case, running a single `MONITOR` client can reduce the -throughput by more than 50%. -Running more `MONITOR` clients will reduce throughput even more. - -Note that, -* [`RESET`](reset.md) can be called to exit monitor mode. -* `AUTH`, [`HELLO`](hello.md), [`EVAL`](eval.md), [`EVAL_RO`](eval_ro.md), [`EVALSHA`](evalsha.md) and [`EVALSHA_RO`](evalsha_ro.md) are included in the command's output, with the credentials of `AUTH` and `HELLO` redacted. - -## Reply - -**Non-standard return value**. Dumps the received commands in an infinite flow. diff --git a/commands/move.md b/commands/move.md deleted file mode 100644 index ec95c2b8..00000000 --- a/commands/move.md +++ /dev/null @@ -1,37 +0,0 @@ -Move `key` from the currently selected database (see [`SELECT`](select.md)) to the specified -destination database. -When `key` does not exist in the source database, it does nothing. -When `key` already exists in the destination database, it does nothing unless -the `REPLACE` option is given, in which case the existing key is overwritten. -Without `REPLACE`, it is possible to use `MOVE` as a locking primitive. - -The caller must have access to the current and the destination databases. See -[database permissions](../topics/acl.md#database-permissions). - -## Reply - -One of the following: - -* Integer: `1` if _key_ was moved. -* Integer: `0` if _key_ does not exist in the source database, or it already exists in the destination database and `REPLACE` was not given. - -## Examples - -``` -127.0.0.1:6379> SET mykey "db0" -OK -127.0.0.1:6379> SELECT 1 -OK -127.0.0.1:6379[1]> SET mykey "db1" -OK -127.0.0.1:6379[1]> SELECT 0 -OK -127.0.0.1:6379> MOVE mykey 1 -(integer) 0 -127.0.0.1:6379> MOVE mykey 1 REPLACE -(integer) 1 -127.0.0.1:6379> SELECT 1 -OK -127.0.0.1:6379[1]> GET mykey -"db0" -``` diff --git a/commands/mset.md b/commands/mset.md deleted file mode 100644 index 45433f1e..00000000 --- a/commands/mset.md +++ /dev/null @@ -1,22 +0,0 @@ -Sets the given keys to their respective values. -`MSET` replaces existing values with new values, just as regular `SET`. -See `MSETNX` if you don't want to overwrite existing values. - -`MSET` is atomic, so all given keys are set at once. -It is not possible for clients to see that some of the keys were updated while -others are unchanged. - -## Reply - -`OK`, since `MSET` can't fail. - -## Examples - -``` -127.0.0.1:6379> MSET key1 "Hello" key2 "World" -OK -127.0.0.1:6379> GET key1 -"Hello" -127.0.0.1:6379> GET key2 -"World" -``` diff --git a/commands/msetex.md b/commands/msetex.md deleted file mode 100644 index 7d70565e..00000000 --- a/commands/msetex.md +++ /dev/null @@ -1,70 +0,0 @@ -`MSETEX` is a combination of `MSET` and `EXPIRE`. -It allows setting multiple key-value pairs while also assigning a shared expiration time to all the keys atomically. - -This command is designed to improve efficiency by avoiding multiple network round-trips that would be required when using separate `MSET` and `EXPIRE` commands. - -`MSETEX` is atomic, so all given keys are set at once with the specified expiration. -It is not possible for clients to see that some of the keys were updated while others are unchanged. - -## Options - -The `MSETEX` command supports a set of options similar to the `SET` command: - -* `EX` *seconds* -- Set the specified expire time, in seconds (a positive integer). -* `PX` *milliseconds* -- Set the specified expire time, in milliseconds (a positive integer). -* `EXAT` *timestamp-seconds* -- Set the specified Unix time at which the keys will expire, in seconds (a positive integer). -* `PXAT` *timestamp-milliseconds* -- Set the specified Unix time at which the keys will expire, in milliseconds (a positive integer). -* `NX` -- Only set the keys if **all** of them do not already exist. -* `XX` -- Only set the keys if **all** of them already exist. -* `KEEPTTL` -- Retain the time to live associated with the keys. - -Note: The `EX`, `PX`, `EXAT`, `PXAT`, `KEEPTTL` options are mutually exclusive. -The `NX` and `XX` options are also mutually exclusive. - -## Reply - -One of the following: - -* Integer: `0` if no key was set (at least one key already existed when `NX` was used, or at least one key didn't exist when `XX` was used). -* Integer: `1` if all the keys were set. - -## Examples - -``` -127.0.0.1:6379> MSETEX 2 key1 "Hello" key2 "World" EX 10 -(integer) 1 -127.0.0.1:6379> GET key1 -"Hello" -127.0.0.1:6379> TTL key1 -(integer) 10 -127.0.0.1:6379> GET key2 -"World" -127.0.0.1:6379> TTL key2 -(integer) 10 -``` - -Using the `NX` option (only set if all keys don't exist): - -``` -127.0.0.1:6379> MSETEX 2 key1 "Hello" key2 "World" NX EX 10 -(integer) 1 -127.0.0.1:6379> MSETEX 2 key1 "New" key3 "Value" NX EX 10 -(integer) 0 -127.0.0.1:6379> GET key1 -"Hello" -127.0.0.1:6379> GET key3 -(nil) -``` - -Using the `XX` option (only set if all keys exist): - -``` -127.0.0.1:6379> SET existing "value" -OK -127.0.0.1:6379> MSETEX 2 existing "updated" newkey "value" XX EX 10 -(integer) 0 -127.0.0.1:6379> MSETEX 1 existing "updated" XX EX 10 -(integer) 1 -127.0.0.1:6379> GET existing -"updated" -``` diff --git a/commands/msetnx.md b/commands/msetnx.md deleted file mode 100644 index 35358a67..00000000 --- a/commands/msetnx.md +++ /dev/null @@ -1,31 +0,0 @@ -Sets the given keys to their respective values. -`MSETNX` will not perform any operation at all even if just a single key already -exists. - -Because of this semantic `MSETNX` can be used in order to set different keys -representing different fields of a unique logic object in a way that ensures -that either all the fields or none at all are set. - -`MSETNX` is atomic, so all given keys are set at once. -It is not possible for clients to see that some of the keys were updated while -others are unchanged. - -## Reply - -One of the following: - -* Integer: `0` if no key was set (at least one key already existed). -* Integer: `1` if all the keys were set. - -## Examples - -``` -127.0.0.1:6379> MSETNX key1 "Hello" key2 "there" -(integer) 1 -127.0.0.1:6379> MSETNX key2 "new" key3 "world" -(integer) 0 -127.0.0.1:6379> MGET key1 key2 key3 -1) "Hello" -2) "there" -3) (nil) -``` diff --git a/commands/multi.md b/commands/multi.md deleted file mode 100644 index 81a4b9ba..00000000 --- a/commands/multi.md +++ /dev/null @@ -1,8 +0,0 @@ -Marks the start of a [transaction][tt] block. -Subsequent commands will be queued for atomic execution using `EXEC`. - -[tt]: ../topics/transactions.md - -## Reply - -`OK`. diff --git a/commands/object-encoding.md b/commands/object-encoding.md deleted file mode 100644 index 9c0bfcf0..00000000 --- a/commands/object-encoding.md +++ /dev/null @@ -1,47 +0,0 @@ -Returns the internal encoding for the Valkey object stored at `` - -Valkey objects can be encoded in different ways: - -* Strings can be encoded as: - - - `raw`, normal string encoding. - - `int`, strings representing integers in a 64-bit signed interval, encoded in this way to save space. - - `embstr`, an embedded string, which is an object where the internal simple dynamic string, `sds`, is an unmodifiable string allocated in the same chuck as the object itself. - `embstr` can be strings with lengths up to the hardcoded limit of `OBJ_ENCODING_EMBSTR_SIZE_LIMIT` or 44 bytes. - -* Lists can be encoded as: - - - `linkedlist`, simple list encoding. No longer used, an old list encoding. - - `listpack`, a space-efficient encoding used for small lists. - - `quicklist`, encoded as linked list of ziplists or listpacks. - -* Sets can be encoded as: - - - `hashtable`, normal set encoding. - - `intset`, a special encoding used for small sets composed solely of integers. - - `listpack`, a space-efficient encoding used for small sets. - -* Hashes can be encoded as: - - - `zipmap`, no longer used, an old hash encoding. - - `hashtable`, normal hash encoding. - - `listpack`, a space-efficient encoding used for small hashes. - -* Sorted Sets can be encoded as: - - - `btree`, normal sorted set encoding. - - `skiplist`, the name used for the normal sorted set encoding before it was replaced by a B+ tree. - - `listpack`, a space-efficient encoding used for small sorted sets. - -* Streams can be encoded as: - - - `stream`, encoded as a radix tree of listpacks. - -All the specially encoded types are automatically converted to the general type once you perform an operation that makes it impossible for Valkey to retain the space saving encoding. - -## Reply - -One of the following: - -* Null: if the key doesn't exist. -* String: the encoding of the object. diff --git a/commands/object-freq.md b/commands/object-freq.md deleted file mode 100644 index c95a7c53..00000000 --- a/commands/object-freq.md +++ /dev/null @@ -1,11 +0,0 @@ -This command returns the logarithmic access frequency counter of a Valkey object stored at ``. - -The command is only available when the `maxmemory-policy` configuration directive is set to one of the LFU policies. - -## Reply - -One of the following: - -Integer: the counter's value. - -Null: if _key_ doesn't exist. diff --git a/commands/object-help.md b/commands/object-help.md deleted file mode 100644 index 60f0cb28..00000000 --- a/commands/object-help.md +++ /dev/null @@ -1,5 +0,0 @@ -The `OBJECT HELP` command returns a helpful text describing the different subcommands. - -## Reply - -Array of sub-commands and their descriptions. diff --git a/commands/object-idletime.md b/commands/object-idletime.md deleted file mode 100644 index 53a8b022..00000000 --- a/commands/object-idletime.md +++ /dev/null @@ -1,11 +0,0 @@ -This command returns the time in seconds since the last access to the value stored at ``. - -The command is only available when the `maxmemory-policy` configuration directive is not set to one of the LFU policies. - -## Reply - -One of the following: - -Integer: the idle time in seconds. - -Null: if _key_ doesn't exist. diff --git a/commands/object-refcount.md b/commands/object-refcount.md deleted file mode 100644 index 3e573f0b..00000000 --- a/commands/object-refcount.md +++ /dev/null @@ -1,9 +0,0 @@ -This command returns the reference count of the stored at ``. - -## Reply - -One of the following: - -Integer: the number of references. - -Null: if _key_ doesn't exist. diff --git a/commands/object.md b/commands/object.md deleted file mode 100644 index 17fd3407..00000000 --- a/commands/object.md +++ /dev/null @@ -1,3 +0,0 @@ -This is a container command for object introspection commands. - -To see the list of available commands you can call [`OBJECT HELP`](object-help.md). diff --git a/commands/persist.md b/commands/persist.md deleted file mode 100644 index 96fda96f..00000000 --- a/commands/persist.md +++ /dev/null @@ -1,25 +0,0 @@ -Remove the existing timeout on `key`, turning the key from _volatile_ (a key -with an expire set) to _persistent_ (a key that will never expire as no timeout -is associated). - -## Reply - -One of the following: - -* Integer: `0` if _key_ does not exist or does not have an associated timeout. -* Integer: `1` if the timeout has been removed. - -## Examples - -``` -127.0.0.1:6379> SET mykey "Hello" -OK -127.0.0.1:6379> EXPIRE mykey 10 -(integer) 1 -127.0.0.1:6379> TTL mykey -(integer) 10 -127.0.0.1:6379> PERSIST mykey -(integer) 1 -127.0.0.1:6379> TTL mykey -(integer) -1 -``` diff --git a/commands/pexpire.md b/commands/pexpire.md deleted file mode 100644 index f2b02281..00000000 --- a/commands/pexpire.md +++ /dev/null @@ -1,42 +0,0 @@ -This command works exactly like [`EXPIRE`](expire.md) but the time to live of the key is -specified in milliseconds instead of seconds. - -## Options - -The `PEXPIRE` command supports a set of options - -* `NX` -- Set expiry only when the key has no expiry -* `XX` -- Set expiry only when the key has an existing expiry -* `GT` -- Set expiry only when the new expiry is greater than current one -* `LT` -- Set expiry only when the new expiry is less than current one - -A non-volatile key is treated as an infinite TTL for the purpose of `GT` and `LT`. -The `GT`, `LT` and `NX` options are mutually exclusive. - -## Reply - -One of the following: - -* Integer: `0`if the timeout was not set. For example, if the key doesn't exist, or the operation skipped because of the provided arguments. -* Integer: `1` if the timeout was set. - -## Examples - -``` -127.0.0.1:6379> SET mykey "Hello" -OK -127.0.0.1:6379> PEXPIRE mykey 1500 -(integer) 1 -127.0.0.1:6379> TTL mykey -(integer) 1 -127.0.0.1:6379> PTTL mykey -(integer) 1480 -127.0.0.1:6379> PEXPIRE mykey 1000 XX -(integer) 1 -127.0.0.1:6379> TTL mykey -(integer) 1 -127.0.0.1:6379> PEXPIRE mykey 1000 NX -(integer) 0 -127.0.0.1:6379> TTL mykey -(integer) 1 -``` diff --git a/commands/pexpireat.md b/commands/pexpireat.md deleted file mode 100644 index fdeb123d..00000000 --- a/commands/pexpireat.md +++ /dev/null @@ -1,34 +0,0 @@ -`PEXPIREAT` has the same effect and semantic as [`EXPIREAT`](expireat.md), but the Unix time at -which the key will expire is specified in milliseconds instead of seconds. - -## Options - -The `PEXPIREAT` command supports a set of options since Redis OSS 7.0: - -* `NX` -- Set expiry only when the key has no expiry -* `XX` -- Set expiry only when the key has an existing expiry -* `GT` -- Set expiry only when the new expiry is greater than current one -* `LT` -- Set expiry only when the new expiry is less than current one - -A non-volatile key is treated as an infinite TTL for the purpose of `GT` and `LT`. -The `GT`, `LT` and `NX` options are mutually exclusive. - -## Reply - -One of the following: - -* Integer: `1` if the timeout was set. -* Integer: `0` if the timeout was not set. For example, if the key doesn't exist, or the operation was skipped due to the provided arguments. - -## Examples - -``` -127.0.0.1:6379> SET mykey "Hello" -OK -127.0.0.1:6379> PEXPIREAT mykey 1555555555005 -(integer) 1 -127.0.0.1:6379> TTL mykey -(integer) -2 -127.0.0.1:6379> PTTL mykey -(integer) -2 -``` diff --git a/commands/pexpiretime.md b/commands/pexpiretime.md deleted file mode 100644 index e727b1f2..00000000 --- a/commands/pexpiretime.md +++ /dev/null @@ -1,20 +0,0 @@ -`PEXPIRETIME` has the same semantic as [`EXPIRETIME`](expiretime.md), but returns the absolute Unix expiration timestamp in milliseconds instead of seconds. - -## Reply - -One of the following: - -* Integer: Expiration Unix timestamp in milliseconds. -* Integer: `-1` if the key exists but has no associated expiration time. -* Integer: `-2` if the key does not exist. - -## Examples - -``` -127.0.0.1:6379> SET mykey "Hello" -OK -127.0.0.1:6379> PEXPIREAT mykey 33177117420000 -(integer) 1 -127.0.0.1:6379> PEXPIRETIME mykey -(integer) 33177117420000 -``` diff --git a/commands/pfadd.md b/commands/pfadd.md deleted file mode 100644 index 93824c37..00000000 --- a/commands/pfadd.md +++ /dev/null @@ -1,25 +0,0 @@ -Adds all the element arguments to the HyperLogLog data structure stored at the variable name specified as first argument. - -As a side effect of this command the HyperLogLog internals may be updated to reflect a different estimation of the number of unique items added so far (the cardinality of the set). - -If the approximated cardinality estimated by the HyperLogLog changed after executing the command, `PFADD` returns 1, otherwise 0 is returned. The command automatically creates an empty HyperLogLog structure (that is, a String of a specified length and with a given encoding) if the specified key does not exist. - -To call the command without elements but just the variable name is valid, this will result into no operation performed if the variable already exists, or just the creation of the data structure if the key does not exist (in the latter case 1 is returned). - -For an introduction to HyperLogLog data structure check the [`PFCOUNT`](pfcount.md) command page. - -## Reply - -One of the following: - -* Integer: `1` if at least one HyperLogLog internal register was altered. -* Integer: `0` if no HyperLogLog internal registers were altered. - -## Examples - -``` -127.0.0.1:6379> PFADD hll a b c d e f g -(integer) 1 -127.0.0.1:6379> PFCOUNT hll -(integer) 7 -``` diff --git a/commands/pfcount.md b/commands/pfcount.md deleted file mode 100644 index 65405c0b..00000000 --- a/commands/pfcount.md +++ /dev/null @@ -1,65 +0,0 @@ -When called with a single key, returns the approximated cardinality computed by the HyperLogLog data structure stored at the specified variable, which is 0 if the variable does not exist. - -When called with multiple keys, returns the approximated cardinality of the union of the HyperLogLogs passed, by internally merging the HyperLogLogs stored at the provided keys into a temporary HyperLogLog. - -The HyperLogLog data structure can be used in order to count **unique** elements in a set using just a small constant amount of memory, specifically 12k bytes for every HyperLogLog (plus a few bytes for the key itself). - -The returned cardinality of the observed set is not exact, but approximated with a standard error of 0.81%. - -For example, in order to take the count of all the unique search queries performed in a day, a program needs to call [`PFADD`](pfadd.md) every time a query is processed. The estimated number of unique queries can be retrieved with `PFCOUNT` at any time. - -Note: as a side effect of calling this function, it is possible that the HyperLogLog is modified, since the last 8 bytes encode the latest computed cardinality -for caching purposes. So `PFCOUNT` is technically a write command. - -## Reply - -Integer: the approximated number of unique elements observed via `PFADD`. - -## Examples - -``` -127.0.0.1:6379> PFADD hll foo bar zap -(integer) 1 -127.0.0.1:6379> PFADD hll zap zap zap -(integer) 0 -127.0.0.1:6379> PFADD hll foo bar -(integer) 0 -127.0.0.1:6379> PFCOUNT hll -(integer) 3 -127.0.0.1:6379> PFADD some-other-hll 1 2 3 -(integer) 1 -127.0.0.1:6379> PFCOUNT hll some-other-hll -(integer) 6 -``` - -Performances ---- - -When `PFCOUNT` is called with a single key, performances are excellent even if -in theory constant times to process a dense HyperLogLog are high. This is -possible because the `PFCOUNT` uses caching in order to remember the cardinality -previously computed, that rarely changes because most `PFADD` operations will -not update any register. Hundreds of operations per second are possible. - -When `PFCOUNT` is called with multiple keys, an on-the-fly merge of the -HyperLogLogs is performed, which is slow, moreover the cardinality of the union -can't be cached, so when used with multiple keys `PFCOUNT` may take a time in -the order of magnitude of the millisecond, and should be not abused. - -The user should take in mind that single-key and multiple-keys executions of -this command are semantically different and have different performances. - -HyperLogLog representation ---- - -HyperLogLogs are represented using a double representation: the *sparse* representation suitable for HLLs counting a small number of elements (resulting in a small number of registers set to non-zero value), and a *dense* representation suitable for higher cardinalities. Valkey automatically switches from the sparse to the dense representation when needed. - -The sparse representation uses a run-length encoding optimized to store efficiently a big number of registers set to zero. The dense representation is a String of 12288 bytes in order to store 16384 6-bit counters. The need for the double representation comes from the fact that using 12k (which is the dense representation memory requirement) to encode just a few registers for smaller cardinalities is extremely suboptimal. - -Both representations are prefixed with a 16 bytes header, that includes a magic, an encoding / version field, and the cached cardinality estimation computed, stored in little endian format (the most significant bit is 1 if the estimation is invalid since the HyperLogLog was updated since the cardinality was computed). - -The HyperLogLog, being a String, can be retrieved with [`GET`](get.md) and restored with [`SET`](set.md). Calling [`PFADD`](pfadd.md), `PFCOUNT` or [`PFMERGE`](pfmerge.md) commands with a corrupted HyperLogLog is never a problem, it may return random values but does not affect the stability of the server. Most of the times when corrupting a sparse representation, the server recognizes the corruption and returns an error. - -The representation is neutral from the point of view of the processor word size and endianness, so the same representation is used by 32 bit and 64 bit processor, big endian or little endian. - -More details about the HyperLogLog implementation can be found in [this blog post](https://web.archive.org/web/20241019222035/http://antirez.com/news/75). The source code of the implementation in the `hyperloglog.c` file is also easy to read and understand, and includes a full specification for the exact encoding used for the sparse and dense representations. diff --git a/commands/pfdebug.md b/commands/pfdebug.md deleted file mode 100644 index 3538e798..00000000 --- a/commands/pfdebug.md +++ /dev/null @@ -1,2 +0,0 @@ -The `PFDEBUG` command is an internal command. -It is meant to be used for developing and testing Valkey. \ No newline at end of file diff --git a/commands/pfmerge.md b/commands/pfmerge.md deleted file mode 100644 index 44319de1..00000000 --- a/commands/pfmerge.md +++ /dev/null @@ -1,27 +0,0 @@ -Merge multiple HyperLogLog values into a unique value that will approximate -the cardinality of the union of the observed Sets of the source HyperLogLog -structures. - -The computed merged HyperLogLog is set to the destination variable, which is -created if does not exist (defaulting to an empty HyperLogLog). - -If the destination variable exists, it is treated as one of the source sets -and its cardinality will be included in the cardinality of the computed -HyperLogLog. - -## Reply - -`OK`. - -## Examples - -``` -127.0.0.1:6379> PFADD hll1 foo bar zap a -(integer) 1 -127.0.0.1:6379> PFADD hll2 a b c foo -(integer) 1 -127.0.0.1:6379> PFMERGE hll3 hll1 hll2 -OK -127.0.0.1:6379> PFCOUNT hll3 -(integer) 6 -``` diff --git a/commands/pfselftest.md b/commands/pfselftest.md deleted file mode 100644 index 221ec918..00000000 --- a/commands/pfselftest.md +++ /dev/null @@ -1,6 +0,0 @@ -The `PFSELFTEST` command is an internal command. -It is meant to be used for developing and testing Valkey. - -## Reply - -`OK`. diff --git a/commands/ping.md b/commands/ping.md deleted file mode 100644 index 712bc4fb..00000000 --- a/commands/ping.md +++ /dev/null @@ -1,28 +0,0 @@ -Returns `PONG` if no argument is provided, otherwise return a copy of the -argument as a bulk. -This command is useful for: -1. Testing whether a connection is still alive. -1. Verifying the server's ability to serve data - an error is returned when this isn't the case (e.g., during load from persistence or accessing a stale replica). -1. Measuring latency. - -If the client is in RESP2 and is subscribed to a channel or a pattern, it will instead return a -multi-bulk with a "pong" in the first position and an empty bulk in the second -position, unless an argument is provided in which case it returns a copy -of the argument. - -## Reply - -Any of the following: - -* `PONG` when no argument is provided. -* String: the provided argument. - -## Examples - -``` -127.0.0.1:6379> PING -PONG -127.0.0.1:6379> -127.0.0.1:6379> PING "hello world" -"hello world" -``` diff --git a/commands/psetex.md b/commands/psetex.md deleted file mode 100644 index 6ca24442..00000000 --- a/commands/psetex.md +++ /dev/null @@ -1,21 +0,0 @@ -`PSETEX` works exactly like `SETEX` with the sole difference that the expire -time is specified in milliseconds instead of seconds. - -## Alternative - -`SET` with the `PX` argument. - -## Reply - -`OK`. - -## Examples - -``` -127.0.0.1:6379> PSETEX mykey 1000 "Hello" -OK -127.0.0.1:6379> PTTL mykey -(integer) 990 -127.0.0.1:6379> GET mykey -"Hello" -``` diff --git a/commands/psubscribe.md b/commands/psubscribe.md deleted file mode 100644 index 2ced2c5f..00000000 --- a/commands/psubscribe.md +++ /dev/null @@ -1,20 +0,0 @@ -Subscribes the client to the given patterns. - -Supported glob-style patterns: - -* `h?llo` subscribes to `hello`, `hallo` and `hxllo` -* `h*llo` subscribes to `hllo` and `heeeello` -* `h[ae]llo` subscribes to `hello` and `hallo,` but not `hillo` - -Use `\` to escape special characters if you want to match them verbatim. - -Once the client enters the subscribed state it is not supposed to issue any other commands, except for additional [`SUBSCRIBE`](subscribe.md), [`SSUBSCRIBE`](ssubscribe.md), `PSUBSCRIBE`, [`UNSUBSCRIBE`](unsubscribe.md), [`SUNSUBSCRIBE`](sunsubscribe.md), [`PUNSUBSCRIBE`](punsubscribe.md), [`PING`](ping.md), [`RESET`](reset.md) and [`QUIT`](quit.md) commands. -However, if RESP3 is used (see [`HELLO`](hello.md)) it is possible for a client to issue any commands while in subscribed state. - -Note that [`RESET`](reset.md) can be called to exit subscribed state. - -For more information, see [Pub/sub](../topics/pubsub.md). - -## Reply - -When successful, this command doesn't return anything. Instead, for each pattern, one message with the first element being the string `psubscribe` is pushed as a confirmation that the command succeeded. diff --git a/commands/psync.md b/commands/psync.md deleted file mode 100644 index ca437a59..00000000 --- a/commands/psync.md +++ /dev/null @@ -1,13 +0,0 @@ -Initiates a replication stream from the primary. - -The `PSYNC` command is called by Valkey replicas for initiating a replication -stream from the primary. - -For more information about replication in Valkey please check the -[replication page][tr]. - -[tr]: ../topics/replication.md - -## Reply - -**Non-standard return value**, a bulk transfer of the data followed by `PING` and write requests from the primary. diff --git a/commands/pttl.md b/commands/pttl.md deleted file mode 100644 index abeb39c1..00000000 --- a/commands/pttl.md +++ /dev/null @@ -1,27 +0,0 @@ -Like [`TTL`](ttl.md) this command returns the remaining time to live of a key that has an -expire set, with the sole difference that `TTL` returns the amount of remaining -time in seconds while `PTTL` returns it in milliseconds. - -The command returns the following values in case of errors: - -* The command returns `-2` if the key does not exist. -* The command returns `-1` if the key exists but has no associated expire. - -## Reply - -One of the following: - -* Integer: TTL in milliseconds. -* Integer: `-1` if the key exists but has no associated expiration. -* Integer: `-2` if the key does not exist. - -## Examples - -``` -127.0.0.1:6379> SET mykey "Hello" -OK -127.0.0.1:6379> EXPIRE mykey 1 -(integer) 1 -127.0.0.1:6379> PTTL mykey -(integer) 989 -``` diff --git a/commands/publish.md b/commands/publish.md deleted file mode 100644 index babb6e79..00000000 --- a/commands/publish.md +++ /dev/null @@ -1,9 +0,0 @@ -Posts a message to the given channel. - -In a Valkey Cluster clients can publish to every node. The cluster makes sure -that published messages are forwarded as needed, so clients can subscribe to any -channel by connecting to any one of the nodes. - -## Reply - -Integer: the number of clients that received the message. Note that in a Valkey Cluster, only clients that are connected to the same node as the publishing client are included in the count. diff --git a/commands/pubsub-channels.md b/commands/pubsub-channels.md deleted file mode 100644 index 094947eb..00000000 --- a/commands/pubsub-channels.md +++ /dev/null @@ -1,11 +0,0 @@ -Lists the currently *active channels*. - -An active channel is a Pub/Sub channel with one or more subscribers (excluding clients subscribed to patterns). - -If no `pattern` is specified, all the channels are listed, otherwise if pattern is specified only channels matching the specified glob-style pattern are listed. - -Cluster note: in a Valkey Cluster clients can subscribe to every node, and can also publish to every other node. The cluster will make sure that published messages are forwarded as needed. That said, the replies from [`PUBSUB`](pubsub.md) in a cluster only report information from the node's Pub/Sub context, rather than the entire cluster. - -## Reply - -Array of active channels, optionally matching the specified pattern. diff --git a/commands/pubsub-help.md b/commands/pubsub-help.md deleted file mode 100644 index 98247b6b..00000000 --- a/commands/pubsub-help.md +++ /dev/null @@ -1,5 +0,0 @@ -The `PUBSUB HELP` command returns a helpful text describing the different subcommands. - -## Reply - -Array of sub-commands and their descriptions. diff --git a/commands/pubsub-numpat.md b/commands/pubsub-numpat.md deleted file mode 100644 index 3df923a0..00000000 --- a/commands/pubsub-numpat.md +++ /dev/null @@ -1,9 +0,0 @@ -Returns the number of unique patterns that are subscribed to by clients (that are performed using the [`PSUBSCRIBE`](psubscribe.md) command). - -Note that this isn't the count of clients subscribed to patterns, but the total number of unique patterns all the clients are subscribed to. - -Cluster note: in a Valkey Cluster clients can subscribe to every node, and can also publish to every other node. The cluster will make sure that published messages are forwarded as needed. That said, the replies from [`PUBSUB`](pubsub.md) in a cluster only report information from the node's Pub/Sub context, rather than the entire cluster. - -## Reply - -Integer: the number of patterns all the clients are subscribed to. diff --git a/commands/pubsub-numsub.md b/commands/pubsub-numsub.md deleted file mode 100644 index 5bb6786e..00000000 --- a/commands/pubsub-numsub.md +++ /dev/null @@ -1,9 +0,0 @@ -Returns the number of subscribers (exclusive of clients subscribed to patterns) for the specified channels. - -Note that it is valid to call this command without channels. In this case it will just return an empty list. - -Cluster note: in a Valkey Cluster clients can subscribe to every node, and can also publish to every other node. The cluster will make sure that published messages are forwarded as needed. That said, the replies from [`PUBSUB`](pubsub.md) in a cluster only report information from the node's Pub/Sub context, rather than the entire cluster. - -## Reply - -Array: the number of subscribers per channel, each even element (including the 0th) is channel name, each odd element is the number of subscribers diff --git a/commands/pubsub-shardchannels.md b/commands/pubsub-shardchannels.md deleted file mode 100644 index c0d263fc..00000000 --- a/commands/pubsub-shardchannels.md +++ /dev/null @@ -1,20 +0,0 @@ -Lists the currently *active shard channels*. - -An active shard channel is a Pub/Sub shard channel with one or more subscribers. - -If no `pattern` is specified, all the channels are listed, otherwise if pattern is specified only channels matching the specified glob-style pattern are listed. - -The information returned about the active shard channels are at the shard level and not at the cluster level. - -## Reply - -Array of active channels, optionally matching the specified pattern. - -## Examples - -``` -> PUBSUB SHARDCHANNELS -1) "orders" -> PUBSUB SHARDCHANNELS o* -1) "orders" -``` diff --git a/commands/pubsub-shardnumsub.md b/commands/pubsub-shardnumsub.md deleted file mode 100644 index f7522023..00000000 --- a/commands/pubsub-shardnumsub.md +++ /dev/null @@ -1,17 +0,0 @@ -Returns the number of subscribers for the specified shard channels. - -Note that it is valid to call this command without channels, in this case it will just return an empty list. - -Cluster note: in a Valkey Cluster, the replies from [`PUBSUB`](pubsub.md) in a cluster only report information from the node's Pub/Sub context, rather than the entire cluster. - -## Reply - -Array: the number of subscribers per shard channel, each even element (including the 0th) is channel name, each odd element is the number of subscribers. - -## Examples - -``` -> PUBSUB SHARDNUMSUB orders -1) "orders" -2) (integer) 1 -``` diff --git a/commands/pubsub.md b/commands/pubsub.md deleted file mode 100644 index 4695cdf8..00000000 --- a/commands/pubsub.md +++ /dev/null @@ -1,3 +0,0 @@ -This is a container command for Pub/Sub introspection commands. - -To see the list of available commands you can call [`PUBSUB HELP`](pubsub-help.md). diff --git a/commands/punsubscribe.md b/commands/punsubscribe.md deleted file mode 100644 index 2e819110..00000000 --- a/commands/punsubscribe.md +++ /dev/null @@ -1,11 +0,0 @@ -Unsubscribes the client from the given patterns, or from all of them if none is -given. - -When no patterns are specified, the client is unsubscribed from all the -previously subscribed patterns. -In this case, a message for every unsubscribed pattern will be sent to the -client. - -## Reply - -When successful, this command doesn't return anything. Instead, for each pattern, one message with the first element being the string `punsubscribe` is pushed as a confirmation that the command succeeded. diff --git a/commands/quit.md b/commands/quit.md deleted file mode 100644 index 9089e54b..00000000 --- a/commands/quit.md +++ /dev/null @@ -1,15 +0,0 @@ -Ask the server to close the connection. -The connection is closed as soon as all pending replies have been written to the -client. - -**Note:** Clients should not use this command. -Instead, clients should simply close the connection when they're not used anymore. -Terminating a connection on the client side is preferable, as it eliminates `TIME_WAIT` lingering sockets on the server side. - -## Alternative - -Just closing the connection. - -## Reply - -`OK`. diff --git a/commands/randomkey.md b/commands/randomkey.md deleted file mode 100644 index bc0fd2dd..00000000 --- a/commands/randomkey.md +++ /dev/null @@ -1,8 +0,0 @@ -Return a random key from the currently selected database. - -## Reply - -One of the following: - -* Null: when the database is empty. -* String: a random key in the database. diff --git a/commands/readonly.md b/commands/readonly.md deleted file mode 100644 index e55b4c80..00000000 --- a/commands/readonly.md +++ /dev/null @@ -1,27 +0,0 @@ -Enables read queries for a connection to a Valkey replica node. - -In cluster mode, replica nodes will redirect clients to the authoritative primary for -the hash slot involved in a given command, however clients can use replicas -in order to scale reads using the `READONLY` command. - -`READONLY` tells a Valkey Cluster replica node that the client is willing to -read possibly stale data and is not interested in running write queries. - -When the connection is in readonly mode, the cluster will send a redirection -to the client only if the operation involves keys not served by the replica's -primary node. This may happen because: - -1. The client sent a command about hash slots never served by the primary of this replica. -2. The cluster was reconfigured (for example resharded) and the replica is no longer able to serve commands for a given hash slot. -3. Since Valkey 8.0, if a slot migration is ongoing. - In this case the replica can return an ASK redirect or a TRYAGAIN error reply. - In earlier versions, replicas are not aware of ongoing slot migrations. - -In standalone mode, by default, clients accessing a replica node can execute read queries, (which might read stale data) without entering readonly mode. - -Since Valkey 8.0, if a client in standalone mode uses the [`CLIENT CAPA redirect`](client-capa.md) command to declare its capability to handle redirections, then the replica node will send redirection messages to the client when executing both read and write commands. The client must issue the `READONLY` command to enter readonly mode before it can execute read commands. -Since Valkey 9.2, the same applies in cluster mode to read and write commands with no key arguments, such as `SCAN` or `DBSIZE`. - -## Reply - -`OK`. diff --git a/commands/readwrite.md b/commands/readwrite.md deleted file mode 100644 index 3de0efb5..00000000 --- a/commands/readwrite.md +++ /dev/null @@ -1,15 +0,0 @@ -Disables read queries for a connection to a Valkey replica node. - -Read queries against a Valkey Cluster replica node are disabled by default. - -For standalone replica nodes, since Valkey 8.0, read queries are also disabled -for clients that have executed the [`CLIENT CAPA redirect`](client-capa.md) command. -Since Valkey 9.2, the same applies in cluster mode to read commands with no key arguments. - -But you can use the [`READONLY`](readonly.md) command to change this behavior on a per- -connection basis. The `READWRITE` command resets the readonly mode flag -of a connection back to readwrite. - -## Reply - -`OK`. diff --git a/commands/rename.md b/commands/rename.md deleted file mode 100644 index a46122d0..00000000 --- a/commands/rename.md +++ /dev/null @@ -1,21 +0,0 @@ -Renames `key` to `newkey`. -It returns an error when `key` does not exist. - -If `newkey` already exists, it is overwritten. By default, Valkey uses implicit lazy freeing (similar to `UNLINK`), so large values are released asynchronously. If lazy freeing is disabled and synchronous deletion is configured, overwriting a key with a very large value may cause high latency. - -In Cluster mode, both `key` and `newkey` must be in the same **hash slot**, meaning that in practice only keys that have the same hash tag can be reliably renamed in cluster. - -## Reply - -`OK`. - -## Examples - -``` -127.0.0.1:6379> SET mykey "Hello" -OK -127.0.0.1:6379> RENAME mykey myotherkey -OK -127.0.0.1:6379> GET myotherkey -"Hello" -``` diff --git a/commands/renamenx.md b/commands/renamenx.md deleted file mode 100644 index aefdd905..00000000 --- a/commands/renamenx.md +++ /dev/null @@ -1,24 +0,0 @@ -Renames `key` to `newkey` if `newkey` does not yet exist. -It returns an error when `key` does not exist. - -In Cluster mode, both `key` and `newkey` must be in the same **hash slot**, meaning that in practice only keys that have the same hash tag can be reliably renamed in cluster. - -## Reply - -One of the following: - -* Integer: `1` if `key` was renamed to `newkey`. -* Integer: `0` if `newkey` already exists. - -## Examples - -``` -127.0.0.1:6379> SET mykey "Hello" -OK -127.0.0.1:6379> SET myotherkey "World" -OK -127.0.0.1:6379> RENAMENX mykey myotherkey -(integer) 0 -127.0.0.1:6379> GET myotherkey -"World" -``` diff --git a/commands/replconf.md b/commands/replconf.md deleted file mode 100644 index 50b7ca94..00000000 --- a/commands/replconf.md +++ /dev/null @@ -1,6 +0,0 @@ -The `REPLCONF` command is an internal command. -It is used by a Valkey primary to configure a connected replica. - -## Reply - -`OK`. diff --git a/commands/replicaof.md b/commands/replicaof.md deleted file mode 100644 index 420118e8..00000000 --- a/commands/replicaof.md +++ /dev/null @@ -1,22 +0,0 @@ -The `REPLICAOF` command can change the replication settings of a replica on the fly. -It's not allowed in cluster mode. In Valkey Cluster, use [`CLUSTER REPLICATE`](cluster-replicate.md) instead. - -If a Valkey server is already acting as replica, the command `REPLICAOF` NO ONE will turn off the replication, turning the Valkey server into a PRIMARY. In the proper form `REPLICAOF` hostname port will make the server a replica of another server listening at the specified hostname and port. - -If a server is already a replica of some primary, `REPLICAOF` hostname port will stop the replication against the old server and start the synchronization against the new one, discarding the old dataset. - -The form `REPLICAOF` NO ONE will stop replication, turning the server into a MASTER, but will not discard the replication. So, if the old primary stops working, it is possible to turn the replica into a primary and set the application to use this new primary in read/write. Later when the other Valkey server is fixed, it can be reconfigured to work as a replica. - -## Reply - -`OK`. - -## Examples - -``` -> REPLICAOF NO ONE -"OK" - -> REPLICAOF 127.0.0.1 6799 -"OK" -``` diff --git a/commands/reset.md b/commands/reset.md deleted file mode 100644 index b751eb91..00000000 --- a/commands/reset.md +++ /dev/null @@ -1,25 +0,0 @@ -This command performs a full reset of the connection's server-side context, -mimicking the effect of disconnecting and reconnecting again. - -When the command is called from a regular client connection, it does the -following: - -* Discards the current `MULTI` transaction block, if one exists. -* Unwatches all keys `WATCH`ed by the connection. -* Disables `CLIENT TRACKING`, if in use. -* Sets the connection to `READWRITE` mode. -* Cancels the connection's `ASKING` mode, if previously set. -* Sets `CLIENT REPLY` to `ON`. -* Sets the protocol version to RESP2. -* `SELECT`s database 0. -* Exits `MONITOR` mode, when applicable. -* Aborts Pub/Sub's subscription state (`SUBSCRIBE` and `PSUBSCRIBE`), when - appropriate. -* Deauthenticates the connection, requiring a call `AUTH` to reauthenticate when - authentication is enabled. -* Turns off `NO-EVICT` mode. -* Turns off `NO-TOUCH` mode. - -## Reply - -`RESET`. diff --git a/commands/restore-asking.md b/commands/restore-asking.md deleted file mode 100644 index 0daf070e..00000000 --- a/commands/restore-asking.md +++ /dev/null @@ -1,6 +0,0 @@ -The `RESTORE-ASKING` command is an internal command. -It is used by a Valkey cluster primary during slot migration. - -## Reply - -`OK`. diff --git a/commands/restore.md b/commands/restore.md deleted file mode 100644 index 5fa7fb83..00000000 --- a/commands/restore.md +++ /dev/null @@ -1,40 +0,0 @@ -Create a key associated with a value that is obtained by deserializing the -provided serialized value (obtained via [`DUMP`](dump.md)). - -If `ttl` is 0 the key is created without any expire, otherwise the specified -expire time (in milliseconds) is set. - -If the `ABSTTL` modifier was used, `ttl` should represent an absolute -[Unix timestamp][hewowu] (in milliseconds) in which the key will expire. - -[hewowu]: http://en.wikipedia.org/wiki/Unix_time - -For eviction purposes, you may use the `IDLETIME` or `FREQ` modifiers. See -[`OBJECT`](object.md) for more information. - -`RESTORE` will return a "Target key name is busy" error when `key` already -exists unless you use the `REPLACE` modifier. - -`RESTORE` checks the RDB version and data checksum. -If they don't match an error is returned. - -## Reply - -`OK`. - -## Examples - -``` -127.0.0.1:6379> DEL mykey -(integer) 0 -127.0.0.1:6379> RESTORE mykey 0 "\n\x17\x17\x00\x00\x00\x12\x00\x00\x00\x03\x00\ - x00\xc0\x01\x00\x04\xc0\x02\x00\x04\xc0\x03\x00\ - xff\x04\x00u#<\xc0;.\xe9\xdd" -OK -127.0.0.1:6379> TYPE mykey -list -127.0.0.1:6379> LRANGE mykey 0 -1 -1) "1" -2) "2" -3) "3" -``` diff --git a/commands/role.md b/commands/role.md deleted file mode 100644 index f52ae39d..00000000 --- a/commands/role.md +++ /dev/null @@ -1,85 +0,0 @@ -Provide information on the role of a Valkey instance in the context of replication, by returning if the instance is currently a `master`, `slave`, or `sentinel`. The command also returns additional information about the state of the replication (if the role is primary or replica) or the list of monitored primary names (if the role is sentinel). - -## Output format - -The command returns an array of elements. The first element is the role of -the instance, as one of the following three strings: - -* "master" -* "slave" -* "sentinel" - -The additional elements of the array depends on the role. - -## Primary output - -An example of output when `ROLE` is called in a primary instance: - -``` -1) "master" -2) (integer) 3129659 -3) 1) 1) "127.0.0.1" - 2) "9001" - 3) "3129242" - 2) 1) "127.0.0.1" - 2) "9002" - 3) "3129543" -``` - -The primary output is composed of the following parts: - -1. The string `master`. -2. The current primary replication offset, which is an offset that primaries and replicas share to understand, in partial resynchronizations, the part of the replication stream the replicas needs to fetch to continue. -3. An array composed of three elements array representing the online replicas. Every sub-array contains the replica IP, port, and the last acknowledged replication offset. - -## Output of the command on replicas - -An example of output when `ROLE` is called in a replica instance: - -``` -1) "slave" -2) "127.0.0.1" -3) (integer) 9000 -4) "connected" -5) (integer) 3167038 -``` - -The replica output is composed of the following parts: - -1. The string `slave`, because of Redis OSS compatibility (see note at the end of this page). -2. The IP of the primary. -3. The port number of the primary. -4. The state of the replication from the point of view of the replica, that can be `connect` (the instance needs to connect to its primary), `connecting` (the primary-replica connection is in progress), `handshake` (the primary and replica are doing the handshake), `sync` (the primary and replica are trying to perform the synchronization), `connected` (the replica is online). -5. The amount of data received from the replica so far in terms of primary replication offset. - -## Sentinel output - -An example of Sentinel output: - -``` -1) "sentinel" -2) 1) "resque-master" - 2) "html-fragments-master" - 3) "stats-master" - 4) "metadata-master" -``` - -The sentinel output is composed of the following parts: - -1. The string `sentinel`. -2. An array of primary names monitored by this Sentinel instance. - -## Reply - -Array: where the first element is one of `master`, `slave`, or `sentinel`, and the additional elements are role-specific as illustrated above. - -## Examples - -``` -127.0.0.1:6379> ROLE -1) "master" -2) (integer) 0 -3) (empty array) -``` - -**A note about the word slave used in this man page**: If not for backward compatibility, the Valkey project no longer uses the words "master" and "slave". Unfortunately in the given commands these words are part of the protocol, so we'll be able to remove such occurrences only when this API will be naturally deprecated. \ No newline at end of file diff --git a/commands/rpop.md b/commands/rpop.md deleted file mode 100644 index d6f0c772..00000000 --- a/commands/rpop.md +++ /dev/null @@ -1,27 +0,0 @@ -By default, the command pops a single element from the end of the list. -When provided with the optional `count` argument, the reply will consist of up -to `count` elements, depending on the list's length. -Deletes the list if the last element was popped. - -## Reply - -One of the following: - -* Null: if the key does not exist. -* String: when called without the _count_ argument, the value of the last element. -* Array: when called with the _count_ argument, a list of popped elements. - -## Examples - -``` -127.0.0.1:6379> RPUSH mylist "one" "two" "three" "four" "five" -(integer) 5 -127.0.0.1:6379> RPOP mylist -"five" -127.0.0.1:6379> RPOP mylist 2 -1) "four" -2) "three" -127.0.0.1:6379> LRANGE mylist 0 -1 -1) "one" -2) "two" -``` diff --git a/commands/rpoplpush.md b/commands/rpoplpush.md deleted file mode 100644 index 802de5ea..00000000 --- a/commands/rpoplpush.md +++ /dev/null @@ -1,89 +0,0 @@ -Atomically returns and removes the last element (tail) of the list stored at -`source`, and pushes the element at the first element (head) of the list stored -at `destination`. - -For example: consider `source` holding the list `a,b,c`, and `destination` -holding the list `x,y,z`. -Executing `RPOPLPUSH` results in `source` holding `a,b` and `destination` -holding `c,x,y,z`. - -If `source` does not exist, the value `nil` is returned and no operation is -performed. -If `source` and `destination` are the same, the operation is equivalent to -removing the last element from the list and pushing it as first element of the -list, so it can be considered as a list rotation command. - -## Alternative - -`LMOVE` with the `RIGHT` and `LEFT` arguments. - -## Reply - -One of the following: - -* String: the element being popped and pushed. -* Null: if the source list is empty. - -## Examples - -``` -127.0.0.1:6379> RPUSH mylist "one" -(integer) 1 -127.0.0.1:6379> RPUSH mylist "two" -(integer) 2 -127.0.0.1:6379> RPUSH mylist "three" -(integer) 3 -127.0.0.1:6379> RPOPLPUSH mylist myotherlist -"three" -127.0.0.1:6379> LRANGE mylist 0 -1 -1) "one" -2) "two" -127.0.0.1:6379> LRANGE myotherlist 0 -1 -1) "three" -``` - -## Pattern: Reliable queue - -Valkey is often used as a messaging server to implement processing of background -jobs or other kinds of messaging tasks. -A simple form of queue is often obtained pushing values into a list in the -producer side, and waiting for this values in the consumer side using `RPOP` -(using polling), or `BRPOP` if the client is better served by a blocking -operation. - -However in this context the obtained queue is not _reliable_ as messages can -be lost, for example in the case there is a network problem or if the consumer -crashes just after the message is received but before it can be processed. - -`RPOPLPUSH` (or `BRPOPLPUSH` for the blocking variant) offers a way to avoid -this problem: the consumer fetches the message and at the same time pushes it -into a _processing_ list. -It will use the `LREM` command in order to remove the message from the -_processing_ list once the message has been processed. - -An additional client may monitor the _processing_ list for items that remain -there for too much time, pushing timed out items into the queue -again if needed. - -## Pattern: Circular list - -Using `RPOPLPUSH` with the same source and destination key, a client can visit -all the elements of an N-elements list, one after the other, in O(N) without -transferring the full list from the server to the client using a single `LRANGE` -operation. - -The above pattern works even if one or both of the following conditions occur: - -* There are multiple clients rotating the list: they'll fetch different - elements, until all the elements of the list are visited, and the process - restarts. -* Other clients are actively pushing new items at the end of the list. - -The above makes it very simple to implement a system where a set of items must -be processed by N workers continuously as fast as possible. -An example is a monitoring system that must check that a set of web sites are -reachable, with the smallest delay possible, using a number of parallel workers. - -Note that this implementation of workers is trivially scalable and reliable, -because even if a message is lost the item is still in the queue and will be -processed at the next iteration. diff --git a/commands/rpush.md b/commands/rpush.md deleted file mode 100644 index d91839c4..00000000 --- a/commands/rpush.md +++ /dev/null @@ -1,27 +0,0 @@ -Insert all the specified values at the tail of the list stored at `key`. -If `key` does not exist, it is created as empty list before performing the push -operation. -When `key` holds a value that is not a list, an error is returned. - -It is possible to push multiple elements using a single command call just -specifying multiple arguments at the end of the command. -Elements are inserted one after the other to the tail of the list, from the -leftmost element to the rightmost element. -So for instance the command `RPUSH mylist a b c` will result into a list -containing `a` as first element, `b` as second element and `c` as third element. - -## Reply - -Integer: the length of the list after the push operation. - -## Examples - -``` -127.0.0.1:6379> RPUSH mylist "hello" -(integer) 1 -127.0.0.1:6379> RPUSH mylist "world" -(integer) 2 -127.0.0.1:6379> LRANGE mylist 0 -1 -1) "hello" -2) "world" -``` diff --git a/commands/rpushx.md b/commands/rpushx.md deleted file mode 100644 index 097be04c..00000000 --- a/commands/rpushx.md +++ /dev/null @@ -1,24 +0,0 @@ -Inserts specified values at the tail of the list stored at `key`, only if `key` -already exists and holds a list. -In contrary to [`RPUSH`](rpush.md), no operation will be performed when `key` does not yet -exist. - -## Reply - -Integer: the length of the list after the push operation. - -## Examples - -``` -127.0.0.1:6379> RPUSH mylist "Hello" -(integer) 1 -127.0.0.1:6379> RPUSHX mylist "World" -(integer) 2 -127.0.0.1:6379> RPUSHX myotherlist "World" -(integer) 0 -127.0.0.1:6379> LRANGE mylist 0 -1 -1) "Hello" -2) "World" -127.0.0.1:6379> LRANGE myotherlist 0 -1 -(empty array) -``` diff --git a/commands/sadd.md b/commands/sadd.md deleted file mode 100644 index 973a6588..00000000 --- a/commands/sadd.md +++ /dev/null @@ -1,24 +0,0 @@ -Add the specified members to the set stored at `key`. -Specified members that are already a member of this set are ignored. -If `key` does not exist, a new set is created before adding the specified -members. - -An error is returned when the value stored at `key` is not a set. - -## Reply - -Integer: the number of elements that were added to the set, not including all the elements already present in the set. - -## Examples - -``` -127.0.0.1:6379> SADD myset "Hello" -(integer) 1 -127.0.0.1:6379> SADD myset "World" -(integer) 1 -127.0.0.1:6379> SADD myset "World" -(integer) 0 -127.0.0.1:6379> SMEMBERS myset -1) "Hello" -2) "World" -``` diff --git a/commands/save.md b/commands/save.md deleted file mode 100644 index 48f4ff90..00000000 --- a/commands/save.md +++ /dev/null @@ -1,18 +0,0 @@ -The `SAVE` commands performs a **synchronous** save of the dataset producing a -_point in time_ snapshot of all the data inside the Valkey instance, in the form -of an RDB file. - -You almost never want to call `SAVE` in production environments where it will -block all the other clients. -Instead usually [`BGSAVE`](bgsave.md) is used. -However in case of issues preventing Valkey to create the background saving child -(for instance errors in the fork(2) system call), the `SAVE` command can be a -good last resort to perform the dump of the latest dataset. - -Please refer to the [persistence documentation][tp] for detailed information. - -[tp]: ../topics/persistence.md - -## Reply - -`OK`. diff --git a/commands/scan.md b/commands/scan.md deleted file mode 100644 index 99a99525..00000000 --- a/commands/scan.md +++ /dev/null @@ -1,286 +0,0 @@ -The `SCAN` command and the closely related commands `SSCAN`, `HSCAN` and `ZSCAN` are used in order to incrementally iterate over a collection of elements. - -* `SCAN` iterates the set of keys in the currently selected Valkey database. -* `SSCAN` iterates elements of Sets types. -* `HSCAN` iterates fields of Hash types and their associated values. -* `ZSCAN` iterates elements of Sorted Set types and their associated scores. - -Since these commands allow for incremental iteration, returning only a small number of elements per call, they can be used in production without the downside of commands like [`KEYS`](keys.md) or [`SMEMBERS`](smembers.md) that may block the server for a long time (even several seconds) when called against big collections of keys or elements. - -However while blocking commands like `SMEMBERS` are able to provide all the elements that are part of a Set in a given moment, the SCAN family of commands only offer limited guarantees about the returned elements since the collection that we incrementally iterate can change during the iteration process. - -Note that `SCAN`, `SSCAN`, `HSCAN` and `ZSCAN` all work very similarly, so this documentation covers all four commands. However an obvious difference is that in the case of `SSCAN`, `HSCAN` and `ZSCAN` the first argument is the name of the key holding the Set, Hash or Sorted Set value. The `SCAN` command does not need any key name argument as it iterates keys in the current database, so the iterated object is the database itself. - -## SCAN basic usage - -SCAN is a cursor based iterator. This means that at every call of the command, the server returns an updated cursor that the user needs to use as the cursor argument in the next call. - -An iteration starts when the cursor is set to 0, and terminates when the cursor returned by the server is 0. The following is an example of SCAN iteration: - -``` -127.0.0.1:6379> scan 0 -1) "17" -2) 1) "key:12" - 2) "key:8" - 3) "key:4" - 4) "key:14" - 5) "key:16" - 6) "key:17" - 7) "key:15" - 8) "key:10" - 9) "key:3" - 10) "key:7" - 11) "key:1" -127.0.0.1:6379> scan 17 -1) "0" -2) 1) "key:5" - 2) "key:18" - 3) "key:0" - 4) "key:2" - 5) "key:19" - 6) "key:13" - 7) "key:6" - 8) "key:9" - 9) "key:11" -``` - -In the example above, the first call uses zero as a cursor, to start the iteration. The second call uses the cursor returned by the previous call as the first element of the reply, that is, 17. - -As you can see the **SCAN return value** is an array of two values: the first value is the new cursor to use in the next call, the second value is an array of elements. - -Since in the second call the returned cursor is 0, the server signaled to the caller that the iteration finished, and the collection was completely explored. Starting an iteration with a cursor value of 0, and calling `SCAN` until the returned cursor is 0 again is called a **full iteration**. - -## Return value - -`SCAN`, `SSCAN`, `HSCAN` and `ZSCAN` return a two element multi-bulk reply, where the first element is a string representing an unsigned 64 bit number (the cursor), and the second element is a multi-bulk with an array of elements. - -* `SCAN` array of elements is a list of keys. -* `SSCAN` array of elements is a list of Set members. -* `HSCAN` array of elements contain two elements, a field and a value, for every returned element of the Hash. -* `ZSCAN` array of elements contain two elements, a member and its associated score, for every returned element of the Sorted Set. - -## Scan guarantees - -The `SCAN` command, and the other commands in the `SCAN` family, are able to provide to the user a set of guarantees associated to full iterations. - -* A full iteration always retrieves all the elements that were present in the collection from the start to the end of a full iteration. This means that if a given element is inside the collection when an iteration is started, and is still there when an iteration terminates, then at some point `SCAN` returned it to the user. -* A full iteration never returns any element that was NOT present in the collection from the start to the end of a full iteration. So if an element was removed before the start of an iteration, and is never added back to the collection for all the time an iteration lasts, `SCAN` ensures that this element will never be returned. - -However because `SCAN` has very little state associated (just the cursor) it has the following drawbacks: - -* A given element may be returned multiple times. It is up to the application to handle the case of duplicated elements, for example only using the returned elements in order to perform operations that are safe when re-applied multiple times. -* Elements that were not constantly present in the collection during a full iteration, may be returned or not: it is undefined. - -Starting with Valkey **9.1**, you can make the `SCAN` family (including `HSCAN`, `SSCAN`, and `ZSCAN`) return keys in a **consistent order**. Set the immutable startup configuration **`hash-seed`** to the **same string (up to 256 characters) on all nodes** which helps clients resume an in-progress scan even after a failover. - -## Number of elements returned at every SCAN call - -`SCAN` family functions do not guarantee that the number of elements returned per call are in a given range. The commands are also allowed to return zero elements, and the client should not consider the iteration complete as long as the returned cursor is not zero. - -However the number of returned elements is reasonable, that is, in practical terms `SCAN` may return a maximum number of elements in the order of a few tens of elements when iterating a large collection, or may return all the elements of the collection in a single call when the iterated collection is small enough to be internally represented as an encoded data structure (this happens for small Sets, Hashes and Sorted Sets). - -However there is a way for the user to tune the order of magnitude of the number of returned elements per call using the **COUNT** option. - -## The COUNT option - -While `SCAN` does not provide guarantees about the number of elements returned at every iteration, it is possible to empirically adjust the behavior of `SCAN` using the **COUNT** option. Basically with COUNT the user specifies the *amount of work that should be done at every call in order to retrieve elements from the collection*. This is **just a hint** for the implementation, however generally speaking this is what you could expect most of the times from the implementation. - -* The default `COUNT` value is 10. -* When iterating the key space, or a Set, Hash or Sorted Set that is big enough to be represented by a hash table, assuming no **MATCH** option is used, the server will usually return *count* or a few more than *count* elements per call. Please check the *why SCAN may return all the elements at once* section later in this document. -* When iterating Sets encoded as intsets (small sets composed of just integers), or Hashes and Sorted Sets encoded as ziplists (small hashes and sets composed of small individual values), usually all the elements are returned in the first `SCAN` call regardless of the `COUNT` value. - -Important: **there is no need to use the same COUNT value** for every iteration. The caller is free to change the count from one iteration to the other as required, as long as the cursor passed in the next call is the one obtained in the previous call to the command. - -## The MATCH option - -It is possible to only iterate elements matching a given glob-style pattern, similarly to the behavior of the `KEYS` command that takes a pattern as its only argument. - -To do so, just append the `MATCH ` arguments at the end of the `SCAN` command (it works with all the `SCAN` family commands). - -This is an example of iteration using **MATCH**: - -``` -127.0.0.1:6379> sadd myset 1 2 3 foo foobar feelsgood -(integer) 6 -127.0.0.1:6379> sscan myset 0 match f* -1) "0" -2) 1) "foo" - 2) "feelsgood" - 3) "foobar" -127.0.0.1:6379> -``` - -It is important to note that the **MATCH** filter is applied after elements are retrieved from the collection, just before returning data to the client. This means that if the pattern matches very little elements inside the collection, `SCAN` will likely return no elements in most iterations. An example is shown below: - -``` -127.0.0.1:6379> scan 0 MATCH *11* -1) "288" -2) 1) "key:911" -127.0.0.1:6379> scan 288 MATCH *11* -1) "224" -2) (empty list or set) -127.0.0.1:6379> scan 224 MATCH *11* -1) "80" -2) (empty list or set) -127.0.0.1:6379> scan 80 MATCH *11* -1) "176" -2) (empty list or set) -127.0.0.1:6379> scan 176 MATCH *11* COUNT 1000 -1) "0" -2) 1) "key:611" - 2) "key:711" - 3) "key:118" - 4) "key:117" - 5) "key:311" - 6) "key:112" - 7) "key:111" - 8) "key:110" - 9) "key:113" - 10) "key:211" - 11) "key:411" - 12) "key:115" - 13) "key:116" - 14) "key:114" - 15) "key:119" - 16) "key:811" - 17) "key:511" - 18) "key:11" -127.0.0.1:6379> -``` - -As you can see most of the calls returned zero elements, but the last call where a `COUNT` of 1000 was used in order to force the command to do more scanning for that iteration. - -When using [Valkey Cluster](../topics/cluster-tutorial.md), the search is optimized for patterns that imply a single slot. -If a pattern can only match keys of one slot, -Valkey only iterates over keys in that slot, rather than the whole database, -when searching for keys matching the pattern. -For example, with the pattern `{a}h*llo`, Valkey would only try to match it with the keys in slot 15495, which hash tag `{a}` implies. -To use pattern with hash tag, see [Hash tags](../topics/cluster-spec.md#hash-tags) in the Cluster specification for more information. - -## The TYPE option - -You can use the `TYPE` option to ask `SCAN` to only return objects that match a given `type`, allowing you to iterate through the database looking for keys of a specific type. The **`TYPE`** option is only available on the whole-database `SCAN`, not `HSCAN` or `ZSCAN` etc. - -The `type` argument is the same string name that the `TYPE` command returns. Note a quirk where some Valkey types, such as GeoHashes, HyperLogLogs, Bitmaps, and Bitfields, may internally be implemented using other Valkey types, such as a string or zset, so can't be distinguished from other keys of that same type by `SCAN`. For example, a ZSET and GEOHASH: - -``` -127.0.0.1:6379> GEOADD geokey 0 0 value -(integer) 1 -127.0.0.1:6379> ZADD zkey 1000 value -(integer) 1 -127.0.0.1:6379> TYPE geokey -zset -127.0.0.1:6379> TYPE zkey -zset -127.0.0.1:6379> SCAN 0 TYPE zset -1) "0" -2) 1) "geokey" - 2) "zkey" -``` - -It is important to note that the **TYPE** filter is also applied after elements are retrieved from the database, so the option does not reduce the amount of work the server has to do to complete a full iteration, and for rare types you may receive no elements in many iterations. - -## The NOVALUES option - -When using `HSCAN`, you can use the `NOVALUES` option to make Valkey return only the keys in the hash table without their corresponding values. - -``` -127.0.0.1:6379> HSET myhash a 1 b 2 -(integer) 2 -127.0.0.1:6379> HSCAN myhash 0 -1) "0" -2) 1) "a" - 2) "1" - 3) "b" - 4) "2" -127.0.0.1:6379> HSCAN myhash 0 NOVALUES -1) "0" -2) 1) "a" - 2) "b" -``` - -## The NOSCORES option - -When using `ZSCAN`, you can use the `NOSCORES` option to make Valkey return only the members in the sorted set without their corresponding scores. - -``` -127.0.0.1:6379> ZADD myzset 1 a 2 b -(integer) 2 -127.0.0.1:6379> ZSCAN myzset 0 -1) "0" -2) 1) "a" - 2) "1" - 3) "b" - 4) "2" -127.0.0.1:6379> ZSCAN myzset 0 NOSCORES -1) "0" -2) 1) "a" - 2) "b" -``` - -## Multiple parallel iterations - -It is possible for an infinite number of clients to iterate the same collection at the same time, as the full state of the iterator is in the cursor, that is obtained and returned to the client at every call. No server side state is taken at all. - -## Terminating iterations in the middle - -Since there is no state server side, but the full state is captured by the cursor, the caller is free to terminate an iteration half-way without signaling this to the server in any way. An infinite number of iterations can be started and never terminated without any issue. - -## Calling SCAN with a corrupted cursor - -Calling `SCAN` with a broken, negative, out of range, or otherwise invalid cursor, will result in undefined behavior but never in a crash. What will be undefined is that the guarantees about the returned elements can no longer be ensured by the `SCAN` implementation. - -The only valid cursors to use are: - -* The cursor value of 0 when starting an iteration. -* The cursor returned by the previous call to SCAN in order to continue the iteration. - -## Guarantee of termination - -The `SCAN` algorithm is guaranteed to terminate only if the size of the iterated collection remains bounded to a given maximum size, otherwise iterating a collection that always grows may result into `SCAN` to never terminate a full iteration. - -This is easy to see intuitively: if the collection grows there is more and more work to do in order to visit all the possible elements, and the ability to terminate the iteration depends on the number of calls to `SCAN` and its COUNT option value compared with the rate at which the collection grows. - -## Why SCAN may return all the items of an aggregate data type in a single call? - -In the `COUNT` option documentation, we state that sometimes this family of commands may return all the elements of a Set, Hash or Sorted Set at once in a single call, regardless of the `COUNT` option value. The reason why this happens is that the cursor-based iterator can be implemented, and is useful, only when the aggregate data type that we are scanning is represented as a hash table. However Valkey uses a [memory optimization](../topics/memory-optimization.md) where small aggregate data types, until they reach a given amount of items or a given max size of single elements, are represented using a compact single-allocation packed encoding. When this is the case, `SCAN` has no meaningful cursor to return, and must iterate the whole data structure at once, so the only sane behavior it has is to return everything in a call. - -However once the data structures are bigger and are promoted to use real hash tables, the `SCAN` family of commands will resort to the normal behavior. Note that since this special behavior of returning all the elements is true only for small aggregates, it has no effects on the command complexity or latency. However the exact limits to get converted into real hash tables are [user configurable](../topics/memory-optimization.md), so the maximum number of elements you can see returned in a single call depends on how big an aggregate data type could be and still use the packed representation. - -Also note that this behavior is specific of `SSCAN`, `HSCAN` and `ZSCAN`. `SCAN` itself never shows this behavior because the key space is always represented by hash tables. - -## Scan-induced accumulation bias - -A common pattern is to iterate a large collection with `SCAN` (or `SSCAN`, `HSCAN`, `ZSCAN`) while deleting the returned elements, expecting the collection to drain over time. **Be careful when another process concurrently adds elements back into the same collection.** This combination can create a systematic load imbalance inside the underlying hash table. - -The reason is that the `SCAN` cursor sweeps the hash table in a fixed order. Buckets *behind* the cursor have just been visited and emptied of the elements that were removed, while buckets *ahead* of the cursor have not been visited yet. If a second process keeps inserting new elements uniformly at random to keep the collection near a target size, those insertions land disproportionately in the not-yet-scanned region. With each pass, the buckets ahead of the cursor accumulate more and more elements, while the buckets behind it stay depleted - the cursor effectively acts like a snowplow, pushing load ahead of itself. - -Over time some buckets grow far beyond their fair share. Scaled up to hundreds of thousands of elements, a single bucket can grow large enough that one `SCAN` call returns far more elements than the requested `COUNT` (recall that `COUNT` is only a hint, and `SCAN` may return all elements that hash to the buckets it visits in a given call). - -**Restarting the scan from the beginning makes this worse.** If your application aborts mid-iteration and restarts with a cursor of 0 - for example, automatically retrying from scratch whenever it hits an error - it repeatedly re-scans the already-depleted front of the table while never reaching the increasingly skewed buckets at the back. This turns the imbalance into a runaway feedback loop and can leave the hash table extremely skewed. To avoid this, **always resume from the cursor returned by the previous call** rather than restarting the iteration at 0. On a transient error, retry from the last cursor you received, not from the beginning. - -## Further reading - -For more information about managing keys, please refer to the [The Valkey Keyspace](../topics/keyspace.md) tutorial. - -## Additional examples - -Iteration of a Hash value. - -``` -127.0.0.1:6379> hmset hash name Jack age 33 -OK -127.0.0.1:6379> hscan hash 0 -1) "0" -2) 1) "name" - 2) "Jack" - 3) "age" - 4) "33" -``` - -## Reply - -Array with two elements. - -* The first element is a string that represents an unsigned 64-bit number, the cursor. -* The second element is an array with the names of scanned keys. diff --git a/commands/scard.md b/commands/scard.md deleted file mode 100644 index aefc9a73..00000000 --- a/commands/scard.md +++ /dev/null @@ -1,16 +0,0 @@ -Returns the set cardinality (number of elements) of the set stored at `key`. - -## Reply - -Integer: the cardinality (number of elements) of the set, or `0` if the key does not exist. - -## Examples - -``` -127.0.0.1:6379> SADD myset "Hello" -(integer) 1 -127.0.0.1:6379> SADD myset "World" -(integer) 1 -127.0.0.1:6379> SCARD myset -(integer) 2 -``` diff --git a/commands/script-debug.md b/commands/script-debug.md deleted file mode 100644 index d26bbba3..00000000 --- a/commands/script-debug.md +++ /dev/null @@ -1,26 +0,0 @@ -Set the debug mode for subsequent scripts executed with [`EVAL`](eval.md). Valkey includes a -complete Lua debugger, codename LDB, that can be used to make the task of -writing complex scripts much simpler. In debug mode Valkey acts as a remote -debugging server and a client, such as [`valkey-cli`](../topics/cli.md), can execute scripts step by -step, set breakpoints, inspect variables and more - for additional information -about LDB refer to the [Valkey Lua debugger](../topics/ldb.md) page. - -**Important note:** avoid debugging Lua scripts using your Valkey production -server. Use a development server instead. - -LDB can be enabled in one of two modes: asynchronous or synchronous. In -asynchronous mode the server creates a forked debugging session that does not -block and all changes to the data are **rolled back** after the session -finishes, so debugging can be restarted using the same initial state. The -alternative synchronous debug mode blocks the server while the debugging session -is active and retains all changes to the data set once it ends. - -* `YES`. Enable non-blocking asynchronous debugging of Lua scripts (changes are discarded). -* `SYNC`. Enable blocking synchronous debugging of Lua scripts (saves changes to data). -* `NO`. Disables scripts debug mode. - -For more information about `EVAL` scripts please refer to [Introduction to Eval Scripts](../topics/eval-intro.md). - -## Reply - -`OK`. diff --git a/commands/script-exists.md b/commands/script-exists.md deleted file mode 100644 index 09168b83..00000000 --- a/commands/script-exists.md +++ /dev/null @@ -1,15 +0,0 @@ -Returns information about the existence of the scripts in the script cache. - -This command accepts one or more SHA1 digests and returns a list of ones or -zeros to signal if the scripts are already defined or not inside the script -cache. -This can be useful before a pipelining operation to ensure that scripts are -loaded (and if not, to load them using [`SCRIPT LOAD`](script-load.md)) so that the pipelining -operation can be performed solely using [`EVALSHA`](evalsha.md) instead of [`EVAL`](eval.md) to save -bandwidth. - -For more information about `EVAL` scripts please refer to [Introduction to Eval Scripts](../topics/eval-intro.md). - -## Reply - -Array of integers that correspond to the specified SHA1 digest arguments. diff --git a/commands/script-flush.md b/commands/script-flush.md deleted file mode 100644 index 438da5f7..00000000 --- a/commands/script-flush.md +++ /dev/null @@ -1,15 +0,0 @@ -Flush the Lua scripts cache. - -By default, `SCRIPT FLUSH` will synchronously flush the cache. -Setting the **lazyfree-lazy-user-flush** configuration directive to "yes" changes the default flush mode to asynchronous. - -It is possible to use one of the following modifiers to dictate the flushing mode explicitly: - -* `ASYNC`: flushes the cache asynchronously -* `SYNC`: flushes the cache synchronously - -For more information about `EVAL` scripts please refer to [Introduction to Eval Scripts](../topics/eval-intro.md). - -## Reply - -`OK`. diff --git a/commands/script-help.md b/commands/script-help.md deleted file mode 100644 index 69935e43..00000000 --- a/commands/script-help.md +++ /dev/null @@ -1,5 +0,0 @@ -The `SCRIPT HELP` command returns a helpful text describing the different subcommands. - -## Reply - -Array of sub-commands and their descriptions. diff --git a/commands/script-kill.md b/commands/script-kill.md deleted file mode 100644 index 6be61a9e..00000000 --- a/commands/script-kill.md +++ /dev/null @@ -1,19 +0,0 @@ -Kills the currently executing [`EVAL`](eval.md) script, assuming no write operation was yet -performed by the script. - -This command is mainly useful to kill a script that is running for too much -time(for instance, because it entered an infinite loop because of a bug). -The script will be killed, and the client currently blocked into EVAL will see -the command returning with an error. - -If the script has already performed write operations, it can not be killed in this -way because it would violate Lua's script atomicity contract. -In such a case, only [`SHUTDOWN NOSAVE`](shutdown.md) can kill the script, killing -the Valkey process in a hard way and preventing it from persisting with half-written -information. - -For more information about `EVAL` scripts please refer to [Introduction to Eval Scripts](../topics/eval-intro.md). - -## Reply - -`OK`. diff --git a/commands/script-load.md b/commands/script-load.md deleted file mode 100644 index d4e42ca4..00000000 --- a/commands/script-load.md +++ /dev/null @@ -1,21 +0,0 @@ -Load a script into the scripts cache, without executing it. -After the specified command is loaded into the script cache it will be callable -using [`EVALSHA`](evalsha.md) with the correct SHA1 digest of the script, exactly like after -the first successful invocation of [`EVAL`](eval.md). - -The script is guaranteed to stay in the script cache forever (unless [`SCRIPT -FLUSH`](script-flush.md) is called). - -The command works in the same way even if the script was already present in the -script cache. - -Scripts loaded with this command are not evicted when the number of cached `EVAL` scripts -or the `maxmemory-scripts` limit is reached. -Starting from Valkey 9.2, `SCRIPT LOAD` is flagged as [`DENYOOM`](command.md#flags): when the server is over -the `maxmemory` limit and can't free memory by eviction, the command is rejected with an out of memory error. - -For more information about `EVAL` scripts please refer to [Introduction to Eval Scripts](../topics/eval-intro.md). - -## Reply - -String: the SHA1 digest of the script added into the script cache. diff --git a/commands/script-show.md b/commands/script-show.md deleted file mode 100644 index 9f451e69..00000000 --- a/commands/script-show.md +++ /dev/null @@ -1,11 +0,0 @@ -Returns the original source code of a script in the script cache. - -This command accepts a SHA1 digest and returns the original script's source code if the script is present in the script cache. -It is intended primary for debugging, allowing users to introspect the contents of a script when they do not have direct access to it. -For example, an admin may only have access to a script's SHA1 from the monitor or slowlog and needs to determine the script's contents for debugging. - -For more information about `EVAL` scripts please refer to [Introduction to Eval Scripts](../topics/eval-intro.md). - -## Reply - -String: Lua script if `sha1` hash exists in script cache. diff --git a/commands/script.md b/commands/script.md deleted file mode 100644 index 7ac90764..00000000 --- a/commands/script.md +++ /dev/null @@ -1,3 +0,0 @@ -This is a container command for script management commands. - -To see the list of available commands you can call [`SCRIPT HELP`](script-help.md). diff --git a/commands/sdiff.md b/commands/sdiff.md deleted file mode 100644 index 6c7858a6..00000000 --- a/commands/sdiff.md +++ /dev/null @@ -1,37 +0,0 @@ -Returns the members of the set resulting from the difference between the first -set and all the successive sets. - -For example: - -``` -key1 = {a,b,c,d} -key2 = {c} -key3 = {a,c,e} -SDIFF key1 key2 key3 = {b,d} -``` - -Keys that do not exist are considered to be empty sets. - -## Reply - -Set: the resulting set. - -## Examples - -``` -127.0.0.1:6379> SADD key1 "a" -(integer) 1 -127.0.0.1:6379> SADD key1 "b" -(integer) 1 -127.0.0.1:6379> SADD key1 "c" -(integer) 1 -127.0.0.1:6379> SADD key2 "c" -(integer) 1 -127.0.0.1:6379> SADD key2 "d" -(integer) 1 -127.0.0.1:6379> SADD key2 "e" -(integer) 1 -127.0.0.1:6379> SDIFF key1 key2 -1) "a" -2) "b" -``` diff --git a/commands/sdiffstore.md b/commands/sdiffstore.md deleted file mode 100644 index 8d3239cc..00000000 --- a/commands/sdiffstore.md +++ /dev/null @@ -1,30 +0,0 @@ -This command is equal to `SDIFF`, but instead of returning the resulting set, it -is stored in `destination`. - -If `destination` already exists, it is overwritten. - -## Reply - -Integer: the number of elements in the resulting set. - -## Examples - -``` -127.0.0.1:6379> SADD key1 "a" -(integer) 1 -127.0.0.1:6379> SADD key1 "b" -(integer) 1 -127.0.0.1:6379> SADD key1 "c" -(integer) 1 -127.0.0.1:6379> SADD key2 "c" -(integer) 1 -127.0.0.1:6379> SADD key2 "d" -(integer) 1 -127.0.0.1:6379> SADD key2 "e" -(integer) 1 -127.0.0.1:6379> SDIFFSTORE key key1 key2 -(integer) 2 -127.0.0.1:6379> SMEMBERS key -1) "a" -2) "b" -``` diff --git a/commands/select.md b/commands/select.md deleted file mode 100644 index 04c70d33..00000000 --- a/commands/select.md +++ /dev/null @@ -1,22 +0,0 @@ -Select the Valkey logical database having the specified zero-based numeric index. -New connections always use the database 0. - -By default, Valkey provides 16 logical databases, indexed from `0` to `15`. -You can increase this number by setting the `databases` parameter in the configuration file. -This change must be made at startup and cannot be modified at runtime. - -Selectable Valkey databases are a form of namespacing: all databases are still persisted in the same RDB / AOF file. However different databases can have keys with the same name, and commands like [`FLUSHDB`](flushdb.md), [`SWAPDB`](swapdb.md) or [`RANDOMKEY`](randomkey.md) work on specific databases. - -In practical terms, Valkey databases should be used to separate different keys belonging to the same application (if needed), and not to use a single Valkey instance for multiple unrelated applications. - -Valkey 9.0 and later supports multiple databases in cluster mode. You can use `SELECT ` to switch between them. - -Since the currently selected database is a property of the connection, clients should track the currently selected database and re-select it on reconnection. - -While there is no dedicated command to query the currently selected database for a connection, you can infer it from the output of [`CLIENT LIST`](client-list.md) or [`CLIENT INFO`](client-info.md), where each client entry includes the `db=N` field indicating the selected database. - -Access to a database can be restricted with ACL [database permissions](../topics/acl.md#database-permissions). New connections always start in database 0 even when the authenticated user is not allowed to access database 0; in that case the client must issue `SELECT` to switch to an allowed database before running any command that accesses the keyspace. If the user does not have access to the target database, `SELECT` fails with a `NOPERM` error and the event is recorded in [`ACL LOG`](acl-log.md). - -## Reply - -`OK`. diff --git a/commands/set.md b/commands/set.md deleted file mode 100644 index 04c7fa9d..00000000 --- a/commands/set.md +++ /dev/null @@ -1,98 +0,0 @@ -Set `key` to hold the string `value`. -If `key` already holds a value, it is overwritten, regardless of its type. -Any previous time to live associated with the key is discarded on successful `SET` operation. - -## Options - -The `SET` command supports a set of options that modify its behavior: - -* `EX` *seconds* -- Set the specified expire time, in seconds (a positive integer). -* `PX` *milliseconds* -- Set the specified expire time, in milliseconds (a positive integer). -* `EXAT` *timestamp-seconds* -- Set the specified Unix time at which the key will expire, in seconds (a positive integer). -* `PXAT` *timestamp-milliseconds* -- Set the specified Unix time at which the key will expire, in milliseconds (a positive integer). -* `NX` -- Only set the key if it does not already exist. -* `XX` -- Only set the key if it already exists. -* `IFEQ` *comparison-value* -- Set the key if the comparison value matches the existing value. An error is returned and `SET` aborted if the value stored at key is not a string. -* `IFNE` *comparison-not-equal* -- Set the key if the comparison value does not match the existing value. If the key does not exist, `IFNE` matches and the key is set. SET aborts if the value stored at key is not a string. -* `KEEPTTL` -- Retain the time to live associated with the key. -* `GET` -- Return the old string stored at key, or nil if key did not exist. An error is returned and `SET` aborted if the value stored at key is not a string. - -Note: Since the `SET` command options can replace `SETNX`, `SETEX`, `PSETEX`, `GETSET`, it is possible that in future versions of Valkey these commands will be deprecated and finally removed. - -## Reply - -If `GET` not given, any of the following: - -* Null: Operation was aborted (conflict with one of the `XX`/`NX` options). -* `OK`: The key was set. - -If `GET` given, any of the following: - -* Null: The key didn't exist before the `SET`. -* String: The previous value of the key. - -Note that when using `GET` together with `XX`/`NX`/`IFEQ`, the reply indirectly indicates whether the key was set: - -* `GET` and `XX` given: Non-null indicates the key was set. -* `GET` and `NX` given: null indicates the key was set. -* `GET` and `IFEQ` given: The key was set if the reply is equal to `comparison-value`. - -## Examples - -Basic usage -``` -127.0.0.1:6379> SET mykey "Hello" -OK -127.0.0.1:6379> GET mykey -"Hello" -``` - -Set a value and an expiry time. -``` -127.0.0.1:6379> SET anotherkey "will expire in a minute" EX 60 -OK -``` - -Conditionally set a value. -``` -127.0.0.1:6379> SET foo "Initial Value" -OK -127.0.0.1:6379> GET foo -"Initial Value" -127.0.0.1:6379> SET foo "New Value" IFEQ "Initial Value" -OK -127.0.0.1:6379> GET foo -"New Value" -``` - -## Patterns - -**Note:** The following pattern is discouraged in favor of [the Redlock algorithm](../topics/distlock.md) which is only a bit more complex to implement, but offers better guarantees and is fault tolerant. - -The command `SET resource-name anystring NX EX max-lock-time` is a simple way to implement a locking system with Valkey. - -A client can acquire the lock if the above command returns `OK` (or retry after some time if the command returns Nil), and remove the lock just using `DEL`. - -The lock will be auto-released after the expire time is reached. - -It is possible to make this system more robust modifying the unlock schema as follows: - -* Instead of setting a fixed string, set a non-guessable large random string, called token. -* Instead of releasing the lock with `DEL`, send a script that only removes the key if the value matches. - -This avoids that a client will try to release the lock after the expire time deleting the key created by another client that acquired the lock later. - -An example of unlock script would be similar to the following: - - if server.call("get",KEYS[1]) == ARGV[1] - then - return server.call("del",KEYS[1]) - else - return 0 - end - -The script should be called with `EVAL ...script... 1 resource-name token-value` - -## See also - -* [`DELIFEQ`](delifeq.md) - Deletes the key if its value matches the given string. diff --git a/commands/setbit.md b/commands/setbit.md deleted file mode 100644 index 0f43d34f..00000000 --- a/commands/setbit.md +++ /dev/null @@ -1,164 +0,0 @@ -Sets or clears the bit at _offset_ in the string value stored at _key_. - -The bit is either set or cleared depending on _value_, which can be either 0 or -1. - -When _key_ does not exist, a new string value is created. -The string is grown to make sure it can hold a bit at _offset_. -The _offset_ argument is required to be greater than or equal to 0, and smaller -than 2^32 (this limits bitmaps to 512MB). -When the string at _key_ is grown, added bits are set to 0. - -**Warning**: When setting the last possible bit (_offset_ equal to 2^32 -1) and -the string value stored at _key_ does not yet hold a string value, or holds a -small string value, Valkey needs to allocate all intermediate memory which can -block the server for some time. -On a 2010 MacBook Pro, setting bit number 2^32 -1 (512MB allocation) takes -~300ms, setting bit number 2^30 -1 (128MB allocation) takes ~80ms, setting bit -number 2^28 -1 (32MB allocation) takes ~30ms and setting bit number 2^26 -1 (8MB -allocation) takes ~8ms. -Note that once this first allocation is done, subsequent calls to `SETBIT` for -the same _key_ will not have the allocation overhead. - -## Reply - -Integer: the original bit value stored at _offset_. - -## Examples - -``` -127.0.0.1:6379> SETBIT mykey 7 1 -(integer) 0 -127.0.0.1:6379> SETBIT mykey 7 0 -(integer) 1 -127.0.0.1:6379> GET mykey -"\x00" -``` - -## Pattern: accessing the entire bitmap - -There are cases when you need to set all the bits of single bitmap at once, for -example when initializing it to a default non-zero value. It is possible to do -this with multiple calls to the `SETBIT` command, one for each bit that needs to -be set. However, so as an optimization you can use a single [`SET`](set.md) command to set -the entire bitmap. - -Bitmaps are not an actual data type, but a set of bit-oriented operations -defined on the String type (for more information refer to the -[Bitmaps section of the Data Types Introduction page][ti]). This means that -bitmaps can be used with string commands, and most importantly with [`SET`](set.md) and -[`GET`](get.md). - -Because Valkey' strings are binary-safe, a bitmap is trivially encoded as a bytes -stream. The first byte of the string corresponds to offsets 0..7 of -the bitmap, the second byte to the 8..15 range, and so forth. - -For example, after setting a few bits, getting the string value of the bitmap -would look like this: - -``` -> SETBIT bitmapsarestrings 2 1 -> SETBIT bitmapsarestrings 3 1 -> SETBIT bitmapsarestrings 5 1 -> SETBIT bitmapsarestrings 10 1 -> SETBIT bitmapsarestrings 11 1 -> SETBIT bitmapsarestrings 14 1 -> GET bitmapsarestrings -"42" -``` - -By getting the string representation of a bitmap, the client can then parse the -response's bytes by extracting the bit values using native bit operations in its -native programming language. Symmetrically, it is also possible to set an entire -bitmap by performing the bits-to-bytes encoding in the client and calling `SET` -with the resultant string. - -[ti]: ../topics/data-types.md#bitmaps - -## Pattern: setting multiple bits - -`SETBIT` excels at setting single bits, and can be called several times when -multiple bits need to be set. To optimize this operation you can replace -multiple `SETBIT` calls with a single call to the variadic [`BITFIELD`](bitfield.md) command -and the use of fields of type `u1`. - -For example, the example above could be replaced by: - -``` -> BITFIELD bitsinabitmap SET u1 2 1 SET u1 3 1 SET u1 5 1 SET u1 10 1 SET u1 11 1 SET u1 14 1 -``` - -## Advanced Pattern: accessing bitmap ranges - -It is also possible to use the [`GETRANGE`](getrange.md) and [`SETRANGE`](setrange.md) string commands to -efficiently access a range of bit offsets in a bitmap. Below is a sample -implementation in idiomatic Valkey Lua scripting that can be run with the [`EVAL`](eval.md) -command: - -``` ---[[ -Sets a bitmap range - -Bitmaps are stored as Strings in Valkey. A range spans one or more bytes, -so we can call `SETRANGE` when entire bytes need to be set instead of flipping -individual bits. Also, to avoid multiple internal memory allocations in -Valkey, we traverse in reverse. -Expected input: - KEYS[1] - bitfield key - ARGV[1] - start offset (0-based, inclusive) - ARGV[2] - end offset (same, should be bigger than start, no error checking) - ARGV[3] - value (should be 0 or 1, no error checking) -]]-- - --- A helper function to stringify a binary string to semi-binary format -local function tobits(str) - local r = '' - for i = 1, string.len(str) do - local c = string.byte(str, i) - local b = ' ' - for j = 0, 7 do - b = tostring(bit.band(c, 1)) .. b - c = bit.rshift(c, 1) - end - r = r .. b - end - return r -end - --- Main -local k = KEYS[1] -local s, e, v = tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3]) - --- First treat the dangling bits in the last byte -local ms, me = s % 8, (e + 1) % 8 -if me > 0 then - local t = math.max(e - me + 1, s) - for i = e, t, -1 do - server.call('SETBIT', k, i, v) - end - e = t -end - --- Then the danglings in the first byte -if ms > 0 then - local t = math.min(s - ms + 7, e) - for i = s, t, 1 do - server.call('SETBIT', k, i, v) - end - s = t + 1 -end - --- Set a range accordingly, if at all -local rs, re = s / 8, (e + 1) / 8 -local rl = re - rs -if rl > 0 then - local b = '\255' - if 0 == v then - b = '\0' - end - server.call('SETRANGE', k, rs, string.rep(b, rl)) -end -``` - -**Note:** the implementation for getting a range of bit offsets from a bitmap is -left as an exercise to the reader. diff --git a/commands/setex.md b/commands/setex.md deleted file mode 100644 index 51bb4750..00000000 --- a/commands/setex.md +++ /dev/null @@ -1,31 +0,0 @@ -Set `key` to hold the string `value` and set `key` to timeout after a given -number of seconds. -This command is equivalent to: - -``` -SET key value EX seconds -``` - -An error is returned when `seconds` is invalid. - -## Alternative - -`SET` with the `EX` argument. - -## Reply - -`OK`. - -## Examples - -``` -127.0.0.1:6379> SETEX mykey 10 "Hello" -OK -127.0.0.1:6379> TTL mykey -(integer) 10 -127.0.0.1:6379> GET mykey -"Hello" -``` -## See also - -`TTL` \ No newline at end of file diff --git a/commands/setnx.md b/commands/setnx.md deleted file mode 100644 index 1a43daa7..00000000 --- a/commands/setnx.md +++ /dev/null @@ -1,106 +0,0 @@ -Set `key` to hold string `value` if `key` does not exist. -In that case, it is equal to `SET`. -When `key` already holds a value, no operation is performed. -`SETNX` is short for "**SET** if **N**ot e**X**ists". - -## Alternative - -`SET` with the `NX` argument. - -## Reply - -One of the following: - -* Integer: `0` if the key was not set. -* Integer: `1` if the key was set. - -## Examples - -``` -127.0.0.1:6379> SETNX mykey "Hello" -(integer) 1 -127.0.0.1:6379> SETNX mykey "World" -(integer) 0 -127.0.0.1:6379> GET mykey -"Hello" -``` - -## Design pattern: Locking with `!SETNX` - -**Please note that:** - -1. The following pattern is discouraged in favor of [the Redlock algorithm](../topics/distlock.md) which is only a bit more complex to implement, but offers better guarantees and is fault tolerant. -2. We document the old pattern anyway because certain existing implementations link to this page as a reference. Moreover it is an interesting example of how Valkey commands can be used in order to mount programming primitives. -3. Anyway even assuming a single-instance locking primitive, starting with 2.6.12 it is possible to create a much simpler locking primitive, equivalent to the one discussed here, using the `SET` command to acquire the lock, and a simple Lua script to release the lock. The pattern is documented in the `SET` command page. - -That said, `SETNX` can be used, and was historically used, as a locking primitive. For example, to acquire the lock of the key `foo`, the client could try the -following: - -``` -SETNX lock.foo -``` - -If `SETNX` returns `1` the client acquired the lock, setting the `lock.foo` key -to the Unix time at which the lock should no longer be considered valid. -The client will later use `DEL lock.foo` in order to release the lock. - -If `SETNX` returns `0` the key is already locked by some other client. -We can either return to the caller if it's a non blocking lock, or enter a loop -retrying to hold the lock until we succeed or some kind of timeout expires. - -### Handling deadlocks - -In the above locking algorithm there is a problem: what happens if a client -fails, crashes, or is otherwise not able to release the lock? -It's possible to detect this condition because the lock key contains a UNIX -timestamp. -If such a timestamp is equal to the current Unix time the lock is no longer -valid. - -When this happens we can't just call `DEL` against the key to remove the lock -and then try to issue a `SETNX`, as there is a race condition here, when -multiple clients detected an expired lock and are trying to release it. - -* C1 and C2 read `lock.foo` to check the timestamp, because they both received - `0` after executing `SETNX`, as the lock is still held by C3 that crashed - after holding the lock. -* C1 sends `DEL lock.foo` -* C1 sends `SETNX lock.foo` and it succeeds -* C2 sends `DEL lock.foo` -* C2 sends `SETNX lock.foo` and it succeeds -* **ERROR**: both C1 and C2 acquired the lock because of the race condition. - -Fortunately, it's possible to avoid this issue using the following algorithm. -Let's see how C4, our sane client, uses the good algorithm: - -* C4 sends `SETNX lock.foo` in order to acquire the lock - -* The crashed client C3 still holds it, so Valkey will reply with `0` to C4. - -* C4 sends `GET lock.foo` to check if the lock expired. - If it is not, it will sleep for some time and retry from the start. - -* Instead, if the lock is expired because the Unix time at `lock.foo` is older - than the current Unix time, C4 tries to perform: - - ``` - GETSET lock.foo - ``` - -* Because of the `GETSET` semantic, C4 can check if the old value stored at - `key` is still an expired timestamp. - If it is, the lock was acquired. - -* If another client, for instance C5, was faster than C4 and acquired the lock - with the `GETSET` operation, the C4 `GETSET` operation will return a non - expired timestamp. - C4 will simply restart from the first step. - Note that even if C4 set the key a bit a few seconds in the future this is - not a problem. - -In order to make this locking algorithm more robust, a -client holding a lock should always check the timeout didn't expire before -unlocking the key with `DEL` because client failures can be complex, not just -crashing but also blocking a lot of time against some operations and trying -to issue `DEL` after a lot of time (when the LOCK is already held by another -client). diff --git a/commands/setrange.md b/commands/setrange.md deleted file mode 100644 index 85772858..00000000 --- a/commands/setrange.md +++ /dev/null @@ -1,53 +0,0 @@ -Overwrites part of the string stored at _key_, starting at the specified offset, -for the entire length of _value_. -If the offset is larger than the current length of the string at _key_, the -string is padded with zero-bytes to make _offset_ fit. -Non-existing keys are considered as empty strings, so this command will make -sure it holds a string large enough to be able to set _value_ at _offset_. - -Note that the maximum offset that you can set is 2^29 -1 (536870911), as Valkey -Strings are limited to 512 megabytes. -If you need to grow beyond this size, you can use multiple keys. - -**Warning**: When setting the last possible byte and the string value stored at -_key_ does not yet hold a string value, or holds a small string value, Valkey -needs to allocate all intermediate memory which can block the server for some -time. -On a 2010 MacBook Pro, setting byte number 536870911 (512MB allocation) takes -~300ms, setting byte number 134217728 (128MB allocation) takes ~80ms, setting -bit number 33554432 (32MB allocation) takes ~30ms and setting bit number 8388608 -(8MB allocation) takes ~8ms. -Note that once this first allocation is done, subsequent calls to `SETRANGE` for -the same _key_ will not have the allocation overhead. - -## Patterns - -Thanks to `SETRANGE` and the analogous `GETRANGE` commands, you can use Valkey -strings as a linear array with O(1) random access. -This is a very fast and efficient storage in many real world use cases. - -## Reply - -Integer: the length of the string after it was modified by the command. - -## Examples - -Basic usage: - -``` -127.0.0.1:6379> SET key1 "Hello World" -OK -127.0.0.1:6379> SETRANGE key1 6 "Valkey" -(integer) 12 -127.0.0.1:6379> GET key1 -"Hello Valkey" -``` - -Example of zero padding: - -``` -127.0.0.1:6379> SETRANGE key2 6 "Valkey" -(integer) 12 -127.0.0.1:6379> GET key2 -"\x00\x00\x00\x00\x00\x00Valkey" -``` diff --git a/commands/shutdown.md b/commands/shutdown.md deleted file mode 100644 index 3996e72d..00000000 --- a/commands/shutdown.md +++ /dev/null @@ -1,76 +0,0 @@ -The command behavior is the following: - -* If there are any replicas lagging behind in replication: - * Pause clients attempting to write by performing a [`CLIENT PAUSE`](client-pause.md) with the `WRITE` option. - * Wait up to the configured `shutdown-timeout` (default 10 seconds) for replicas to catch up the replication offset. -* Stop all the clients. -* Perform a blocking SAVE if at least one **save point** is configured. -* Flush the Append Only File if AOF is enabled. -* Quit the server. - -If persistence is enabled this commands makes sure that Valkey is switched off -without any data loss. - -Note: A Valkey instance that is configured for not persisting on disk (no AOF -configured, nor "save" directive) will not dump the RDB file on `SHUTDOWN`, as -usually you don't want Valkey instances used only for caching to block on when -shutting down. - -Also note: If Valkey receives one of the signals `SIGTERM` and `SIGINT`, the same shutdown sequence is performed. -See also [Signal Handling](../topics/signals.md). - -## Modifiers - -It is possible to specify optional modifiers to alter the behavior of the command. -Specifically: - -* **SAVE** will force a DB saving operation even if no save points are configured. -* **NOSAVE** will prevent a DB saving operation even if one or more save points are configured. -* **NOW** skips waiting for lagging replicas, i.e. it bypasses the first step in the shutdown sequence. -* **FORCE** ignores any errors that would normally prevent the server from exiting. - For details, see the following section. -* **SAFE** will return an error if it is unsafe to shut down. - For details, see the following section. -* **FAILOVER** will trigger a failover before shutting down a primary node in a cluster. -* **ABORT** cancels an ongoing shutdown and cannot be combined with other flags. - -## Conditions where a SHUTDOWN fails - -When a save point is configured or the `SAVE` modifier is specified, the shutdown may fail if the RDB file can't be saved. -Then, the server continues to run in order to ensure no data loss. -This may be bypassed using the `FORCE` modifier, causing the server to exit anyway. - -When the Append Only File is enabled the shutdown may fail because the -system is in a state that does not allow to safely immediately persist -on disk. - -Normally if there is an AOF child process performing an AOF rewrite, Valkey -will simply kill it and exit. -However, there are situations where it is unsafe to do so and, unless the `FORCE` modifier is specified, the `SHUTDOWN` command will be refused with an error instead. -This happens in the following situations: - -* The user just turned on AOF, and the server triggered the first AOF rewrite in order to create the initial AOF file. In this context, stopping will result in losing the dataset at all: once restarted, the server will potentially have AOF enabled without having any AOF file at all. -* A replica with AOF enabled, reconnected with its primary, performed a full resynchronization, and restarted the AOF file, triggering the initial AOF creation process. In this case not completing the AOF rewrite is dangerous because the latest dataset received from the primary would be lost. The new primary can actually be even a different instance (if the [`REPLICAOF`](replicaof.md) or [`SLAVEOF`](slaveof.md) command was used in order to reconfigure the replica), so it is important to finish the AOF rewrite and start with the correct data set representing the data set in memory when the server was terminated. - -When the **SAFE** modifier is specified, the shutdown may fail if the Valkey instance is in an unsafe situation. -Unless the **FORCE** modifier is specified, the **SHUTDOWN** command will be refused with an error instead. -This happens in the following situations: - -* In cluster mode, if the instance is a primary node and is responsible for at least one slot, shutting down such a node will cause the cluster to fail, so **SAFE** will refuse to shut down. - -There are situations when we want just to terminate a Valkey instance ASAP, regardless of what its content is. -In such a case, the command `SHUTDOWN NOW NOSAVE FORCE` can be used. -In versions before 7.0, where the `NOW` and `FORCE` flags are not available, the right combination of commands is to send a [`CONFIG appendonly no`](config.md) followed by a `SHUTDOWN NOSAVE`. -The first command will turn off the AOF if needed, and will terminate the AOF rewriting child if there is one active. -The second command will not have any problem to execute since the AOF is no longer enabled. - -## Minimize the risk of data loss - -The server waits for lagging replicas up to a configurable `shutdown-timeout`, by default 10 seconds, before shutting down. -This provides a best effort minimizing the risk of data loss in a situation where no save points are configured and AOF is disabled. -Before version 7.0, shutting down a heavily loaded primary node in a diskless setup was more likely to result in data loss. -To minimize the risk of data loss in such setups, it's advised to trigger a manual [`FAILOVER`](failover.md) (or [`CLUSTER FAILOVER`](cluster-failover.md)) to demote the primary to a replica and promote one of the replicas to be the new primary, before shutting down a primary node. - -## Reply - -`OK` if _ABORT_ was specified and shutdown was aborted. On successful shutdown, nothing is returned because the server quits and the connection is closed. On failure, an error is returned. diff --git a/commands/sinter.md b/commands/sinter.md deleted file mode 100644 index 113424c3..00000000 --- a/commands/sinter.md +++ /dev/null @@ -1,38 +0,0 @@ -Returns the members of the set resulting from the intersection of all the given -sets. - -For example: - -``` -key1 = {a,b,c,d} -key2 = {c} -key3 = {a,c,e} -SINTER key1 key2 key3 = {c} -``` - -Keys that do not exist are considered to be empty sets. -With one of the keys being an empty set, the resulting set is also empty (since -set intersection with an empty set always results in an empty set). - -## Reply - -Set: the resulting set. - -## Examples - -``` -127.0.0.1:6379> SADD key1 "a" -(integer) 1 -127.0.0.1:6379> SADD key1 "b" -(integer) 1 -127.0.0.1:6379> SADD key1 "c" -(integer) 1 -127.0.0.1:6379> SADD key2 "c" -(integer) 1 -127.0.0.1:6379> SADD key2 "d" -(integer) 1 -127.0.0.1:6379> SADD key2 "e" -(integer) 1 -127.0.0.1:6379> SINTER key1 key2 -1) "c" -``` diff --git a/commands/sintercard.md b/commands/sintercard.md deleted file mode 100644 index c0648d6f..00000000 --- a/commands/sintercard.md +++ /dev/null @@ -1,39 +0,0 @@ -This command is similar to `SINTER`, but instead of returning the result set, it returns just the cardinality of the result. -Returns the cardinality of the set which would result from the intersection of all the given sets. - -Keys that do not exist are considered to be empty sets. -With one of the keys being an empty set, the resulting set is also empty (since set intersection with an empty set always results in an empty set). - -By default, the command calculates the cardinality of the intersection of all given sets. -When provided with the optional `LIMIT` argument (which defaults to 0 and means unlimited), if the intersection cardinality reaches limit partway through the computation, the algorithm will exit and yield limit as the cardinality. -Such implementation ensures a significant speedup for queries where the limit is lower than the actual intersection cardinality. - -## Reply - -Integer: the number of elements in the resulting intersection. - -## Examples - -``` -127.0.0.1:6379> SADD key1 "a" -(integer) 1 -127.0.0.1:6379> SADD key1 "b" -(integer) 1 -127.0.0.1:6379> SADD key1 "c" -(integer) 1 -127.0.0.1:6379> SADD key1 "d" -(integer) 1 -127.0.0.1:6379> SADD key2 "c" -(integer) 1 -127.0.0.1:6379> SADD key2 "d" -(integer) 1 -127.0.0.1:6379> SADD key2 "e" -(integer) 1 -127.0.0.1:6379> SINTER key1 key2 -1) "c" -2) "d" -127.0.0.1:6379> SINTERCARD 2 key1 key2 -(integer) 2 -127.0.0.1:6379> SINTERCARD 2 key1 key2 LIMIT 1 -(integer) 1 -``` diff --git a/commands/sinterstore.md b/commands/sinterstore.md deleted file mode 100644 index 6b91d0db..00000000 --- a/commands/sinterstore.md +++ /dev/null @@ -1,29 +0,0 @@ -This command is equal to `SINTER`, but instead of returning the resulting set, -it is stored in `destination`. - -If `destination` already exists, it is overwritten. - -## Reply - -Integer: the number of elements in the resulting set. - -## Examples - -``` -127.0.0.1:6379> SADD key1 "a" -(integer) 1 -127.0.0.1:6379> SADD key1 "b" -(integer) 1 -127.0.0.1:6379> SADD key1 "c" -(integer) 1 -127.0.0.1:6379> SADD key2 "c" -(integer) 1 -127.0.0.1:6379> SADD key2 "d" -(integer) 1 -127.0.0.1:6379> SADD key2 "e" -(integer) 1 -127.0.0.1:6379> SINTERSTORE key key1 key2 -(integer) 1 -127.0.0.1:6379> SMEMBERS key -1) "c" -``` diff --git a/commands/sismember.md b/commands/sismember.md deleted file mode 100644 index 9ee7c47a..00000000 --- a/commands/sismember.md +++ /dev/null @@ -1,19 +0,0 @@ -Returns if `member` is a member of the set stored at `key`. - -## Reply - -One of the following: - -* Integer: `0` if the element is not a member of the set, or when the key does not exist. -* Integer: `1` if the element is a member of the set. - -## Examples - -``` -127.0.0.1:6379> SADD myset "one" -(integer) 1 -127.0.0.1:6379> SISMEMBER myset "one" -(integer) 1 -127.0.0.1:6379> SISMEMBER myset "two" -(integer) 0 -``` diff --git a/commands/slaveof.md b/commands/slaveof.md deleted file mode 100644 index 3bbf1c6d..00000000 --- a/commands/slaveof.md +++ /dev/null @@ -1,22 +0,0 @@ -**A note about the word slave used in this man page and command name**: If not for backward compatibility, the Valkey project no longer uses the words "master" and "slave". Please use the new command `REPLICAOF`. The command `SLAVEOF` will continue to work for backward compatibility. - -The `SLAVEOF` command can change the replication settings of a replica on the fly. -If a Valkey server is already acting as replica, the command `SLAVEOF` NO ONE will -turn off the replication, turning the Valkey server into a MASTER. -In the proper form `SLAVEOF` hostname port will make the server a replica of -another server listening at the specified hostname and port. - -If a server is already a replica of some primary, `SLAVEOF` hostname port will stop -the replication against the old server and start the synchronization against the -new one, discarding the old dataset. - -The form `SLAVEOF` NO ONE will stop replication, turning the server into a -MASTER, but will not discard the replication. -So, if the old primary stops working, it is possible to turn the replica into a -primary and set the application to use this new primary in read/write. -Later when the other Valkey server is fixed, it can be reconfigured to work as a -replica. - -## Reply - -`OK`. diff --git a/commands/slowlog-get.md b/commands/slowlog-get.md deleted file mode 100644 index 36b589fa..00000000 --- a/commands/slowlog-get.md +++ /dev/null @@ -1,30 +0,0 @@ -The `SLOWLOG GET` command returns entries from the slow log in chronological order. - -The Valkey Slow Log is a system to log queries that exceeded a specified execution time. -The execution time does not include I/O operations like talking with the client, sending the reply and so forth, but just the time needed to actually execute the command (this is the only stage of command execution where the thread is blocked and can not serve other requests in the meantime). - -A new entry is added to the slow log whenever a command exceeds the execution time threshold defined by the `slowlog-log-slower-than` configuration directive. -The maximum number of entries in the slow log is governed by the `slowlog-max-len` configuration directive. - -By default the command returns latest ten entries in the log. The optional `count` argument limits the number of returned entries, so the command returns at most up to `count` entries, the special number -1 means return all entries. - -Each entry from the slow log is comprised of the following six values: - -1. A unique progressive identifier for every slow log entry. -2. The unix timestamp at which the logged command was processed. -3. The amount of time needed for its execution, in microseconds. -4. The array composing the arguments of the command. -5. Client IP address and port. -6. Client name if set via the `CLIENT SETNAME` command. - -The entry's unique ID can be used in order to avoid processing slow log entries multiple times (for instance you may have a script sending you an email alert for every new slow log entry). -The ID is never reset in the course of the Valkey server execution, only a server -restart will reset it. - -## Alternative - -`COMMANDLOG GET SLOW`. - -## Reply - -Array of slow log entries per the above format. diff --git a/commands/slowlog-help.md b/commands/slowlog-help.md deleted file mode 100644 index 8bac780b..00000000 --- a/commands/slowlog-help.md +++ /dev/null @@ -1,9 +0,0 @@ -The `SLOWLOG HELP` command returns a helpful text describing the different subcommands. - -## Alternative - -`COMMANDLOG HELP` - -## Reply - -Array of sub-commands and their descriptions. diff --git a/commands/slowlog-len.md b/commands/slowlog-len.md deleted file mode 100644 index b730a6e3..00000000 --- a/commands/slowlog-len.md +++ /dev/null @@ -1,14 +0,0 @@ -This command returns the current number of entries in the slow log. - -A new entry is added to the slow log whenever a command exceeds the execution time threshold defined by the `slowlog-log-slower-than` configuration directive. -The maximum number of entries in the slow log is governed by the `slowlog-max-len` configuration directive. -Once the slog log reaches its maximal size, the oldest entry is removed whenever a new entry is created. -The slow log can be cleared with the `SLOWLOG RESET` command. - -## Alternative - -`COMMANDLOG LEN SLOW` - -## Reply - -Integer: the number of entries in the slow log. diff --git a/commands/slowlog-reset.md b/commands/slowlog-reset.md deleted file mode 100644 index bca79ff6..00000000 --- a/commands/slowlog-reset.md +++ /dev/null @@ -1,11 +0,0 @@ -This command resets the slow log, clearing all entries in it. - -Once deleted the information is lost forever. - -## Alternative - -`COMMANDLOG RESET SLOW` - -## Reply - -`OK`. diff --git a/commands/slowlog.md b/commands/slowlog.md deleted file mode 100644 index 3a530099..00000000 --- a/commands/slowlog.md +++ /dev/null @@ -1,7 +0,0 @@ -This is a container command for slow log management commands. - -To see the list of available commands you can call `SLOWLOG HELP`. - -## Alternative - -`COMMANDLOG` diff --git a/commands/smembers.md b/commands/smembers.md deleted file mode 100644 index 5766bd00..00000000 --- a/commands/smembers.md +++ /dev/null @@ -1,19 +0,0 @@ -Returns all the members of the set value stored at `key`. - -This has the same effect as running `SINTER` with one argument `key`. - -## Reply - -Set: all members of the set. - -## Examples - -``` -127.0.0.1:6379> SADD myset "Hello" -(integer) 1 -127.0.0.1:6379> SADD myset "World" -(integer) 1 -127.0.0.1:6379> SMEMBERS myset -1) "Hello" -2) "World" -``` diff --git a/commands/smismember.md b/commands/smismember.md deleted file mode 100644 index a91dbf61..00000000 --- a/commands/smismember.md +++ /dev/null @@ -1,19 +0,0 @@ -Returns whether each `member` is a member of the set stored at `key`. - -For every `member`, `1` is returned if the value is a member of the set, or `0` if the element is not a member of the set or if `key` does not exist. - -## Reply - -Array representing the membership of the given elements, in the same order as they are requested. - -## Examples - -``` -127.0.0.1:6379> SADD myset "one" -(integer) 1 -127.0.0.1:6379> SADD myset "one" -(integer) 0 -127.0.0.1:6379> SMISMEMBER myset "one" "notamember" -1) (integer) 1 -2) (integer) 0 -``` diff --git a/commands/smove.md b/commands/smove.md deleted file mode 100644 index d6c9ad64..00000000 --- a/commands/smove.md +++ /dev/null @@ -1,38 +0,0 @@ -Move `member` from the set at `source` to the set at `destination`. -This operation is atomic. -In every given moment the element will appear to be a member of `source` **or** -`destination` for other clients. - -If the source set does not exist or does not contain the specified element, no -operation is performed and `0` is returned. -Otherwise, the element is removed from the source set and added to the -destination set. -When the specified element already exists in the destination set, it is only -removed from the source set. - -An error is returned if `source` or `destination` does not hold a set value. - -## Reply - -One of the following: - -* Integer: `1` if the element is moved. -* Integer: `0` if the element is not a member of _source_ and no operation was performed. - -## Examples - -``` -127.0.0.1:6379> SADD myset "one" -(integer) 1 -127.0.0.1:6379> SADD myset "two" -(integer) 1 -127.0.0.1:6379> SADD myotherset "three" -(integer) 1 -127.0.0.1:6379> SMOVE myset myotherset "two" -(integer) 1 -127.0.0.1:6379> SMEMBERS myset -1) "one" -127.0.0.1:6379> SMEMBERS myotherset -1) "three" -2) "two" -``` diff --git a/commands/sort.md b/commands/sort.md deleted file mode 100644 index 650acfa6..00000000 --- a/commands/sort.md +++ /dev/null @@ -1,158 +0,0 @@ -Returns or stores the elements contained in the [list][tdtl], [set][tdts] or -[sorted set][tdtss] at `key`. - -There is also the [`SORT_RO`](sort_ro.md) read-only variant of this command. - -By default, sorting is numeric and elements are compared by their value -interpreted as double precision floating point number. -This is `SORT` in its simplest form: - -[tdtl]: ../topics/data-types.md#lists -[tdts]: ../topics/data-types.md#sets -[tdtss]: ../topics/data-types.md#sorted-sets - -``` -SORT mylist -``` - -Assuming `mylist` is a list of numbers, this command will return the same list -with the elements sorted from small to large. -In order to sort the numbers from large to small, use the `DESC` modifier: - -``` -SORT mylist DESC -``` - -When `mylist` contains string values and you want to sort them -lexicographically, use the `ALPHA` modifier: - -``` -SORT mylist ALPHA -``` - -Valkey is UTF-8 aware, assuming you correctly set the `LC_COLLATE` environment -variable or the `locale-collate` config. - -The number of returned elements can be limited using the `LIMIT` modifier. -This modifier takes the `offset` argument, specifying the number of elements to -skip and the `count` argument, specifying the number of elements to return from -starting at `offset`. -The following example will return 10 elements of the sorted version of `mylist`, -starting at element 0 (`offset` is zero-based): - -``` -SORT mylist LIMIT 0 10 -``` - -Almost all modifiers can be used together. -The following example will return the first 5 elements, lexicographically sorted -in descending order: - -``` -SORT mylist LIMIT 0 5 ALPHA DESC -``` - -## Sorting by external keys - -Sometimes you want to sort elements using external keys as weights to compare -instead of comparing the actual elements in the list, set or sorted set. -Let's say the list `mylist` contains the elements `1`, `2` and `3` representing -unique IDs of objects stored in `object_1`, `object_2` and `object_3`. -When these objects have associated weights stored in `weight_1`, `weight_2` and -`weight_3`, `SORT` can be instructed to use these weights to sort `mylist` with -the following statement: - -``` -SORT mylist BY weight_* -``` - -The `BY` option takes a pattern (equal to `weight_*` in this example) that is -used to generate the keys that are used for sorting. -These key names are obtained substituting the first occurrence of `*` with the -actual value of the element in the list (`1`, `2` and `3` in this example). - -## Skip sorting the elements - -The `BY` option can also take a non-existent key, which causes `SORT` to skip -the sorting operation. -This is useful if you want to retrieve external keys (see the `GET` option -below) without the overhead of sorting. - -``` -SORT mylist BY nosort -``` - -## Retrieving external keys - -Our previous example returns just the sorted IDs. -In some cases, it is more useful to get the actual objects instead of their IDs -(`object_1`, `object_2` and `object_3`). -Retrieving external keys based on the elements in a list, set or sorted set can -be done with the following command: - -``` -SORT mylist BY weight_* GET object_* -``` - -The `GET` option can be used multiple times in order to get more keys for every -element of the original list, set or sorted set. - -It is also possible to `GET` the element itself using the special pattern `#`: - -``` -SORT mylist BY weight_* GET object_* GET # -``` - -## Restrictions for using external keys - -Before 8.0, when enabling Valkey `cluster-mode` there is no way to guarantee the existence of the external keys on the node which the command is processed on. In this case, any use of `GET` or `BY` which reference external key pattern will cause the command to fail with an error. - -Starting from 8.0, pattern with hash tag can be mapped to a slot, and so in Valkey `cluster-mode`, the use of `BY` or `GET` is allowed when pattern contains hash tag and implies a specific slot which the key is also in, which means any key matching this pattern must be in the same slot as the key, and therefore in the same node. For example, in cluster mode, `{mylist}weight_*` is acceptable as a pattern when sorting `mylist`, while pattern `{abc}weight_*` will be denied, causing the command to fail with an error. - -To use pattern with hash tag, see [Hash tags](../topics/cluster-spec.md#hash-tags) for more information. - -Any use of `GET` or `BY` which reference external key pattern will only be allowed in case the current user running the command has full key read permissions. -Full key read permissions can be set for the user by, for example, specifying `'%R~*'` or `'~*` with the relevant command access rules. -You can check the [`ACL SETUSER`](acl-setuser.md) command manual for more information on setting ACL access rules. -If full key read permissions aren't set, the command will fail with an error. - -## Storing the result of a SORT operation - -By default, `SORT` returns the sorted elements to the client. -With the `STORE` option, the result will be stored as a list at the specified -key instead of being returned to the client. - -``` -SORT mylist BY weight_* STORE resultkey -``` - -An interesting pattern using `SORT ... STORE` consists in associating an -`EXPIRE` timeout to the resulting key so that in applications where the result -of a `SORT` operation can be cached for some time. -Other clients will use the cached list instead of calling `SORT` for every -request. -When the key will timeout, an updated version of the cache can be created by -calling `SORT ... STORE` again. - -Note that for correctly implementing this pattern it is important to avoid -multiple clients rebuilding the cache at the same time. -Some kind of locking is needed here (for instance using [`SETNX`](setnx.md)). - -## Using hashes in `BY` and `GET` - -It is possible to use `BY` and `GET` options against hash fields with the -following syntax: - -``` -SORT mylist BY weight_*->fieldname GET object_*->fieldname -``` - -The string `->` is used to separate the key name from the hash field name. -The key is substituted as documented above, and the hash stored at the resulting -key is accessed to retrieve the specified hash field. - -## Reply - -Array: without passing the _STORE_ option, the command returns a list of sorted elements. - -Integer: when the _STORE_ option is specified, the command returns the number of sorted elements in the destination list. diff --git a/commands/sort_ro.md b/commands/sort_ro.md deleted file mode 100644 index 1e97fd50..00000000 --- a/commands/sort_ro.md +++ /dev/null @@ -1,17 +0,0 @@ -Read-only variant of the [`SORT`](sort.md) command. It is exactly like the original `SORT` but refuses the `STORE` option and can safely be used in read-only replicas. - -Since the original `SORT` has a `STORE` option it is technically flagged as a writing command in the Valkey command table. For this reason read-only replicas in a Valkey Cluster will redirect it to the primary instance even if the connection is in read-only mode (see the [`READONLY`](readonly.md) command of Valkey Cluster). - -The `SORT_RO` variant was introduced in order to allow `SORT` behavior in read-only replicas without breaking compatibility on command flags. - -See original `SORT` for more details. - -## Reply - -Array of sorted elements. - -## Examples - -``` -SORT_RO mylist BY weight_*->fieldname GET object_*->fieldname -``` diff --git a/commands/spop.md b/commands/spop.md deleted file mode 100644 index 183f4608..00000000 --- a/commands/spop.md +++ /dev/null @@ -1,44 +0,0 @@ -Removes and returns one or more random members from the set value store at `key`. - -This operation is similar to `SRANDMEMBER`, that returns one or more random elements from a set but does not remove it. - -By default, the command pops a single member from the set. When provided with -the optional `count` argument, the reply will consist of up to `count` members, -depending on the set's cardinality. - -## Reply - -One of the following: - -* Null: if the key does not exist. -* String: when called without the _count_ argument, the removed member. -* Set: when called with the _count_ argument, the set of removed members. - -## Examples - -``` -127.0.0.1:6379> SADD myset "one" -(integer) 1 -127.0.0.1:6379> SADD myset "two" -(integer) 1 -127.0.0.1:6379> SADD myset "three" -(integer) 1 -127.0.0.1:6379> SPOP myset -"three" -127.0.0.1:6379> SMEMBERS myset -1) "one" -2) "two" -127.0.0.1:6379> SADD myset "four" -(integer) 1 -127.0.0.1:6379> SADD myset "five" -(integer) 1 -127.0.0.1:6379> SPOP myset 3 -1) "one" -2) "four" -3) "five" -127.0.0.1:6379> SMEMBERS myset -1) "two" -``` -## Distribution of returned elements - -Note that this command is not suitable when you need a guaranteed uniform distribution of the returned elements. For more information about the algorithms used for `SPOP`, look up both the Knuth sampling and Floyd sampling algorithms. diff --git a/commands/spublish.md b/commands/spublish.md deleted file mode 100644 index 60f5f7d0..00000000 --- a/commands/spublish.md +++ /dev/null @@ -1,20 +0,0 @@ -Posts a message to the given shard channel. - -In Valkey Cluster, shard channels are assigned to slots by the same algorithm used to assign keys to slots. -A shard message must be sent to a node that own the slot the shard channel is hashed to. -The cluster makes sure that published shard messages are forwarded to all the node in the shard, so clients can subscribe to a shard channel by connecting to any one of the nodes in the shard. - -For more information about sharded pubsub, see [Sharded Pubsub](../topics/pubsub.md#sharded-pub-sub). - -## Reply - -Integer: the number of clients that received the message. Note that in a Valkey Cluster, only clients that are connected to the same node as the publishing client are included in the count - -## Examples - -For example the following command publish to channel `orders` with a subscriber already waiting for message(s). - -``` -> spublish orders hello -(integer) 1 -``` diff --git a/commands/srandmember.md b/commands/srandmember.md deleted file mode 100644 index 5bbabc2e..00000000 --- a/commands/srandmember.md +++ /dev/null @@ -1,46 +0,0 @@ -When called with just the `key` argument, return a random element from the set value stored at `key`. - -If the provided `count` argument is positive, return an array of **distinct elements**. -The array's length is either `count` or the set's cardinality (`SCARD`), whichever is lower. - -If called with a negative `count`, the behavior changes and the command is allowed to return the **same element multiple times**. -In this case, the number of returned elements is the absolute value of the specified `count`. - -## Reply - -One of the following: - -* String: without the additional _count_ argument, the command returns a randomly selected member, or a null when _key_ doesn't exist. -* Array: when the optional _count_ argument is passed, the command returns an array of members, or an empty array when _key_ doesn't exist. - -## Examples - -``` -127.0.0.1:6379> SADD myset one two three -(integer) 3 -127.0.0.1:6379> SRANDMEMBER myset -"three" -127.0.0.1:6379> SRANDMEMBER myset 2 -1) "one" -2) "three" -127.0.0.1:6379> SRANDMEMBER myset -5 -1) "two" -2) "one" -3) "one" -4) "one" -5) "two" -``` - -## Specification of the behavior when count is passed - -When the `count` argument is a positive value this command behaves as follows: - -* No repeated elements are returned. -* If `count` is bigger than the set's cardinality, the command will only return the whole set without additional elements. -* The order of elements in the reply is not truly random, so it is up to the client to shuffle them if needed. - -When the `count` is a negative value, the behavior changes as follows: - -* Repeating elements are possible. -* Exactly `count` elements, or an empty array if the set is empty (non-existing key), are always returned. -* The order of elements in the reply is truly random. \ No newline at end of file diff --git a/commands/srem.md b/commands/srem.md deleted file mode 100644 index 69394dab..00000000 --- a/commands/srem.md +++ /dev/null @@ -1,28 +0,0 @@ -Remove the specified members from the set stored at `key`. -Specified members that are not a member of this set are ignored. -If `key` does not exist, it is treated as an empty set and this command returns -`0`. - -An error is returned when the value stored at `key` is not a set. - -## Reply - -Integer: the number of members that were removed from the set, not including non existing members. - -## Examples - -``` -127.0.0.1:6379> SADD myset "one" -(integer) 1 -127.0.0.1:6379> SADD myset "two" -(integer) 1 -127.0.0.1:6379> SADD myset "three" -(integer) 1 -127.0.0.1:6379> SREM myset "one" -(integer) 1 -127.0.0.1:6379> SREM myset "four" -(integer) 0 -127.0.0.1:6379> SMEMBERS myset -1) "two" -2) "three" -``` diff --git a/commands/sscan.md b/commands/sscan.md deleted file mode 100644 index 65ac8108..00000000 --- a/commands/sscan.md +++ /dev/null @@ -1,8 +0,0 @@ -See [`SCAN`](scan.md) for `SSCAN` documentation. - -## Reply - -Array with two elements: - -* The first element is a string that represents an unsigned 64-bit number, the cursor. -* The second element is an array with the names of scanned members. diff --git a/commands/ssubscribe.md b/commands/ssubscribe.md deleted file mode 100644 index b6089a74..00000000 --- a/commands/ssubscribe.md +++ /dev/null @@ -1,25 +0,0 @@ -Subscribes the client to the specified shard channels. - -In a Valkey cluster, shard channels are assigned to slots by the same algorithm used to assign keys to slots. -Client(s) can subscribe to a node covering a slot (primary/replica) to receive the messages published. -All the specified shard channels needs to belong to a single slot to subscribe in a given `SSUBSCRIBE` call, -A client can subscribe to channels across different slots over separate `SSUBSCRIBE` call. - -For more information about sharded Pub/Sub, see [Sharded Pub/Sub](../topics/pubsub.md#sharded-pub-sub). - -## Reply - -When successful, this command doesn't return anything. Instead, for each shard channel, one message with the first element being the string `ssubscribe` is pushed as a confirmation that the command succeeded. Note that this command can also return a -MOVED redirect. - -## Examples - -``` -> ssubscribe orders -Reading messages... (press Ctrl-C to quit) -1) "ssubscribe" -2) "orders" -3) (integer) 1 -1) "smessage" -2) "orders" -3) "hello" -``` diff --git a/commands/strlen.md b/commands/strlen.md deleted file mode 100644 index f16c72bf..00000000 --- a/commands/strlen.md +++ /dev/null @@ -1,17 +0,0 @@ -Returns the length of the string value stored at `key`. -An error is returned when `key` holds a non-string value. - -## Reply - -Integer: the length of the string stored at key, or 0 when the key does not exist. - -## Examples - -``` -127.0.0.1:6379> SET mykey "Hello world" -OK -127.0.0.1:6379> STRLEN mykey -(integer) 11 -127.0.0.1:6379> STRLEN nonexisting -(integer) 0 -``` diff --git a/commands/subscribe.md b/commands/subscribe.md deleted file mode 100644 index 0e2181dc..00000000 --- a/commands/subscribe.md +++ /dev/null @@ -1,14 +0,0 @@ -Subscribes the client to the specified channels. - -Once the client enters the subscribed state it is not supposed to issue any -other commands, except for additional `SUBSCRIBE`, [`SSUBSCRIBE`](ssubscribe.md), [`PSUBSCRIBE`](psubscribe.md), [`UNSUBSCRIBE`](unsubscribe.md), [`SUNSUBSCRIBE`](sunsubscribe.md), -[`PUNSUBSCRIBE`](punsubscribe.md), [`PING`](ping.md), [`RESET`](reset.md) and [`QUIT`](quit.md) commands. -However, if RESP3 is used (see [`HELLO`](hello.md)) it is possible for a client to issue any commands while in subscribed state. - -Note that [`RESET`](reset.md) can be called to exit subscribed state. - -For more information, see [Pub/sub](../topics/pubsub.md). - -## Reply - -When successful, this command doesn't return anything. Instead, for each channel, one message with the first element being the string `subscribe` is pushed as a confirmation that the command succeeded. diff --git a/commands/substr.md b/commands/substr.md deleted file mode 100644 index 109f236e..00000000 --- a/commands/substr.md +++ /dev/null @@ -1,31 +0,0 @@ -Returns the substring of the string value stored at `key`, determined by the -offsets `start` and `end` (both are inclusive). -Negative offsets can be used in order to provide an offset starting from the end -of the string. -So -1 means the last character, -2 the penultimate and so forth. - -The function handles out of range requests by limiting the resulting range to -the actual length of the string. - -## Alternative - -`GETRANGE` - -## Reply - -String: the substring of the string value stored at key, determined by the offsets start and end (both are inclusive). - -## Examples - -``` -127.0.0.1:6379> SET mykey "This is a string" -OK -127.0.0.1:6379> GETRANGE mykey 0 3 -"This" -127.0.0.1:6379> GETRANGE mykey -3 -1 -"ing" -127.0.0.1:6379> GETRANGE mykey 0 -1 -"This is a string" -127.0.0.1:6379> GETRANGE mykey 10 100 -"string" -``` diff --git a/commands/sunion.md b/commands/sunion.md deleted file mode 100644 index 2ece9e78..00000000 --- a/commands/sunion.md +++ /dev/null @@ -1,39 +0,0 @@ -Returns the members of the set resulting from the union of all the given sets. - -For example: - -``` -key1 = {a,b,c,d} -key2 = {c} -key3 = {a,c,e} -SUNION key1 key2 key3 = {a,b,c,d,e} -``` - -Keys that do not exist are considered to be empty sets. - -## Reply - -Set: the resulting set. - -## Examples - -``` -127.0.0.1:6379> SADD key1 "a" -(integer) 1 -127.0.0.1:6379> SADD key1 "b" -(integer) 1 -127.0.0.1:6379> SADD key1 "c" -(integer) 1 -127.0.0.1:6379> SADD key2 "c" -(integer) 1 -127.0.0.1:6379> SADD key2 "d" -(integer) 1 -127.0.0.1:6379> SADD key2 "e" -(integer) 1 -127.0.0.1:6379> SUNION key1 key2 -1) "a" -2) "b" -3) "c" -4) "d" -5) "e" -``` diff --git a/commands/sunionstore.md b/commands/sunionstore.md deleted file mode 100644 index 62052515..00000000 --- a/commands/sunionstore.md +++ /dev/null @@ -1,33 +0,0 @@ -This command is equal to `SUNION`, but instead of returning the resulting set, -it is stored in `destination`. - -If `destination` already exists, it is overwritten. - -## Reply - -Integer: the number of elements in the resulting set. - -## Examples - -``` -127.0.0.1:6379> SADD key1 "a" -(integer) 1 -127.0.0.1:6379> SADD key1 "b" -(integer) 1 -127.0.0.1:6379> SADD key1 "c" -(integer) 1 -127.0.0.1:6379> SADD key2 "c" -(integer) 1 -127.0.0.1:6379> SADD key2 "d" -(integer) 1 -127.0.0.1:6379> SADD key2 "e" -(integer) 1 -127.0.0.1:6379> SUNIONSTORE key key1 key2 -(integer) 5 -127.0.0.1:6379> SMEMBERS key -1) "a" -2) "b" -3) "c" -4) "d" -5) "e" -``` diff --git a/commands/sunsubscribe.md b/commands/sunsubscribe.md deleted file mode 100644 index c92ade65..00000000 --- a/commands/sunsubscribe.md +++ /dev/null @@ -1,12 +0,0 @@ -Unsubscribes the client from the given shard channels, or from all of them if none is given. - -When no shard channels are specified, the client is unsubscribed from all the previously subscribed shard channels. -In this case a message for every unsubscribed shard channel will be sent to the client. - -Note: The global channels and shard channels needs to be unsubscribed from separately. - -For more information about sharded Pub/Sub, see [Sharded Pub/Sub](../topics/pubsub.md#sharded-pub-sub). - -## Reply - -When successful, this command doesn't return anything. Instead, for each shard channel, one message with the first element being the string `sunsubscribe` is pushed as a confirmation that the command succeeded. diff --git a/commands/swapdb.md b/commands/swapdb.md deleted file mode 100644 index 64b047be..00000000 --- a/commands/swapdb.md +++ /dev/null @@ -1,22 +0,0 @@ -This command swaps two Valkey databases, so that immediately all the -clients connected to a given database will see the data of the other database, and -the other way around. - -**Note:** `SWAPDB` is **disabled in cluster mode** to prevent shard inconsistencies, -as swapping databases on one shard while leaving others unchanged could lead to -data inconsistencies. - -The caller must have ACL permission to access **both** of the databases being -swapped. See [database permissions](../topics/acl.md#database-permissions). - -## Reply - -`OK`. - -## Examples - -``` -SWAPDB 0 1 -``` - -This will swap database 0 with database 1. All the clients connected with database 0 will immediately see the new data, exactly like all the clients connected with database 1 will see the data that was formerly of database 0. \ No newline at end of file diff --git a/commands/sync.md b/commands/sync.md deleted file mode 100644 index 15629201..00000000 --- a/commands/sync.md +++ /dev/null @@ -1,14 +0,0 @@ -Initiates a replication stream from the primary. - -The `SYNC` command is called by Valkey replicas for initiating a replication -stream from the primary. It has been replaced in newer versions of Valkey by - [`PSYNC`](psync.md). - -For more information about replication in Valkey please check the -[replication page][tr]. - -[tr]: ../topics/replication.md - -## Reply - -**Non-standard return value**, a bulk transfer of the data followed by `PING` and write requests from the primary. diff --git a/commands/time.md b/commands/time.md deleted file mode 100644 index d4887c82..00000000 --- a/commands/time.md +++ /dev/null @@ -1,19 +0,0 @@ -The `TIME` command returns the current server time as a two items lists: a Unix -timestamp and the amount of microseconds already elapsed in the current second. -Basically the interface is very similar to the one of the `gettimeofday` system -call. - -## Reply - -Array: specifically, a two-element array consisting of the Unix timestamp in seconds and the microseconds' count. - -## Examples - -``` -127.0.0.1:6379> TIME -1) "1714701491" -2) "723379" -127.0.0.1:6379> TIME -1) "1714701491" -2) "731773" -``` diff --git a/commands/touch.md b/commands/touch.md deleted file mode 100644 index 380fe936..00000000 --- a/commands/touch.md +++ /dev/null @@ -1,17 +0,0 @@ -Alters the last access time of a key(s). -A key is ignored if it does not exist. - -## Reply - -Integer: the number of touched keys. - -## Examples - -``` -127.0.0.1:6379> SET key1 "Hello" -OK -127.0.0.1:6379> SET key2 "World" -OK -127.0.0.1:6379> TOUCH key1 key2 -(integer) 2 -``` diff --git a/commands/ttl.md b/commands/ttl.md deleted file mode 100644 index ff8b859f..00000000 --- a/commands/ttl.md +++ /dev/null @@ -1,29 +0,0 @@ -Returns the remaining time to live of a key that has a timeout. -This introspection capability allows a Valkey client to check how many seconds a -given key will continue to be part of the dataset. - -The command returns the following values in case of errors: - -* The command returns `-2` if the key does not exist. -* The command returns `-1` if the key exists but has no associated expire. - -See also the [`PTTL`](pttl.md) command that returns the same information with milliseconds resolution. - -## Reply - -One of the following: - -* Integer: TTL in seconds. -* Integer: `-1` if the key exists but has no associated expiration. -* Integer: `-2` if the key does not exist. - -## Examples - -``` -127.0.0.1:6379> SET mykey "Hello" -OK -127.0.0.1:6379> EXPIRE mykey 10 -(integer) 1 -127.0.0.1:6379> TTL mykey -(integer) 10 -``` diff --git a/commands/type.md b/commands/type.md deleted file mode 100644 index 4c0b71d0..00000000 --- a/commands/type.md +++ /dev/null @@ -1,24 +0,0 @@ -Returns the string representation of the type of the value stored at `key`. -The different types that can be returned are: `string`, `list`, `set`, `zset`, -`hash` and `stream`. - -## Reply - -Simple string: the type of _key_, or `none` when _key_ doesn't exist. - -## Examples - -``` -127.0.0.1:6379> SET key1 "value" -OK -127.0.0.1:6379> LPUSH key2 "value" -(integer) 1 -127.0.0.1:6379> SADD key3 "value" -(integer) 1 -127.0.0.1:6379> TYPE key1 -string -127.0.0.1:6379> TYPE key2 -list -127.0.0.1:6379> TYPE key3 -set -``` diff --git a/commands/unlink.md b/commands/unlink.md deleted file mode 100644 index 50005a09..00000000 --- a/commands/unlink.md +++ /dev/null @@ -1,21 +0,0 @@ -This command is very similar to [`DEL`](del.md): it removes the specified keys. -Just like `DEL` a key is ignored if it does not exist. However the command -performs the actual memory reclaiming in a different thread, so it is not -blocking, while `DEL` is. This is where the command name comes from: the -command just **unlinks** the keys from the keyspace. The actual removal -will happen later asynchronously. - -## Reply - -Integer: the number of keys that were unlinked. - -## Examples - -``` -127.0.0.1:6379> SET key1 "Hello" -OK -127.0.0.1:6379> SET key2 "World" -OK -127.0.0.1:6379> UNLINK key1 key2 key3 -(integer) 2 -``` diff --git a/commands/unsubscribe.md b/commands/unsubscribe.md deleted file mode 100644 index 4d103cff..00000000 --- a/commands/unsubscribe.md +++ /dev/null @@ -1,11 +0,0 @@ -Unsubscribes the client from the given channels, or from all of them if none is -given. - -When no channels are specified, the client is unsubscribed from all the -previously subscribed channels. -In this case, a message for every unsubscribed channel will be sent to the -client. - -## Reply - -When successful, this command doesn't return anything. Instead, for each channel, one message with the first element being the string `unsubscribe` is pushed as a confirmation that the command succeeded. diff --git a/commands/unwatch.md b/commands/unwatch.md deleted file mode 100644 index 26d62684..00000000 --- a/commands/unwatch.md +++ /dev/null @@ -1,9 +0,0 @@ -Flushes all the previously watched keys for a [transaction][tt]. - -[tt]: ../topics/transactions.md - -If you call `EXEC` or `DISCARD`, there's no need to manually call `UNWATCH`. - -## Reply - -`OK`. diff --git a/commands/wait.md b/commands/wait.md deleted file mode 100644 index c3406682..00000000 --- a/commands/wait.md +++ /dev/null @@ -1,55 +0,0 @@ -This command blocks the current client until all the previous write commands -are successfully transferred and acknowledged by at least the specified number -of replicas. If the timeout, specified in milliseconds, is reached, the command -returns even if the specified number of replicas were not yet reached. - -The command **will always return** the number of replicas that acknowledged -the write commands sent by the current client before the `WAIT` command, both in the case where -the specified number of replicas are reached, or when the timeout is reached. - -A few remarks: - -1. When `WAIT` returns, all the previous write commands sent in the context of the current connection are guaranteed to be received by the number of replicas returned by `WAIT`. -2. If the command is sent as part of any context that does not allow blocking, such as inside scripts, the command does not block but instead just return ASAP the number of replicas that acknowledged the previous write commands. -3. A timeout of 0 means to block forever. -4. Since `WAIT` returns the number of replicas reached both in case of failure and success, the client should check that the returned value is equal or greater to the replication level it demanded. - -Consistency and WAIT ---- - -Note that `WAIT` does not make Valkey a strongly consistent store: while synchronous replication is part of a replicated state machine, it is not the only thing needed. However in the context of Sentinel or Valkey Cluster failover, `WAIT` improves the real world data safety. - -Specifically if a given write is transferred to one or more replicas, it is more likely (but not guaranteed) that if the primary fails, we'll be able to promote, during a failover, a replica that received the write: both Sentinel and Valkey Cluster will do a best-effort attempt to promote the best replica among the set of available replicas. - -However this is just a best-effort attempt so it is possible to still lose a write synchronously replicated to multiple replicas. - -Implementation details ---- - -Since the introduction of partial resynchronization with replicas (PSYNC feature) Valkey replicas asynchronously ping their primary with the offset they already processed in the replication stream. This is used in multiple ways: - -1. Detect timed out replicas. -2. Perform a partial resynchronization after a disconnection. -3. Implement `WAIT`. - -In the specific case of the implementation of `WAIT`, Valkey remembers, for each client, the replication offset of the produced replication stream when a given -write command was executed in the context of a given client. When `WAIT` is -called Valkey checks if the specified number of replicas already acknowledged -this offset or a greater one. - -## Reply - -Integer: the number of replicas reached by all the writes performed in the context of the current connection. - -## Examples - -``` -> SET foo bar -OK -> WAIT 1 0 -(integer) 1 -> WAIT 2 1000 -(integer) 1 -``` - -In the following example the first call to `WAIT` does not use a timeout and asks for the write to reach 1 replica. It returns with success. In the second attempt instead we put a timeout, and ask for the replication of the write to two replicas. Since there is a single replica available, after one second `WAIT` unblocks and returns 1, the number of replicas reached. diff --git a/commands/waitaof.md b/commands/waitaof.md deleted file mode 100644 index 87263324..00000000 --- a/commands/waitaof.md +++ /dev/null @@ -1,66 +0,0 @@ -This command blocks the current client until all previous write commands by that client are acknowledged as having been fsynced to the AOF of the local Valkey and/or at least the specified number of replicas. - -`numlocal` represents the number of local fsyncs required to be confirmed before proceeding. -When `numlocal` is set to 1, the command blocks until the data written to the Valkey instance is confirmed to be persisted to the local AOF file. -The value 0 disables this check. - -If the timeout, specified in milliseconds, is reached, the command returns even if the specified number of acknowledgments has not been met. - -The command **will always return** the number of primaries and replicas that have fsynced all write commands sent by the current client before the `WAITAOF` command, both in the case where the specified thresholds were met, and when the timeout is reached. - -A few remarks: - -1. When `WAITAOF` returns, all the previous write commands sent in the context of the current connection are guaranteed to be fsynced to the AOF of at least the number of primaries and replicas returned by `WAITAOF`. -2. If the command is sent as part of a `MULTI` transaction (or any other context that does not allow blocking, such as inside scripts), the command does not block but instead returns immediately the number of primaries and replicas that fsynced all previous write commands. -3. A timeout of 0 means to block forever. -4. Since `WAITAOF` returns the number of fsyncs completed both in case of success and timeout, the client should check that the returned values are equal or greater than the persistence level required. -5. `WAITAOF` cannot be used on replica instances, and the `numlocal` argument cannot be non-zero if the local Valkey does not have AOF enabled. - -Limitations ---- -It is possible to write a module or Lua script that propagate writes to the AOF but not the replication stream. -(For modules, this is done using the `fmt` argument to `RedisModule_Call` or `RedisModule_Replicate`; For Lua scripts, this is achieved using `server.set_repl`.) - -These features are incompatible with the `WAITAOF` command as it is currently implemented, and using them in combination may result in incorrect behavior. - -Consistency and WAITAOF ---- - -Note that, similarly to [`WAIT`](wait.md), `WAITAOF` does not make Valkey a strongly-consistent store. -Unless waiting for all members of a cluster to fsync writes to disk, data can still be lost during a failover or a Valkey restart. -However, `WAITAOF` does improve real-world data safety. - -Implementation details ---- - -Valkey tracks and increments the replication offset even when no replicas are configured (as long as AOF exists). - -In addition, Valkey replicas asynchronously ping their primary with two replication offsets: the offset they have processed in the replication stream, and the offset they have fsynced to their AOF. - -Valkey remembers, for each client, the replication offset of the produced replication stream when the last write command was executed in the context of that client. -When `WAITAOF` is called, Valkey checks if the local Valkey and/or the specified number of replicas have confirmed fsyncing this offset or a greater one to their AOF. - -## Reply - -Array: The command returns an array of two integers: - -1. The first is the number of local Valkey nodes (0 or 1) that have fsynced to AOF all writes performed in the context of the current connection -2. The second is the number of replicas that have acknowledged doing the same. - -## Examples - -``` -> SET foo bar -OK -> WAITAOF 1 0 0 -1) (integer) 1 -2) (integer) 0 -> WAITAOF 0 1 1000 -1) (integer) 1 -2) (integer) 0 -``` - -In the above example, the first call to `WAITAOF` does not use a timeout and asks for the write to be fsynced to the local Valkey only; it returns with [1, 0] when this is completed. - -In the second attempt we instead specify a timeout, and ask for the write to be confirmed as fsynced by a single replica. -Since there are no connected replicas, the `WAITAOF` command unblocks after one second and again returns [1, 0], indicating the write has been fsynced on the local Valkey but no replicas. diff --git a/commands/watch.md b/commands/watch.md deleted file mode 100644 index 6449ff64..00000000 --- a/commands/watch.md +++ /dev/null @@ -1,8 +0,0 @@ -Marks the given keys to be watched for conditional execution of a -[transaction][tt]. - -[tt]: ../topics/transactions.md - -## Reply - -`OK`. diff --git a/commands/xack.md b/commands/xack.md deleted file mode 100644 index 75fd72b2..00000000 --- a/commands/xack.md +++ /dev/null @@ -1,28 +0,0 @@ -The `XACK` command removes one or multiple messages from the -*Pending Entries List* (PEL) of a stream consumer group. A message is pending, -and as such stored inside the PEL, when it was delivered to some consumer, -normally as a side effect of calling `XREADGROUP`, or when a consumer took -ownership of a message calling `XCLAIM`. The pending message was delivered to -some consumer but the server is yet not sure it was processed at least once. -So new calls to `XREADGROUP` to grab the messages history for a consumer -(for instance using an ID of 0), will return such message. -Similarly the pending message will be listed by the `XPENDING` command, -that inspects the PEL. - -Once a consumer *successfully* processes a message, it should call `XACK` -so that such message does not get processed again, and as a side effect, -the PEL entry about this message is also purged, releasing memory from the -Valkey server. - -To acknowledge and delete entries in a single step, with control over how other consumer groups' PEL references are handled, see [XACKDEL](xackdel.md), which extends this command with explicit `KEEPREF`, `DELREF`, and `ACKED` deletion modes. - -## Reply - -Integer: The command returns the number of messages successfully acknowledged. Certain message IDs may no longer be part of the PEL (for example because they have already been acknowledged), and XACK will not count them as successfully acknowledged. - -## Examples - -``` -127.0.0.1:6379> XACK mystream mygroup 1526569495631-0 -(integer) 1 -``` diff --git a/commands/xackdel.md b/commands/xackdel.md deleted file mode 100644 index 3390b2aa..00000000 --- a/commands/xackdel.md +++ /dev/null @@ -1,46 +0,0 @@ -The `XACKDEL` command is an extension of the [XACK](xack.md) stream command that acknowledges the specified message IDs in `group`'s pending entries list (PEL) and, depending on `mode`, deletes the underlying stream messages. - -This is particularly useful when multiple consumer groups independently process the same stream and you need to reclaim space without deleting messages that another group still needs. - -The command supports three deletion modes: - -- `KEEPREF` (default, implicit): acknowledges and deletes messages immediately, leaving PEL references in other groups, -- `DELREF`: acknowledges, deletes, and forcibly removes PEL references from all other groups, -- `ACKED`: deletes a message only once no consumer group still needs it, meaning none has it pending (each has either acknowledged it or never picked it up), and no group can still deliver it later. - -## Reply - -Array of integer codes, one per requested ID, in the same order as the IDs are given. - -* -1: The key doesn't exist, the group doesn't exist, or the ID isn't in the group's PEL. -* 1: The entry was acknowledged and deleted, or a dangling PEL entry (whose stream entry was already deleted) was acknowledged. -* 2: The entry was acknowledged but not deleted because another consumer group still needs it (`ACKED` mode only). - -## Examples - -``` -127.0.0.1:6899> XADD s5 * a 1 -"1788350000000-0" -127.0.0.1:6899> XGROUP CREATE s5 g1 0 -OK -127.0.0.1:6899> XGROUP CREATE s5 g2 0 -OK -127.0.0.1:6899> XREADGROUP GROUP g1 cons1 COUNT 10 STREAMS s5 > -1) 1) "s5" - 2) 1) 1) "1788350000000-0" - 2) 1) "a" - 2) "1" -127.0.0.1:6899> XACKDEL s5 g1 ACKED IDS 1 1788350000000-0 -1) (integer) 2 -127.0.0.1:6899> XLEN s5 -(integer) 1 -127.0.0.1:6899> XREADGROUP GROUP g2 cons1 COUNT 10 STREAMS s5 > -1) 1) "s5" - 2) 1) 1) "1788350000000-0" - 2) 1) "a" - 2) "1" -127.0.0.1:6899> XACKDEL s5 g2 ACKED IDS 1 1788350000000-0 -1) (integer) 1 -127.0.0.1:6899> XLEN s5 -(integer) 0 -``` diff --git a/commands/xadd.md b/commands/xadd.md deleted file mode 100644 index d7938606..00000000 --- a/commands/xadd.md +++ /dev/null @@ -1,104 +0,0 @@ -Appends the specified stream entry to the stream at the specified key. -If the key does not exist, as a side effect of running this command the -key is created with a stream value. The creation of stream's key can be -disabled with the `NOMKSTREAM` option. - -An entry is composed of a list of field-value pairs. -The field-value pairs are stored in the same order they are given by the user. -Commands that read the stream, such as `XRANGE` or `XREAD`, are guaranteed to return the fields and values exactly in the same order they were added by `XADD`. - -`XADD` is the *only Valkey command* that can add data to a stream, but -there are other commands, such as `XDEL` and `XTRIM`, that are able to -remove data from a stream. - -## Specifying a Stream ID as an argument - -A stream entry ID identifies a given entry inside a stream. - -The `XADD` command will auto-generate a unique ID for you if the ID argument -specified is the `*` character (asterisk ASCII character). However, while -useful only in very rare cases, it is possible to specify a well-formed ID, so -that the new entry will be added exactly with the specified ID. - -IDs are specified by two numbers separated by a `-` character: - - 1526919030474-55 - -Both quantities are 64-bit numbers. When an ID is auto-generated, the -first part is the Unix time in milliseconds of the Valkey instance generating -the ID. The second part is just a sequence number and is used in order to -distinguish IDs generated in the same millisecond. - -You can also specify an incomplete ID, that consists only of the milliseconds part, which is interpreted as a zero value for sequence part. -To have only the sequence part automatically generated, specify the milliseconds part followed by the `-` separator and the `*` character: - -``` -> XADD mystream 1526919030474-55 message "Hello," -"1526919030474-55" -> XADD mystream 1526919030474-* message " World!" -"1526919030474-56" -``` - -IDs are guaranteed to be always incremental: If you compare the ID of the -entry just inserted it will be greater than any other past ID, so entries -are totally ordered inside a stream. In order to guarantee this property, -if the current top ID in the stream has a time greater than the current -local time of the instance, the top entry time will be used instead, and -the sequence part of the ID incremented. This may happen when, for instance, -the local clock jumps backward, or if after a failover the new primary has -a different absolute time. - -When a user specified an explicit ID to `XADD`, the minimum valid ID is -`0-1`, and the user *must* specify an ID which is greater than any other -ID currently inside the stream, otherwise the command will fail and return an error. Usually -resorting to specific IDs is useful only if you have another system generating -unique IDs (for instance an SQL table) and you really want the Stream -IDs to match the one of this other system. - -## Capped streams - -`XADD` incorporates the same semantics as the `XTRIM` command - refer to its documentation page for more information. -This allows adding new entries and keeping the stream's size in check with a single call to `XADD`, effectively capping the stream with an arbitrary threshold. -Although exact trimming is possible and is the default, due to the internal representation of steams it is more efficient to add an entry and trim stream with `XADD` using **almost exact** trimming (the `~` argument). - -For example, calling `XADD` in the following form: - - XADD mystream MAXLEN ~ 1000 * ... entry fields here ... - -Will add a new entry but will also evict old entries so that the stream will contain only 1000 entries, or at most a few tens more. - -## Additional information about streams - -For further information about streams please check our -[introduction to Streams document](../topics/streams-intro.md). - -## Reply - -One of the following: - -* String: The ID of the added entry. The ID is the one automatically generated if an asterisk (`*`) is passed as the _id_ argument, otherwise the command just returns the same ID specified by the user during insertion. -* Null: if the NOMKSTREAM option is given and the key doesn't exist. - -## Examples - -``` -127.0.0.1:6379> XADD mystream * name Sara surname OConnor -"1714701491958-0" -127.0.0.1:6379> XADD mystream * field1 value1 field2 value2 field3 value3 -"1714701491968-0" -127.0.0.1:6379> XLEN mystream -(integer) 2 -127.0.0.1:6379> XRANGE mystream - + -1) 1) "1714701491958-0" - 2) 1) "name" - 2) "Sara" - 3) "surname" - 4) "OConnor" -2) 1) "1714701491968-0" - 2) 1) "field1" - 2) "value1" - 3) "field2" - 4) "value2" - 5) "field3" - 6) "value3" -``` diff --git a/commands/xautoclaim.md b/commands/xautoclaim.md deleted file mode 100644 index c11da25f..00000000 --- a/commands/xautoclaim.md +++ /dev/null @@ -1,50 +0,0 @@ -This command transfers ownership of pending stream entries that match the specified criteria. Conceptually, `XAUTOCLAIM` is equivalent to calling `XPENDING` and then `XCLAIM`, -but provides a more straightforward way to deal with message delivery failures via `SCAN`-like semantics. - -Like `XCLAIM`, the command operates on the stream entries at `` and in the context of the provided ``. -It transfers ownership to `` of messages pending for more than `` milliseconds and having an equal or greater ID than ``. - -The optional `` argument, which defaults to 100, is the upper limit of the number of entries that the command attempts to claim. -Internally, the command begins scanning the consumer group's Pending Entries List (PEL) from `` and filters out entries having an idle time less than or equal to ``. -The maximum number of pending entries that the command scans is the product of multiplying ``'s value by 10 (hard-coded). -It is possible, therefore, that the number of entries claimed will be less than the specified value. - -The optional `JUSTID` argument changes the reply to return just an array of IDs of messages successfully claimed, without returning the actual message. -Using this option means the retry counter is not incremented. - -The command returns the claimed entries as an array. It also returns a stream ID intended for cursor-like use as the `` argument for its subsequent call. -When there are no remaining PEL entries, the command returns the special `0-0` ID to signal completion. -However, note that you may want to continue calling `XAUTOCLAIM` even after the scan is complete with the `0-0` as `` ID, because enough time passed, so older pending entries may now be eligible for claiming. - -Note that only messages that are idle longer than `` are claimed, and claiming a message resets its idle time. -This ensures that only a single consumer can successfully claim a given pending message at a specific instant of time and trivially reduces the probability of processing the same message multiple times. - -While iterating the PEL, if `XAUTOCLAIM` stumbles upon a message which doesn't exist in the stream anymore (either trimmed or deleted by `XDEL`) it does not claim it, and deletes it from the PEL in which it was found. -These message IDs are returned to the caller as a part of `XAUTOCLAIM`s reply. - -Lastly, claiming a message with `XAUTOCLAIM` also increments the attempted deliveries count for that message, unless the `JUSTID` option has been specified (which only delivers the message ID, not the message itself). -Messages that cannot be processed for some reason - for example, because consumers systematically crash when processing them - will exhibit high attempted delivery counts that can be detected by monitoring. - -## Reply - -Array, specifically, an array with three elements: - -1. A stream ID to be used as the _start_ argument for the next call to XAUTOCLAIM. -2. An array containing all the successfully claimed messages in the same format as `XRANGE`. -3. An array containing message IDs that no longer exist in the stream, and were deleted from the PEL in which they were found. - -## Examples - -``` -> XAUTOCLAIM mystream mygroup Alice 3600000 0-0 COUNT 25 -1) "0-0" -2) 1) 1) "1609338752495-0" - 2) 1) "field" - 2) "value" -3) (empty array) -``` - -In the above example, we attempt to claim up to 25 entries that are pending and idle (not having been acknowledged or claimed) for at least an hour, starting at the stream's beginning. -The consumer "Alice" from the "mygroup" group acquires ownership of these messages. -Note that the stream ID returned in the example is `0-0`, indicating that the entire stream was scanned. -We can also see that `XAUTOCLAIM` did not stumble upon any deleted messages (the third reply element is an empty array). diff --git a/commands/xclaim.md b/commands/xclaim.md deleted file mode 100644 index 6344a05b..00000000 --- a/commands/xclaim.md +++ /dev/null @@ -1,54 +0,0 @@ -In the context of a stream consumer group, this command changes the ownership -of a pending message, so that the new owner is the consumer specified as the -command argument. Normally this is what happens: - -1. There is a stream with an associated consumer group. -2. Some consumer A reads a message via `XREADGROUP` from a stream, in the context of that consumer group. -3. As a side effect a pending message entry is created in the Pending Entries List (PEL) of the consumer group: it means the message was delivered to a given consumer, but it was not yet acknowledged via `XACK`. -4. Then suddenly that consumer fails forever. -5. Other consumers may inspect the list of pending messages, that are stale for quite some time, using the `XPENDING` command. In order to continue processing such messages, they use `XCLAIM` to acquire the ownership of the message and continue. Consumers can also use the `XAUTOCLAIM` command to automatically scan and claim stale pending messages. - -This dynamic is clearly explained in the [Stream intro documentation](../topics/streams-intro.md). - -Note that the message is claimed only if its idle time is greater than the minimum idle time we specify when calling `XCLAIM`. Because as a side effect `XCLAIM` will also reset the idle time (since this is a new attempt at processing the message), two consumers trying to claim a message at the same time will never both succeed: only one will successfully claim the message. This avoids that we process a given message multiple times in a trivial way (yet multiple processing is possible and unavoidable in the general case). - -Moreover, as a side effect, `XCLAIM` will increment the count of attempted deliveries of the message unless the `JUSTID` option has been specified (which only delivers the message ID, not the message itself). In this way messages that cannot be processed for some reason, for instance because the consumers crash attempting to process them, will start to have a larger counter and can be detected inside the system. - -`XCLAIM` will not claim a message in the following cases: - -1. The message doesn't exist in the group PEL (i.e. it was never read by any consumer) -2. The message exists in the group PEL but not in the stream itself (i.e. the message was read but never acknowledged, and then was deleted from the stream, either by trimming or by `XDEL`) - -In both cases the reply will not contain a corresponding entry to that message (i.e. the length of the reply array may be smaller than the number of IDs provided to `XCLAIM`). -In the latter case, the message will also be deleted from the PEL in which it was found. - -## Command options - -The command has multiple options, however most are mainly for internal use in -order to transfer the effects of `XCLAIM` or other commands to the AOF file -and to propagate the same effects to the replicas, and are unlikely to be -useful to normal users: - -1. `IDLE `: Set the idle time (last time it was delivered) of the message. If IDLE is not specified, an IDLE of 0 is assumed, that is, the time count is reset because the message has now a new owner trying to process it. -2. `TIME `: This is the same as IDLE but instead of a relative amount of milliseconds, it sets the idle time to a specific Unix time (in milliseconds). This is useful in order to rewrite the AOF file generating `XCLAIM` commands. -3. `RETRYCOUNT `: Set the retry counter to the specified value. This counter is incremented every time a message is delivered again. Normally `XCLAIM` does not alter this counter, which is just served to clients when the XPENDING command is called: this way clients can detect anomalies, like messages that are never processed for some reason after a big number of delivery attempts. -4. `FORCE`: Creates the pending message entry in the PEL even if certain specified IDs are not already in the PEL assigned to a different client. However the message must be exist in the stream, otherwise the IDs of non existing messages are ignored. -5. `JUSTID`: Return just an array of IDs of messages successfully claimed, without returning the actual message. Using this option means the retry counter is not incremented. - -## Reply - -Any of the following: - -* Array: when the _JUSTID_ option is specified, an array of IDs of messages successfully claimed. -* Array of stream entries, each of which contains an array of two elements, the entry ID and the entry data itself. - -## Examples - -``` -> XCLAIM mystream mygroup Alice 3600000 1526569498055-0 -1) 1) 1526569498055-0 - 2) 1) "message" - 2) "orange" -``` - -In the above example we claim the message with ID `1526569498055-0`, only if the message is idle for at least one hour without the original consumer or some other consumer making progresses (acknowledging or claiming it), and assigns the ownership to the consumer `Alice`. diff --git a/commands/xdel.md b/commands/xdel.md deleted file mode 100644 index fe939779..00000000 --- a/commands/xdel.md +++ /dev/null @@ -1,53 +0,0 @@ -The `XDEL` command removes the specified entries from a stream, and returns the number of entries -deleted. This number may be less than the number of IDs passed to the command in -the case where some of the specified IDs do not exist in the stream. - -Normally you may think at a Stream as an append-only data structure, -however Streams are represented in memory, so we are also able to -delete entries. This may be useful, for instance, in order to comply with -certain privacy policies. - -For more control over how consumer group PEL references are handled when deleting entries, see [XDELEX](xdelex.md), which extends this command with explicit `KEEPREF`, `DELREF`, and `ACKED` deletion modes. - -## Understanding the low level details of entries deletion - -streams are represented in a way that makes them memory efficient: -a radix tree is used in order to index macro-nodes that pack linearly tens -of stream entries. Normally what happens when you delete an entry from a stream -is that the entry is not *really* evicted, it just gets marked as deleted. - -Eventually if all the entries in a macro-node are marked as deleted, the whole -node is destroyed and the memory reclaimed. This means that if you delete -a large amount of entries from a stream, for instance more than 50% of the -entries appended to the stream, the memory usage per entry may increment, since -what happens is that the stream will become fragmented. However the stream -performance will remain the same. - -In future versions of Valkey it is possible that we'll trigger a node garbage -collection in case a given macro-node reaches a given amount of deleted -entries. Currently with the usage we anticipate for this data structure, it is -not a good idea to add such complexity. - -## Reply - -Integer: the number of entries that were deleted. - -## Examples - -``` -> XADD mystream * a 1 -1538561698944-0 -> XADD mystream * b 2 -1538561700640-0 -> XADD mystream * c 3 -1538561701744-0 -> XDEL mystream 1538561700640-0 -(integer) 1 -127.0.0.1:6379> XRANGE mystream - + -1) 1) 1538561698944-0 - 2) 1) "a" - 2) "1" -2) 1) 1538561701744-0 - 2) 1) "c" - 2) "3" -``` diff --git a/commands/xdelex.md b/commands/xdelex.md deleted file mode 100644 index d6b2d65d..00000000 --- a/commands/xdelex.md +++ /dev/null @@ -1,39 +0,0 @@ -The `XDELEX` command is an extension of the [XDEL](xdel.md) command that deletes one or more stream messages with control over how deletion affects consumer groups. - -The command supports three deletion modes: - -- `KEEPREF` (default): deletes the stream message but leaves pending entries list (PEL) references intact in all consumer groups, -- `DELREF`: deletes the stream message and forcibly removes it from all consumer group PELs, -- `ACKED`: deletes a message only once no consumer group still needs it, meaning none has it pending (each has either acknowledged it or never picked it up), and no group can still deliver it later. - -## Reply - -Array of integer codes, one per requested ID, in the same order as the IDs are given. - -* -1: The ID doesn't exist in the stream, or the key doesn't exist. -* 1: The entry was deleted. -* 2: The entry was not deleted because a consumer group still needs it (`ACKED` mode only). - -## Examples - -``` -127.0.0.1:6899> XADD s4 * a 1 -"1788346731590-0" -127.0.0.1:6899> XGROUP CREATE s4 grp 0 -OK -127.0.0.1:6899> XREADGROUP GROUP grp cons1 COUNT 10 STREAMS s4 > -1) 1) "s4" - 2) 1) 1) "1788346731590-0" - 2) 1) "a" - 2) "1" -127.0.0.1:6899> XDELEX s4 ACKED IDS 1 1788346731590-0 -1) (integer) 2 -127.0.0.1:6899> XLEN s4 -(integer) 1 -127.0.0.1:6899> XACK s4 grp 1788346731590-0 -(integer) 1 -127.0.0.1:6899> XDELEX s4 ACKED IDS 1 1788346731590-0 -1) (integer) 1 -127.0.0.1:6899> XLEN s4 -(integer) 0 -``` diff --git a/commands/xgroup-create.md b/commands/xgroup-create.md deleted file mode 100644 index 733d4532..00000000 --- a/commands/xgroup-create.md +++ /dev/null @@ -1,25 +0,0 @@ -Create a new consumer group uniquely identified by `` for the stream stored at `` - -Every group has a unique name in a given stream. -When a consumer group with the same name already exists, the command returns a `-BUSYGROUP` error. - -The command's `` argument specifies the last delivered entry in the stream from the new group's perspective. -The special ID `$` is the ID of the last entry in the stream, but you can substitute it with any valid ID. - -For example, if you want the group's consumers to fetch the entire stream from the beginning, use zero as the starting ID for the consumer group: - - XGROUP CREATE mystream mygroup 0 - -By default, the `XGROUP CREATE` command expects that the target stream exists, and returns an error when it doesn't. -If a stream does not exist, you can create it automatically with length of 0 by using the optional `MKSTREAM` subcommand as the last argument after the ``: - - XGROUP CREATE mystream mygroup $ MKSTREAM - -To enable consumer group lag tracking, specify the optional `entries_read` named argument with an arbitrary ID. -An arbitrary ID is any ID that isn't the ID of the stream's first entry, last entry, or zero ("0-0") ID. -Use it to find out how many entries are between the arbitrary ID (excluding it) and the stream's last entry. -Set the `entries_read` the stream's `entries_added` subtracted by the number of entries. - -## Reply - -`OK`. diff --git a/commands/xgroup-createconsumer.md b/commands/xgroup-createconsumer.md deleted file mode 100644 index d87873c2..00000000 --- a/commands/xgroup-createconsumer.md +++ /dev/null @@ -1,8 +0,0 @@ -Create a consumer named `` in the consumer group `` of the stream that's stored at ``. - -Consumers are also created automatically whenever an operation, such as `XREADGROUP`, references a consumer that doesn't exist. -This is valid for `XREADGROUP` only when there is data in the stream. - -## Reply - -Integer: the number of created consumers, either 0 or 1. diff --git a/commands/xgroup-delconsumer.md b/commands/xgroup-delconsumer.md deleted file mode 100644 index ee0c11f7..00000000 --- a/commands/xgroup-delconsumer.md +++ /dev/null @@ -1,10 +0,0 @@ -The `XGROUP DELCONSUMER` command deletes a consumer from the consumer group. - -Sometimes it may be useful to remove old consumers since they are no longer used. - -Note, however, that any pending messages that the consumer had will become unclaimable after it was deleted. -It is strongly recommended, therefore, that any pending messages are claimed or acknowledged prior to deleting the consumer from the group. - -## Reply - -Integer: the number of pending messages the consumer had before it was deleted. diff --git a/commands/xgroup-destroy.md b/commands/xgroup-destroy.md deleted file mode 100644 index 09e93102..00000000 --- a/commands/xgroup-destroy.md +++ /dev/null @@ -1,7 +0,0 @@ -The `XGROUP DESTROY` command completely destroys a consumer group. - -The consumer group will be destroyed even if there are active consumers, and pending messages, so make sure to call this command only when really needed. - -## Reply - -Integer: the number of destroyed consumer groups, either 0 or 1. diff --git a/commands/xgroup-help.md b/commands/xgroup-help.md deleted file mode 100644 index 6f1cf3df..00000000 --- a/commands/xgroup-help.md +++ /dev/null @@ -1,5 +0,0 @@ -The `XGROUP HELP` command returns a helpful text describing the different subcommands. - -## Reply - -Array of sub-commands and their descriptions. diff --git a/commands/xgroup-setid.md b/commands/xgroup-setid.md deleted file mode 100644 index b50ff845..00000000 --- a/commands/xgroup-setid.md +++ /dev/null @@ -1,16 +0,0 @@ -Set the **last delivered ID** for a consumer group. - -Normally, a consumer group's last delivered ID is set when the group is created with `XGROUP CREATE`. -The `XGROUP SETID` command allows modifying the group's last delivered ID, without having to delete and recreate the group. -For instance if you want the consumers in a consumer group to re-process all the messages in a stream, you may want to set its next ID to 0: - - XGROUP SETID mystream mygroup 0 - -The optional `entries_read` argument can be specified to enable consumer group lag tracking for an arbitrary ID. -An arbitrary ID is any ID that isn't the ID of the stream's first entry, its last entry or the zero ("0-0") ID. -This can be useful you know exactly how many entries are between the arbitrary ID (excluding it) and the stream's last entry. -In such cases, the `entries_read` can be set to the stream's `entries_added` subtracted with the number of entries. - -## Reply - -`OK`. diff --git a/commands/xgroup.md b/commands/xgroup.md deleted file mode 100644 index e7b517a9..00000000 --- a/commands/xgroup.md +++ /dev/null @@ -1,3 +0,0 @@ -This is a container command for stream consumer group management commands. - -To see the list of available commands you can call `XGROUP HELP`. diff --git a/commands/xinfo-consumers.md b/commands/xinfo-consumers.md deleted file mode 100644 index d4639de8..00000000 --- a/commands/xinfo-consumers.md +++ /dev/null @@ -1,34 +0,0 @@ -This command returns the list of consumers that belong to the `` consumer group of the stream stored at ``. - -The following information is provided for each consumer in the group: - -* **name**: the consumer's name -* **pending**: the number of entries in the PEL: pending messages for the consumer, which are messages that were delivered but are yet to be acknowledged -* **idle**: the number of milliseconds that have passed since the consumer's last attempted interaction (Examples: `XREADGROUP`, `XCLAIM`, `XAUTOCLAIM`) -* **inactive**: the number of milliseconds that have passed since the consumer's last successful interaction (Examples: `XREADGROUP` that actually read some entries into the PEL, `XCLAIM`/`XAUTOCLAIM` that actually claimed some entries) - -## Reply - -Array of consumers and their attributes. - -## Examples - -``` -> XINFO CONSUMERS mystream mygroup -1) 1) name - 2) "Alice" - 3) pending - 4) (integer) 1 - 5) idle - 6) (integer) 9104628 - 7) inactive - 8) (integer) 18104698 -2) 1) name - 2) "Bob" - 3) pending - 4) (integer) 1 - 5) idle - 6) (integer) 83841983 - 7) inactive - 8) (integer) 993841998 -``` diff --git a/commands/xinfo-groups.md b/commands/xinfo-groups.md deleted file mode 100644 index 9ed3832b..00000000 --- a/commands/xinfo-groups.md +++ /dev/null @@ -1,74 +0,0 @@ -This command returns the list of all consumer groups of the stream stored at ``. - -By default, only the following information is provided for each of the groups: - -* **name**: the consumer group's name -* **consumers**: the number of consumers in the group -* **pending**: the length of the group's pending entries list (PEL), which are messages that were delivered but are yet to be acknowledged -* **last-delivered-id**: the ID of the last entry delivered to the group's consumers -* **entries-read**: the logical "read counter" of the last entry delivered to the group's consumers -* **lag**: the number of entries in the stream that are still waiting to be delivered to the group's consumers, or a NULL when that number can't be determined. - -### Consumer group lag - -The lag of a given consumer group is the number of entries in the range between the group's `entries_read` and the stream's `entries_added`. -Put differently, it is the number of entries that are yet to be delivered to the group's consumers. - -The values and trends of this metric are helpful in making scaling decisions about the consumer group. -You can address high lag values by adding more consumers to the group, whereas low values may indicate that you can remove consumers from the group to scale it down. - -Valkey reports the lag of a consumer group by keeping two counters: the number of all entries added to the stream and the number of logical reads made by the consumer group. -The lag is the difference between these two. - -The stream's counter (the `entries_added` field of the `XINFO STREAM` command) is incremented by one with every `XADD` and counts all of the entries added to the stream during its lifetime. - -The consumer group's counter, `entries_read`, is the logical counter of entries the group had read. -It is important to note that this counter is only a heuristic rather than an accurate counter, and therefore the use of the term "logical". -The counter attempts to reflect the number of entries that the group **should have read** to get to its current `last-delivered-id`. -The `entries_read` counter is accurate only in a perfect world, where a consumer group starts at the stream's first entry and processes all of its entries (i.e., no entries deleted before processing). - -There are two special cases in which this mechanism is unable to report the lag: - -1. A consumer group is created or set with an arbitrary last delivered ID (the `XGROUP CREATE` and `XGROUP SETID` commands, respectively). - An arbitrary ID is any ID that isn't the ID of the stream's first entry, its last entry or the zero ("0-0") ID. -2. One or more entries between the group's `last-delivered-id` and the stream's `last-generated-id` were deleted (with `XDEL` or a trimming operation). - -In both cases, the group's read counter is considered invalid, and the returned value is set to NULL to signal that the lag isn't currently available. - -However, the lag is only temporarily unavailable. -It is restored automatically during regular operation as consumers keep processing messages. -Once the consumer group delivers the last message in the stream to its members, it will be set with the correct logical read counter, and tracking its lag can be resumed. - -## Reply - -Array of consumer groups. - -## Examples - -``` -> XINFO GROUPS mystream -1) 1) "name" - 2) "mygroup" - 3) "consumers" - 4) (integer) 2 - 5) "pending" - 6) (integer) 2 - 7) "last-delivered-id" - 8) "1638126030001-0" - 9) "entries-read" - 10) (integer) 2 - 11) "lag" - 12) (integer) 0 -2) 1) "name" - 2) "some-other-group" - 3) "consumers" - 4) (integer) 1 - 5) "pending" - 6) (integer) 0 - 7) "last-delivered-id" - 8) "1638126028070-0" - 9) "entries-read" - 10) (integer) 1 - 11) "lag" - 12) (integer) 1 -``` diff --git a/commands/xinfo-help.md b/commands/xinfo-help.md deleted file mode 100644 index 70ae8f9f..00000000 --- a/commands/xinfo-help.md +++ /dev/null @@ -1,5 +0,0 @@ -The `XINFO HELP` command returns a helpful text describing the different subcommands. - -## Reply - -Array of sub-commands and their descriptions. diff --git a/commands/xinfo-stream.md b/commands/xinfo-stream.md deleted file mode 100644 index 2c34ef65..00000000 --- a/commands/xinfo-stream.md +++ /dev/null @@ -1,152 +0,0 @@ -This command returns information about the stream stored at ``. - -The informative details provided by this command are: - -* **length**: the number of entries in the stream (see `XLEN`) -* **radix-tree-keys**: the number of keys in the underlying radix data structure -* **radix-tree-nodes**: the number of nodes in the underlying radix data structure -* **groups**: the number of consumer groups defined for the stream -* **last-generated-id**: the ID of the least-recently entry that was added to the stream -* **max-deleted-entry-id**: the maximal entry ID that was deleted from the stream -* **entries-added**: the count of all entries added to the stream during its lifetime -* **first-entry**: the ID and field-value tuples of the first entry in the stream -* **last-entry**: the ID and field-value tuples of the last entry in the stream - -### The `FULL` modifier - -The optional `FULL` modifier provides a more verbose reply. -When provided, the `FULL` reply includes an **entries** array that consists of the stream entries (ID and field-value tuples) in ascending order. -Furthermore, **groups** is also an array, and for each of the consumer groups it consists of the information reported by `XINFO GROUPS` and `XINFO CONSUMERS`. - -The following information is provided for each of the groups: - -* **name**: the consumer group's name -* **last-delivered-id**: the ID of the last entry delivered to the group's consumers -* **entries-read**: the logical "read counter" of the last entry delivered to the group's consumers -* **lag**: the number of entries in the stream that are still waiting to be delivered to the group's consumers, or a NULL when that number can't be determined. -* **pel-count**: the length of the group's pending entries list (PEL), which are messages that were delivered but are yet to be acknowledged -* **pending**: an array with pending entries information (see below) -* **consumers**: an array with consumers information (see below) - -The following information is provided for each pending entry: - -1. The ID of the message. -2. The name of the consumer that fetched the message and has still to acknowledge it. We call it the current *owner* of the message. -3. The UNIX timestamp of when the message was delivered to this consumer. -4. The number of times this message was delivered. - -The following information is provided for each consumer: - -* **name**: the consumer's name -* **seen-time**: the UNIX timestamp of the last attempted interaction (Examples: `XREADGROUP`, `XCLAIM`, `XAUTOCLAIM`) -* **active-time**: the UNIX timestamp of the last successful interaction (Examples: `XREADGROUP` that actually read some entries into the PEL, `XCLAIM`/`XAUTOCLAIM` that actually claimed some entries) -* **pel-count**: the number of entries in the PEL: pending messages for the consumer, which are messages that were delivered but are yet to be acknowledged -* **pending**: an array with pending entries information, has the same structure as described above, except the consumer name is omitted (redundant, since anyway we are in a specific consumer context) - -Note that before Redis OSS 7.2.0, **seen-time** used to denote the last successful interaction. -In 7.2.0, **active-time** was added and **seen-time** was changed to denote the last attempted interaction. - -The `COUNT` option can be used to limit the number of stream and PEL entries that are returned (The first `` entries are returned). -The default `COUNT` is 10 and a `COUNT` of 0 means that all entries will be returned (execution time may be long if the stream has a lot of entries). - -## Reply - -One of the following: - -* Map: when the _FULL_ argument was not given, a list of information about a stream in summary form. -* Map: when the _FULL_ argument was given, a list of information about a stream in extended form. - -## Examples - -Default reply: - -``` -> XINFO STREAM mystream - 1) "length" - 2) (integer) 2 - 3) "radix-tree-keys" - 4) (integer) 1 - 5) "radix-tree-nodes" - 6) (integer) 2 - 7) "last-generated-id" - 8) "1638125141232-0" - 9) "max-deleted-entry-id" -10) "0-0" -11) "entries-added" -12) (integer) 2 -13) "groups" -14) (integer) 1 -15) "first-entry" -16) 1) "1638125133432-0" - 2) 1) "message" - 2) "apple" -17) "last-entry" -18) 1) "1638125141232-0" - 2) 1) "message" - 2) "banana" -``` - -Full reply: - -``` -> XADD mystream * foo bar -"1638125133432-0" -> XADD mystream * foo bar2 -"1638125141232-0" -> XGROUP CREATE mystream mygroup 0-0 -OK -> XREADGROUP GROUP mygroup Alice COUNT 1 STREAMS mystream > -1) 1) "mystream" - 2) 1) 1) "1638125133432-0" - 2) 1) "foo" - 2) "bar" -> XINFO STREAM mystream FULL - 1) "length" - 2) (integer) 2 - 3) "radix-tree-keys" - 4) (integer) 1 - 5) "radix-tree-nodes" - 6) (integer) 2 - 7) "last-generated-id" - 8) "1638125141232-0" - 9) "max-deleted-entry-id" -10) "0-0" -11) "entries-added" -12) (integer) 2 -13) "entries" -14) 1) 1) "1638125133432-0" - 2) 1) "foo" - 2) "bar" - 2) 1) "1638125141232-0" - 2) 1) "foo" - 2) "bar2" -15) "groups" -16) 1) 1) "name" - 2) "mygroup" - 3) "last-delivered-id" - 4) "1638125133432-0" - 5) "entries-read" - 6) (integer) 1 - 7) "lag" - 8) (integer) 1 - 9) "pel-count" - 10) (integer) 1 - 11) "pending" - 12) 1) 1) "1638125133432-0" - 2) "Alice" - 3) (integer) 1638125153423 - 4) (integer) 1 - 13) "consumers" - 14) 1) 1) "name" - 2) "Alice" - 3) "seen-time" - 4) (integer) 1638125133422 - 5) "active-time" - 6) (integer) 1638125133432 - 7) "pel-count" - 8) (integer) 1 - 9) "pending" - 10) 1) 1) "1638125133432-0" - 2) (integer) 1638125133432 - 3) (integer) 1 -``` diff --git a/commands/xinfo.md b/commands/xinfo.md deleted file mode 100644 index 93fe9a29..00000000 --- a/commands/xinfo.md +++ /dev/null @@ -1,3 +0,0 @@ -This is a container command for stream introspection commands. - -To see the list of available commands you can call `XINFO HELP`. diff --git a/commands/xlen.md b/commands/xlen.md deleted file mode 100644 index 5bf7deb1..00000000 --- a/commands/xlen.md +++ /dev/null @@ -1,26 +0,0 @@ -Returns the number of entries inside a stream. If the specified key does not -exist the command returns zero, as if the stream was empty. -However note that unlike other Valkey types, zero-length streams are -possible, so you should call `TYPE` or `EXISTS` in order to check if -a key exists or not. - -Streams are not auto-deleted once they have no entries inside (for instance -after an `XDEL` call), because the stream may have consumer groups -associated with it. - -## Reply - -Integer: the number of entries of the stream at _key_. - -## Examples - -``` -127.0.0.1:6379> XADD mystream * item 1 -"1714701492011-0" -127.0.0.1:6379> XADD mystream * item 2 -"1714701492021-0" -127.0.0.1:6379> XADD mystream * item 3 -"1714701492031-0" -127.0.0.1:6379> XLEN mystream -(integer) 3 -``` diff --git a/commands/xpending.md b/commands/xpending.md deleted file mode 100644 index 80bafc12..00000000 --- a/commands/xpending.md +++ /dev/null @@ -1,133 +0,0 @@ -Fetching data from a stream via a consumer group, and not acknowledging -such data, has the effect of creating *pending entries*. This is -well explained in the `XREADGROUP` command, and even better in our -[introduction to Streams](../topics/streams-intro.md). The `XACK` command -will immediately remove the pending entry from the Pending Entries List (PEL) -since once a message is successfully processed, there is no longer need -for the consumer group to track it and to remember the current owner -of the message. - -The `XPENDING` command is the interface to inspect the list of pending -messages, and is as thus a very important command in order to observe -and understand what is happening with a streams consumer groups: what -clients are active, what messages are pending to be consumed, or to see -if there are idle messages. Moreover this command, together with `XCLAIM` -is used in order to implement recovering of consumers that are failing -for a long time, and as a result certain messages are not processed: a -different consumer can claim the message and continue. This is better -explained in the [streams intro](../topics/streams-intro.md) and in the -`XCLAIM` command page, and is not covered here. - -## Summary form of XPENDING - -When `XPENDING` is called with just a key name and a consumer group -name, it just outputs a summary about the pending messages in a given -consumer group. In the following example, we create a consumer group and -immediately create a pending message by reading from the group with -`XREADGROUP`. - -``` -> XGROUP CREATE mystream group55 0-0 -OK - -> XREADGROUP GROUP group55 consumer-123 COUNT 1 STREAMS mystream > -1) 1) "mystream" - 2) 1) 1) 1526984818136-0 - 2) 1) "duration" - 2) "1532" - 3) "event-id" - 4) "5" - 5) "user-id" - 6) "7782813" -``` - -We expect the pending entries list for the consumer group `group55` to -have a message right now: consumer named `consumer-123` fetched the -message without acknowledging its processing. The simple `XPENDING` -form will give us this information: - -``` -> XPENDING mystream group55 -1) (integer) 1 -2) 1526984818136-0 -3) 1526984818136-0 -4) 1) 1) "consumer-123" - 2) "1" -``` - -In this form, the command outputs the total number of pending messages for this -consumer group, which is one, followed by the smallest and greatest ID among the -pending messages, and then list every consumer in the consumer group with -at least one pending message, and the number of pending messages it has. - -## Extended form of XPENDING - -The summary provides a good overview, but sometimes we are interested in the -details. In order to see all the pending messages with more associated -information we need to also pass a range of IDs, in a similar way we do it with -`XRANGE`, and a non optional *count* argument, to limit the number -of messages returned per call: - -``` -> XPENDING mystream group55 - + 10 -1) 1) 1526984818136-0 - 2) "consumer-123" - 3) (integer) 196415 - 4) (integer) 1 -``` - -In the extended form we no longer see the summary information, instead there -is detailed information for each message in the pending entries list. For -each message four attributes are returned: - -1. The ID of the message. -2. The name of the consumer that fetched the message and has still to acknowledge it. We call it the current *owner* of the message. -3. The number of milliseconds that elapsed since the last time this message was delivered to this consumer. -4. The number of times this message was delivered. - -The deliveries counter, that is the fourth element in the array, is incremented -when some other consumer *claims* the message with `XCLAIM`, or when the -message is delivered again via `XREADGROUP`, when accessing the history -of a consumer in a consumer group (see the `XREADGROUP` page for more info). - -It is possible to pass an additional argument to the command, in order -to see the messages having a specific owner: - -``` -> XPENDING mystream group55 - + 10 consumer-123 -``` - -But in the above case the output would be the same, since we have pending -messages only for a single consumer. However what is important to keep in -mind is that this operation, filtering by a specific consumer, is not -inefficient even when there are many pending messages from many consumers: -we have a pending entries list data structure both globally, and for -every consumer, so we can very efficiently show just messages pending for -a single consumer. - -## Idle time filter - -It is also possible to filter pending stream entries by their idle-time, -given in milliseconds (useful for `XCLAIM`ing entries that have not been -processed for some time): - -``` -> XPENDING mystream group55 IDLE 9000 - + 10 -> XPENDING mystream group55 IDLE 9000 - + 10 consumer-123 -``` - -The first case will return the first 10 (or less) PEL entries of the entire group -that are idle for over 9 seconds, whereas in the second case only those of -`consumer-123`. - -## Exclusive ranges and iterating the PEL - -The `XPENDING` command allows iterating over the pending entries just like -`XRANGE` and `XREVRANGE` allow for the stream's entries. You can do this by -prefixing the ID of the last-read pending entry with the `(` character that -denotes an open (exclusive) range, and proving it to the subsequent call to the -command. - -## Reply - -* Array: different data depending on the way XPENDING is called, as explained on this page. diff --git a/commands/xrange.md b/commands/xrange.md deleted file mode 100644 index 414d2b1b..00000000 --- a/commands/xrange.md +++ /dev/null @@ -1,202 +0,0 @@ -The command returns the stream entries matching a given range of IDs. -The range is specified by a minimum and maximum ID. All the entries having -an ID between the two specified or exactly one of the two IDs specified -(closed interval) are returned. - -The `XRANGE` command has a number of applications: - -* Returning items in a specific time range. This is possible because - Stream IDs are [related to time](../topics/streams-intro.md). -* Iterating a stream incrementally, returning just - a few items at every iteration. However it is semantically much more - robust than the `SCAN` family of functions. -* Fetching a single entry from a stream, providing the ID of the entry - to fetch two times: as start and end of the query interval. - -The command also has a reciprocal command returning items in the -reverse order, called `XREVRANGE`, which is otherwise identical. - -## `-` and `+` special IDs - -The `-` and `+` special IDs mean respectively the minimum ID possible -and the maximum ID possible inside a stream, so the following command -will just return every entry in the stream: - -``` -> XRANGE somestream - + -1) 1) 1526985054069-0 - 2) 1) "duration" - 2) "72" - 3) "event-id" - 4) "9" - 5) "user-id" - 6) "839248" -2) 1) 1526985069902-0 - 2) 1) "duration" - 2) "415" - 3) "event-id" - 4) "2" - 5) "user-id" - 6) "772213" -... other entries here ... -``` - -The `-` and `+` special IDs mean, respectively, the minimal and maximal range IDs, -however they are nicer to type. - -## Incomplete IDs - -Stream IDs are composed of two parts, a Unix millisecond time stamp and a -sequence number for entries inserted in the same millisecond. It is possible -to use `XRANGE` specifying just the first part of the ID, the millisecond time, -like in the following example: - -``` -> XRANGE somestream 1526985054069 1526985055069 -``` - -In this case, `XRANGE` will auto-complete the start interval with `-0` -and end interval with `-18446744073709551615`, in order to return all the -entries that were generated between a given millisecond and the end of -the other specified millisecond. This also means that repeating the same -millisecond two times, we get all the entries within such millisecond, -because the sequence number range will be from zero to the maximum. - -Used in this way `XRANGE` works as a range query command to obtain entries -in a specified time. This is very handy in order to access the history -of past events in a stream. - -## Exclusive ranges - -The range is close (inclusive) by default, meaning that the reply can include -entries with IDs matching the query's start and end intervals. It is possible -to specify an open interval (exclusive) by prefixing the ID with the -character `(`. This is useful for iterating the stream, as explained below. - -## Returning a maximum number of entries - -Using the **COUNT** option it is possible to reduce the number of entries -reported. This is a very important feature even if it may look marginal, -because it allows, for instance, to model operations such as *give me -the entry greater or equal to the following*: - -``` -> XRANGE somestream 1526985054069-0 + COUNT 1 -1) 1) 1526985054069-0 - 2) 1) "duration" - 2) "72" - 3) "event-id" - 4) "9" - 5) "user-id" - 6) "839248" -``` - -In the above case the entry `1526985054069-0` exists, otherwise the server -would have sent us the next one. Using `COUNT` is also the base in order to -use `XRANGE` as an iterator. - -## Iterating a stream - -In order to iterate a stream, we can proceed as follows. Let's assume that -we want two elements per iteration. We start fetching the first two -elements, which is trivial: - -``` -> XRANGE writers - + COUNT 2 -1) 1) 1526985676425-0 - 2) 1) "name" - 2) "Virginia" - 3) "surname" - 4) "Woolf" -2) 1) 1526985685298-0 - 2) 1) "name" - 2) "Jane" - 3) "surname" - 4) "Austen" -``` - -Then instead of starting the iteration again from `-`, as the start -of the range we use the entry ID of the *last* entry returned by the -previous `XRANGE` call as an exclusive interval. - -The ID of the last entry is `1526985685298-0`, so we just prefix it -with a '(', and continue our iteration: - -``` -> XRANGE writers (1526985685298-0 + COUNT 2 -1) 1) 1526985691746-0 - 2) 1) "name" - 2) "Toni" - 3) "surname" - 4) "Morrison" -2) 1) 1526985712947-0 - 2) 1) "name" - 2) "Agatha" - 3) "surname" - 4) "Christie" -``` - -And so forth. Eventually this will allow to visit all the entries in the -stream. Obviously, we can start the iteration from any ID, or even from -a specific time, by providing a given incomplete start ID. Moreover, we -can limit the iteration to a given ID or time, by providing an end -ID or incomplete ID instead of `+`. - -The command `XREAD` is also able to iterate the stream. -The command `XREVRANGE` can iterate the stream reverse, from higher IDs -(or times) to lower IDs (or times). - -## Fetching single items - -If you look for an `XGET` command you'll be disappointed because `XRANGE` -is effectively the way to go in order to fetch a single entry from a -stream. All you have to do is to specify the ID two times in the arguments -of XRANGE: - -``` -> XRANGE mystream 1526984818136-0 1526984818136-0 -1) 1) 1526984818136-0 - 2) 1) "duration" - 2) "1532" - 3) "event-id" - 4) "5" - 5) "user-id" - 6) "7782813" -``` - -## Additional information about streams - -For further information about streams please check our -[introduction to Streams document](../topics/streams-intro.md). - -## Reply - -Array of stream entries with IDs matching the specified range. - -## Examples - -``` -127.0.0.1:6379> XADD writers * name Virginia surname Woolf -"1714701492065-0" -127.0.0.1:6379> XADD writers * name Jane surname Austen -"1714701492075-0" -127.0.0.1:6379> XADD writers * name Toni surname Morrison -"1714701492084-0" -127.0.0.1:6379> XADD writers * name Agatha surname Christie -"1714701492094-0" -127.0.0.1:6379> XADD writers * name Ngozi surname Adichie -"1714701492104-0" -127.0.0.1:6379> XLEN writers -(integer) 5 -127.0.0.1:6379> XRANGE writers - + COUNT 2 -1) 1) "1714701492065-0" - 2) 1) "name" - 2) "Virginia" - 3) "surname" - 4) "Woolf" -2) 1) "1714701492075-0" - 2) 1) "name" - 2) "Jane" - 3) "surname" - 4) "Austen" -``` diff --git a/commands/xread.md b/commands/xread.md deleted file mode 100644 index 5e58f496..00000000 --- a/commands/xread.md +++ /dev/null @@ -1,209 +0,0 @@ -Read data from one or multiple streams, only returning entries with an -ID greater than the last received ID reported by the caller. -This command has an option to block if items are not available, in a similar -fashion to `BRPOP` or `BZPOPMIN` and others. - -Please note that before reading this page, if you are new to streams, -we recommend to read [our introduction to Streams](../topics/streams-intro.md). - -## Non-blocking usage - -If the **BLOCK** option is not used, the command is synchronous, and can -be considered somewhat related to `XRANGE`: it will return a range of items -inside streams, however it has two fundamental differences compared to `XRANGE` -even if we just consider the synchronous usage: - -* This command can be called with multiple streams if we want to read at - the same time from a number of keys. This is a key feature of `XREAD` because - especially when blocking with **BLOCK**, to be able to listen with a single - connection to multiple keys is a vital feature. -* While `XRANGE` returns items in a range of IDs, `XREAD` is more suited in - order to consume the stream starting from the first entry which is greater - than any other entry we saw so far. So what we pass to `XREAD` is, for each - stream, the ID of the last element that we received from that stream. - -For example, if I have two streams `mystream` and `writers`, and I want to -read data from both the streams starting from the first element they contain, -I could call `XREAD` like in the following example. - -Note: we use the **COUNT** option in the example, so that for each stream -the call will return at maximum two elements per stream. - -``` -> XREAD COUNT 2 STREAMS mystream writers 0-0 0-0 -1) 1) "mystream" - 2) 1) 1) 1526984818136-0 - 2) 1) "duration" - 2) "1532" - 3) "event-id" - 4) "5" - 5) "user-id" - 6) "7782813" - 2) 1) 1526999352406-0 - 2) 1) "duration" - 2) "812" - 3) "event-id" - 4) "9" - 5) "user-id" - 6) "388234" -2) 1) "writers" - 2) 1) 1) 1526985676425-0 - 2) 1) "name" - 2) "Virginia" - 3) "surname" - 4) "Woolf" - 2) 1) 1526985685298-0 - 2) 1) "name" - 2) "Jane" - 3) "surname" - 4) "Austen" -``` - -The **STREAMS** option is mandatory and MUST be the final option because -such option gets a variable length of argument in the following format: - - STREAMS key_1 key_2 key_3 ... key_N ID_1 ID_2 ID_3 ... ID_N - -So we start with a list of keys, and later continue with all the associated -IDs, representing *the last ID we received for that stream*, so that the -call will serve us only greater IDs from the same stream. - -For instance in the above example, the last items that we received -for the stream `mystream` has ID `1526999352406-0`, while for the -stream `writers` has the ID `1526985685298-0`. - -To continue iterating the two streams I'll call: - -``` -> XREAD COUNT 2 STREAMS mystream writers 1526999352406-0 1526985685298-0 -1) 1) "mystream" - 2) 1) 1) 1526999626221-0 - 2) 1) "duration" - 2) "911" - 3) "event-id" - 4) "7" - 5) "user-id" - 6) "9488232" -2) 1) "writers" - 2) 1) 1) 1526985691746-0 - 2) 1) "name" - 2) "Toni" - 3) "surname" - 4) "Morrison" - 2) 1) 1526985712947-0 - 2) 1) "name" - 2) "Agatha" - 3) "surname" - 4) "Christie" -``` - -And so forth. Eventually, the call will not return any item, but just an -empty array, then we know that there is nothing more to fetch from our -stream (and we would have to retry the operation, hence this command -also supports a blocking mode). - -## Incomplete IDs - -To use incomplete IDs is valid, like it is valid for `XRANGE`. However -here the sequence part of the ID, if missing, is always interpreted as -zero, so the command: - -``` -> XREAD COUNT 2 STREAMS mystream writers 0 0 -``` - -is exactly equivalent to - -``` -> XREAD COUNT 2 STREAMS mystream writers 0-0 0-0 -``` - -## Blocking for data - -In its synchronous form, the command can get new data as long as there -are more items available. However, at some point, we'll have to wait for -producers of data to use `XADD` to push new entries inside the streams -we are consuming. In order to avoid polling at a fixed or adaptive interval -the command is able to block if it could not return any data, according -to the specified streams and IDs, and automatically unblock once one of -the requested keys accept data. - -It is important to understand that this command *fans out* to all the -clients that are waiting for the same range of IDs, so every consumer will -get a copy of the data, unlike to what happens when blocking list pop -operations are used. - -In order to block, the **BLOCK** option is used, together with the number -of milliseconds we want to block before timing out. Normally Valkey blocking -commands take timeouts in seconds, however this command takes a millisecond -timeout, even if normally the server will have a timeout resolution near -to 0.1 seconds. This time it is possible to block for a shorter time in -certain use cases, and if the server internals will improve over time, it is -possible that the resolution of timeouts will improve. - -When the **BLOCK** command is passed, but there is data to return at -least in one of the streams passed, the command is executed synchronously -*exactly like if the BLOCK option would be missing*. - -This is an example of blocking invocation, where the command later returns -a null reply because the timeout has elapsed without new data arriving: - -``` -> XREAD BLOCK 1000 STREAMS mystream 1526999626221-0 -(nil) -``` - -## The special `$` ID. - -When blocking sometimes we want to receive just entries that are added -to the stream via `XADD` starting from the moment we block. In such a case -we are not interested in the history of already added entries. For -this use case, we would have to check the stream top element ID, and use -such ID in the `XREAD` command line. This is not clean and requires to -call other commands, so instead it is possible to use the special `$` -ID to signal the stream that we want only the new things. - -It is **very important** to understand that you should use the `$` -ID only for the first call to `XREAD`. Later the ID should be the one -of the last reported item in the stream, otherwise you could miss all -the entries that are added in between. - -This is how a typical `XREAD` call looks like in the first iteration -of a consumer willing to consume only new entries: - -``` -> XREAD BLOCK 5000 COUNT 100 STREAMS mystream $ -``` - -Once we get some replies, the next call will be something like: - -``` -> XREAD BLOCK 5000 COUNT 100 STREAMS mystream 1526999644174-3 -``` - -And so forth. - -## How multiple clients blocked on a single stream are served - -Blocking list operations on lists or sorted sets have a *pop* behavior. -Basically, the element is removed from the list or sorted set in order -to be returned to the client. In this scenario you want the items -to be consumed in a fair way, depending on the moment clients blocked -on a given key arrived. Normally Valkey uses the FIFO semantics in this -use cases. - -However note that with streams this is not a problem: stream entries -are not removed from the stream when clients are served, so every -client waiting will be served as soon as an `XADD` command provides -data to the stream. - -Reading the [Streams introduction](../topics/streams-intro.md) is highly -suggested in order to understand more about the streams overall behavior -and semantics. - -## Reply - -One of the following: - -* Map where each key is a stream key name and each value is the entries reported for that key. The entries reported are full stream entries, having IDs and the list of all the fields and values. Field and values are guaranteed to be reported in the same order they were added by `XADD`. In RESP2, the reply is instead an array where each element is a two-element array containing the key name and the entries reported for that key. -* Null: if the _BLOCK_ option is given and a timeout occurs, or if there is no stream that can be served. diff --git a/commands/xreadgroup.md b/commands/xreadgroup.md deleted file mode 100644 index 5519e824..00000000 --- a/commands/xreadgroup.md +++ /dev/null @@ -1,141 +0,0 @@ -The `XREADGROUP` command is a special version of the `XREAD` command -with support for consumer groups. Probably you will have to understand the -`XREAD` command before reading this page will makes sense. - -Moreover, if you are new to streams, we recommend to read our -[introduction to Streams](../topics/streams-intro.md). -Make sure to understand the concept of consumer group in the introduction -so that following how this command works will be simpler. - -## Consumer groups in 30 seconds - -The difference between this command and the vanilla `XREAD` is that this -one supports consumer groups. - -Without consumer groups, just using `XREAD`, all the clients are served with all the entries arriving in a stream. Instead using consumer groups with `XREADGROUP`, it is possible to create groups of clients that consume different parts of the messages arriving in a given stream. If, for instance, the stream gets the new entries A, B, and C and there are two consumers reading via a consumer group, one client will get, for instance, the messages A and C, and the other the message B, and so forth. - -Within a consumer group, a given consumer (that is, just a client consuming messages from the stream), has to identify with a unique *consumer name*. Which is just a string. - -One of the guarantees of consumer groups is that a given consumer can only see the history of messages that were delivered to it, so a message has just a single owner. However there is a special feature called *message claiming* that allows other consumers to claim messages in case there is a non recoverable failure of some consumer. In order to implement such semantics, consumer groups require explicit acknowledgment of the messages successfully processed by the consumer, via the `XACK` command. This is needed because the stream will track, for each consumer group, who is processing what message. - -This is how to understand if you want to use a consumer group or not: - -1. If you have a stream and multiple clients, and you want all the clients to get all the messages, you do not need a consumer group. -2. If you have a stream and multiple clients, and you want the stream to be *partitioned* or *sharded* across your clients, so that each client will get a sub set of the messages arriving in a stream, you need a consumer group. - -## Differences between XREAD and XREADGROUP - -From the point of view of the syntax, the commands are almost the same, -however `XREADGROUP` *requires* a special and mandatory option: - - GROUP - -The group name is just the name of a consumer group associated to the stream. -The group is created using the `XGROUP` command. The consumer name is the -string that is used by the client to identify itself inside the group. -The consumer is auto created inside the consumer group the first time it -is saw. Different clients should select a different consumer name. - -When you read with `XREADGROUP`, the server will *remember* that a given -message was delivered to you: the message will be stored inside the -consumer group in what is called a Pending Entries List (PEL), that is -a list of message IDs delivered but not yet acknowledged. - -The client will have to acknowledge the message processing using `XACK` -in order for the pending entry to be removed from the PEL. The PEL -can be inspected using the `XPENDING` command. - -The `NOACK` subcommand can be used to avoid adding the message to the PEL in -cases where reliability is not a requirement and the occasional message loss -is acceptable. This is equivalent to acknowledging the message when it is read. - -The ID to specify in the **STREAMS** option when using `XREADGROUP` can -be one of the following two: - -* The special `>` ID, which means that the consumer want to receive only messages that were *never delivered to any other consumer*. It just means, give me new messages. -* Any other ID, that is, 0 or any other valid ID or incomplete ID (just the millisecond time part), will have the effect of returning entries that are pending for the consumer sending the command with IDs greater than the one provided. So basically if the ID is not `>`, then the command will just let the client access its pending entries: messages delivered to it, but not yet acknowledged. Note that in this case, both `BLOCK` and `NOACK` are ignored. - -Like `XREAD` the `XREADGROUP` command can be used in a blocking way. There -are no differences in this regard. - -## What happens when a message is delivered to a consumer? - -Two things: - -1. If the message was never delivered to anyone, that is, if we are talking about a new message, then a PEL (Pending Entries List) is created. -2. If instead the message was already delivered to this consumer, and it is just re-fetching the same message again, then the *last delivery counter* is updated to the current time, and the *number of deliveries* is incremented by one. You can access those message properties using the `XPENDING` command. - -## Usage example - -Normally you use the command like that in order to get new messages and -process them. In pseudo-code: - -``` -WHILE true - entries = XREADGROUP GROUP $GroupName $ConsumerName BLOCK 2000 COUNT 10 STREAMS mystream > - if entries == nil - puts "Timeout... try again" - CONTINUE - end - - FOREACH entries AS stream_entries - FOREACH stream_entries as message - process_message(message.id,message.fields) - - # ACK the message as processed - XACK mystream $GroupName message.id - END - END -END -``` - -In this way the example consumer code will fetch only new messages, process -them, and acknowledge them via `XACK`. However the example code above is -not complete, because it does not handle recovering after a crash. What -will happen if we crash in the middle of processing messages, is that our -messages will remain in the pending entries list, so we can access our -history by giving `XREADGROUP` initially an ID of 0, and performing the same -loop. Once providing an ID of 0 the reply is an empty set of messages, we -know that we processed and acknowledged all the pending messages: we -can start to use `>` as ID, in order to get the new messages and rejoin the -consumers that are processing new things. - -To see how the command actually replies, please check the `XREAD` command page. - -## What happens when a pending message is deleted? - -Entries may be deleted from the stream due to trimming or explicit calls to `XDEL` at any time. -By design, Valkey doesn't prevent the deletion of entries that are present in the stream's PELs. -When this happens, the PELs retain the deleted entries' IDs, but the actual entry payload is no longer available. -Therefore, when reading such PEL entries, Valkey will return a null value in place of their respective data. - -Example: - -``` -> XADD mystream 1 myfield mydata -"1-0" -> XGROUP CREATE mystream mygroup 0 -OK -> XREADGROUP GROUP mygroup myconsumer STREAMS mystream > -1) 1) "mystream" - 2) 1) 1) "1-0" - 2) 1) "myfield" - 2) "mydata" -> XDEL mystream 1-0 -(integer) 1 -> XREADGROUP GROUP mygroup myconsumer STREAMS mystream 0 -1) 1) "mystream" - 2) 1) 1) "1-0" - 2) (nil) -``` - -Reading the [Streams introduction](../topics/streams-intro.md) is highly -suggested in order to understand more about the streams overall behavior -and semantics. - -## Reply - -One of the following: - -* Map where each key is a stream key name and each value is the entries reported for that key. The entries reported are full stream entries, having IDs and the list of all the fields and values. Field and values are guaranteed to be reported in the same order they were added by `XADD`. In RESP2, the reply is instead an array where each element is a two-element array containing the key name and the entries reported for that key. -* Null: if the _BLOCK_ option is given and a timeout occurs, or if there is no stream that can be served. diff --git a/commands/xrevrange.md b/commands/xrevrange.md deleted file mode 100644 index e8ae862b..00000000 --- a/commands/xrevrange.md +++ /dev/null @@ -1,42 +0,0 @@ -This command is exactly like `XRANGE`, but with the notable difference of -returning the entries in reverse order, and also taking the start-end -range in reverse order: in `XREVRANGE` you need to state the *end* ID -and later the *start* ID, and the command will produce all the element -between (or exactly like) the two IDs, starting from the *end* side. - -So for instance, to get all the elements from the higher ID to the lower -ID one could use: - - XREVRANGE somestream + - - -Similarly to get just the last element added into the stream it is -enough to send: - - XREVRANGE somestream + - COUNT 1 - -## Reply - -Array: The command returns the entries with IDs matching the specified range. The returned entries are complete, which means that the ID and all the fields they are composed of are returned. Moreover, the entries are returned with their fields and values in the same order as `XADD` added them. - -## Examples - -``` -127.0.0.1:6379> XADD writers * name Virginia surname Woolf -"1714701492147-0" -127.0.0.1:6379> XADD writers * name Jane surname Austen -"1714701492157-0" -127.0.0.1:6379> XADD writers * name Toni surname Morrison -"1714701492167-0" -127.0.0.1:6379> XADD writers * name Agatha surname Christie -"1714701492177-0" -127.0.0.1:6379> XADD writers * name Ngozi surname Adichie -"1714701492187-0" -127.0.0.1:6379> XLEN writers -(integer) 5 -127.0.0.1:6379> XREVRANGE writers + - COUNT 1 -1) 1) "1714701492187-0" - 2) 1) "name" - 2) "Ngozi" - 3) "surname" - 4) "Adichie" -``` diff --git a/commands/xsetid.md b/commands/xsetid.md deleted file mode 100644 index ceb1f02e..00000000 --- a/commands/xsetid.md +++ /dev/null @@ -1,6 +0,0 @@ -The `XSETID` command is an internal command. -It is used by a Valkey primary to replicate the last delivered ID of streams. - -## Reply - -`OK`. diff --git a/commands/xtrim.md b/commands/xtrim.md deleted file mode 100644 index 7784e2e1..00000000 --- a/commands/xtrim.md +++ /dev/null @@ -1,68 +0,0 @@ -`XTRIM` trims the stream by evicting older entries (entries with lower IDs) if needed. - -Trimming the stream can be done using one of these strategies: - -* `MAXLEN`: Evicts entries as long as the stream's length exceeds the specified `threshold`, where `threshold` is a positive integer. -* `MINID`: Evicts entries with IDs lower than `threshold`, where `threshold` is a stream ID. - -For example, this will trim the stream to exactly the latest 1000 items: - -``` -XTRIM mystream MAXLEN 1000 -``` - -Whereas in this example, all entries that have an ID lower than 649085820-0 will be evicted: - -``` -XTRIM mystream MINID 649085820 -``` - -By default, or when provided with the optional `=` argument, the command performs exact trimming. - -Depending on the strategy, exact trimming means: - -* `MAXLEN`: the trimmed stream's length will be exactly the minimum between its original length and the specified `threshold`. -* `MINID`: the oldest ID in the stream will be exactly the maximum between its original oldest ID and the specified `threshold`. - -Nearly exact trimming ---- - -Because exact trimming may require additional effort from the Valkey server, the optional `~` argument can be provided to make it more efficient. - -For example: - -``` -XTRIM mystream MAXLEN ~ 1000 -``` - -The `~` argument between the `MAXLEN` strategy and the `threshold` means that the user is requesting to trim the stream so its length is **at least** the `threshold`, but possibly slightly more. -In this case, Valkey will stop trimming early when performance can be gained (for example, when a whole macro node in the data structure can't be removed). -This makes trimming much more efficient, and it is usually what you want, although after trimming, the stream may have few tens of additional entries over the `threshold`. - -Another way to control the amount of work done by the command when using the `~`, is the `LIMIT` clause. -When used, it specifies the maximal `count` of entries that will be evicted. -When `LIMIT` and `count` aren't specified, the default value of 100 * the number of entries in a macro node will be implicitly used as the `count`. -Specifying the value 0 as `count` disables the limiting mechanism entirely. - -## Reply - -Integer: The number of entries deleted from the stream. - -## Examples - -``` -127.0.0.1:6379> XADD mystream * field1 A field2 B field3 C field4 D -"1714701492231-0" -127.0.0.1:6379> XTRIM mystream MAXLEN 2 -(integer) 0 -127.0.0.1:6379> XRANGE mystream - + -1) 1) "1714701492231-0" - 2) 1) "field1" - 2) "A" - 3) "field2" - 4) "B" - 5) "field3" - 6) "C" - 7) "field4" - 8) "D" -``` diff --git a/commands/zadd.md b/commands/zadd.md deleted file mode 100644 index 0bf55ec0..00000000 --- a/commands/zadd.md +++ /dev/null @@ -1,88 +0,0 @@ -Adds all the specified members with the specified scores to the sorted set -stored at `key`. -It is possible to specify multiple score / member pairs. -If a specified member is already a member of the sorted set, the score is -updated and the element reinserted at the right position to ensure the correct -ordering. - -If `key` does not exist, a new sorted set with the specified members as sole -members is created, like if the sorted set was empty. If the key exists but does not hold a sorted set, an error is returned. - -The score values should be the string representation of a double precision floating point number. `+inf` and `-inf` values are valid values as well. - -ZADD options ---- - -ZADD supports a list of options, specified after the name of the key and before -the first score argument. Options are: - -* **XX**: Only update elements that already exist. Don't add new elements. -* **NX**: Only add new elements. Don't update already existing elements. -* **LT**: Only update existing elements if the new score is **less than** the current score. This flag doesn't prevent adding new elements. -* **GT**: Only update existing elements if the new score is **greater than** the current score. This flag doesn't prevent adding new elements. -* **CH**: Modify the return value from the number of new elements added, to the total number of elements changed (CH is an abbreviation of *changed*). Changed elements are **new elements added** and elements already existing for which **the score was updated**. So elements specified in the command line having the same score as they had in the past are not counted. Note: normally the return value of `ZADD` only counts the number of new elements added. -* **INCR**: When this option is specified `ZADD` acts like `ZINCRBY`. Only one score-element pair can be specified in this mode. - -Note: The **GT**, **LT** and **NX** options are mutually exclusive. - -Range of integer scores that can be expressed precisely ---- - -Sorted Sets use a *double 64-bit floating point number* to represent the score. In all the architectures we support, this is represented as an **IEEE 754 floating point number**, that is able to represent precisely integer numbers between `-(2^53)` and `+(2^53)` included. In more practical terms, all the integers between -9007199254740992 and 9007199254740992 are perfectly representable. Larger integers, or fractions, are internally represented in exponential form, so it is possible that you get only an approximation of the decimal number, or of the very big integer, that you set as score. - -Sorted sets 101 ---- - -Sorted sets are sorted by their score in an ascending way. -The same element only exists a single time, no repeated elements are -permitted. The score can be modified both by `ZADD` that will update the -element score, and as a side effect, its position on the sorted set, and -by `ZINCRBY` that can be used in order to update the score relatively to its -previous value. - -The current score of an element can be retrieved using the `ZSCORE` command, -that can also be used to verify if an element already exists or not. - -For an introduction to sorted sets, see the data types page on [sorted -sets][tdtss]. - -[tdtss]: ../topics/data-types.md#sorted-sets - -Elements with the same score ---- - -While the same element can't be repeated in a sorted set since every element -is unique, it is possible to add multiple different elements *having the same score*. When multiple elements have the same score, they are *ordered lexicographically* (they are still ordered by score as a first key, however, locally, all the elements with the same score are relatively ordered lexicographically). - -The lexicographic ordering used is binary, it compares strings as array of bytes. - -If the user inserts all the elements in a sorted set with the same score (for example 0), all the elements of the sorted set are sorted lexicographically, and range queries on elements are possible using the command `ZRANGEBYLEX` (Note: it is also possible to query sorted sets by range of scores using `ZRANGEBYSCORE`). - -## Reply - -Any of the following: - -* Null: if the operation was aborted because of a conflict with one of the `XX`/`NX`/`LT`/`GT` options. -* Integer: the number of new members when the _CH_ option is not used. -* Integer: the number of new or updated members when the _CH_ option is used. -* Double: the updated score of the member when the _INCR_ option is used. - -## Examples - -``` -127.0.0.1:6379> ZADD myzset 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD myzset 1 "uno" -(integer) 1 -127.0.0.1:6379> ZADD myzset 2 "two" 3 "three" -(integer) 2 -127.0.0.1:6379> ZRANGE myzset 0 -1 WITHSCORES -1) "one" -2) "1" -3) "uno" -4) "1" -5) "two" -6) "2" -7) "three" -8) "3" -``` diff --git a/commands/zcard.md b/commands/zcard.md deleted file mode 100644 index f875ab83..00000000 --- a/commands/zcard.md +++ /dev/null @@ -1,17 +0,0 @@ -Returns the sorted set cardinality (number of elements) of the sorted set stored -at `key`. - -## Reply - -Integer: the cardinality (number of members) of the sorted set, or 0 if the key doesn't exist. - -## Examples - -``` -127.0.0.1:6379> ZADD myzset 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD myzset 2 "two" -(integer) 1 -127.0.0.1:6379> ZCARD myzset -(integer) 2 -``` diff --git a/commands/zcount.md b/commands/zcount.md deleted file mode 100644 index e73472d7..00000000 --- a/commands/zcount.md +++ /dev/null @@ -1,26 +0,0 @@ -Returns the number of elements in the sorted set at `key` with a score between -`min` and `max`. - -The `min` and `max` arguments have the same semantic as described for -`ZRANGEBYSCORE`. - -Note: the command has a complexity of just O(log(N)) because it uses elements ranks (see `ZRANK`) to get an idea of the range. Because of this there is no need to do a work proportional to the size of the range. - -## Reply - -Integer: the number of members in the specified score range. - -## Examples - -``` -127.0.0.1:6379> ZADD myzset 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD myzset 2 "two" -(integer) 1 -127.0.0.1:6379> ZADD myzset 3 "three" -(integer) 1 -127.0.0.1:6379> ZCOUNT myzset -inf +inf -(integer) 3 -127.0.0.1:6379> ZCOUNT myzset (1 3 -(integer) 2 -``` diff --git a/commands/zdiff.md b/commands/zdiff.md deleted file mode 100644 index 4a69b1e2..00000000 --- a/commands/zdiff.md +++ /dev/null @@ -1,26 +0,0 @@ -This command is similar to `ZDIFFSTORE`, but instead of storing the resulting -sorted set, it is returned to the client. - -## Reply - -* Array: the result of the difference including, optionally, scores when the _WITHSCORES_ option is used. - -## Examples - -``` -127.0.0.1:6379> ZADD zset1 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD zset1 2 "two" -(integer) 1 -127.0.0.1:6379> ZADD zset1 3 "three" -(integer) 1 -127.0.0.1:6379> ZADD zset2 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD zset2 2 "two" -(integer) 1 -127.0.0.1:6379> ZDIFF 2 zset1 zset2 -1) "three" -127.0.0.1:6379> ZDIFF 2 zset1 zset2 WITHSCORES -1) "three" -2) "3" -``` diff --git a/commands/zdiffstore.md b/commands/zdiffstore.md deleted file mode 100644 index 5bfac0b7..00000000 --- a/commands/zdiffstore.md +++ /dev/null @@ -1,31 +0,0 @@ -Computes the difference between the first and all successive input sorted sets -and stores the result in `destination`. The total number of input keys is -specified by `numkeys`. - -Keys that do not exist are considered to be empty sets. - -If `destination` already exists, it is overwritten. - -## Reply - -Integer: the number of members in the resulting sorted set at _destination_. - -## Examples - -``` -127.0.0.1:6379> ZADD zset1 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD zset1 2 "two" -(integer) 1 -127.0.0.1:6379> ZADD zset1 3 "three" -(integer) 1 -127.0.0.1:6379> ZADD zset2 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD zset2 2 "two" -(integer) 1 -127.0.0.1:6379> ZDIFFSTORE out 2 zset1 zset2 -(integer) 1 -127.0.0.1:6379> ZRANGE out 0 -1 WITHSCORES -1) "three" -2) "3" -``` diff --git a/commands/zincrby.md b/commands/zincrby.md deleted file mode 100644 index f4f30610..00000000 --- a/commands/zincrby.md +++ /dev/null @@ -1,32 +0,0 @@ -Increments the score of `member` in the sorted set stored at `key` by -`increment`. -If `member` does not exist in the sorted set, it is added with `increment` as -its score (as if its previous score was `0.0`). -If `key` does not exist, a new sorted set with the specified `member` as its -sole member is created. - -An error is returned when `key` exists but does not hold a sorted set. - -The `score` value should be the string representation of a numeric value, and -accepts double precision floating point numbers. -It is possible to provide a negative value to decrement the score. - -## Reply - -Double: the new score of _member_. - -## Examples - -``` -127.0.0.1:6379> ZADD myzset 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD myzset 2 "two" -(integer) 1 -127.0.0.1:6379> ZINCRBY myzset 2 "one" -"3" -127.0.0.1:6379> ZRANGE myzset 0 -1 WITHSCORES -1) "two" -2) "2" -3) "one" -4) "3" -``` diff --git a/commands/zinter.md b/commands/zinter.md deleted file mode 100644 index 4a4aec1f..00000000 --- a/commands/zinter.md +++ /dev/null @@ -1,31 +0,0 @@ -This command is similar to `ZINTERSTORE`, but instead of storing the resulting -sorted set, it is returned to the client. - -For a description of the `WEIGHTS` and `AGGREGATE` options, see `ZUNIONSTORE`. - -## Reply - -* Array: the result of the intersection including, optionally, scores when the _WITHSCORES_ option is used. - -## Examples - -``` -127.0.0.1:6379> ZADD zset1 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD zset1 2 "two" -(integer) 1 -127.0.0.1:6379> ZADD zset2 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD zset2 2 "two" -(integer) 1 -127.0.0.1:6379> ZADD zset2 3 "three" -(integer) 1 -127.0.0.1:6379> ZINTER 2 zset1 zset2 -1) "one" -2) "two" -127.0.0.1:6379> ZINTER 2 zset1 zset2 WITHSCORES -1) "one" -2) "2" -3) "two" -4) "4" -``` diff --git a/commands/zintercard.md b/commands/zintercard.md deleted file mode 100644 index d59a1108..00000000 --- a/commands/zintercard.md +++ /dev/null @@ -1,34 +0,0 @@ -This command is similar to `ZINTER`, but instead of returning the result set, it returns just the cardinality of the result. - -Keys that do not exist are considered to be empty sets. -With one of the keys being an empty set, the resulting set is also empty (since set intersection with an empty set always results in an empty set). - -By default, the command calculates the cardinality of the intersection of all given sets. -When provided with the optional `LIMIT` argument (which defaults to 0 and means unlimited), if the intersection cardinality reaches limit partway through the computation, the algorithm will exit and yield limit as the cardinality. -Such implementation ensures a significant speedup for queries where the limit is lower than the actual intersection cardinality. - -## Reply - -Integer: the number of members in the resulting intersection. - -## Examples - -``` -127.0.0.1:6379> ZADD zset1 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD zset1 2 "two" -(integer) 1 -127.0.0.1:6379> ZADD zset2 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD zset2 2 "two" -(integer) 1 -127.0.0.1:6379> ZADD zset2 3 "three" -(integer) 1 -127.0.0.1:6379> ZINTER 2 zset1 zset2 -1) "one" -2) "two" -127.0.0.1:6379> ZINTERCARD 2 zset1 zset2 -(integer) 2 -127.0.0.1:6379> ZINTERCARD 2 zset1 zset2 LIMIT 1 -(integer) 1 -``` diff --git a/commands/zinterstore.md b/commands/zinterstore.md deleted file mode 100644 index a3dad968..00000000 --- a/commands/zinterstore.md +++ /dev/null @@ -1,40 +0,0 @@ -Computes the intersection of `numkeys` sorted sets given by the specified keys, -and stores the result in `destination`. -It is mandatory to provide the number of input keys (`numkeys`) before passing -the input keys and the other (optional) arguments. - -By default, the resulting score of an element is the sum of its scores in the -sorted sets where it exists. -Because intersection requires an element to be a member of every given sorted -set, this results in the score of every element in the resulting sorted set to -be equal to the number of input sorted sets. - -For a description of the `WEIGHTS` and `AGGREGATE` options, see `ZUNIONSTORE`. - -If `destination` already exists, it is overwritten. - -## Reply - -Integer: the number of members in the resulting sorted set at the _destination_. - -## Examples - -``` -127.0.0.1:6379> ZADD zset1 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD zset1 2 "two" -(integer) 1 -127.0.0.1:6379> ZADD zset2 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD zset2 2 "two" -(integer) 1 -127.0.0.1:6379> ZADD zset2 3 "three" -(integer) 1 -127.0.0.1:6379> ZINTERSTORE out 2 zset1 zset2 WEIGHTS 2 3 -(integer) 2 -127.0.0.1:6379> ZRANGE out 0 -1 WITHSCORES -1) "one" -2) "5" -3) "two" -4) "10" -``` diff --git a/commands/zlexcount.md b/commands/zlexcount.md deleted file mode 100644 index cbeacc45..00000000 --- a/commands/zlexcount.md +++ /dev/null @@ -1,23 +0,0 @@ -When all the elements in a sorted set are inserted with the same score, in order to force lexicographical ordering, this command returns the number of elements in the sorted set at `key` with a value between `min` and `max`. - -The `min` and `max` arguments have the same meaning as described for -`ZRANGEBYLEX`. - -Note: the command has a complexity of just O(log(N)) because it uses elements ranks (see `ZRANK`) to get an idea of the range. Because of this there is no need to do a work proportional to the size of the range. - -## Reply - -Integer: the number of members in the specified score range. - -## Examples - -``` -127.0.0.1:6379> ZADD myzset 0 a 0 b 0 c 0 d 0 e -(integer) 5 -127.0.0.1:6379> ZADD myzset 0 f 0 g -(integer) 2 -127.0.0.1:6379> ZLEXCOUNT myzset - + -(integer) 7 -127.0.0.1:6379> ZLEXCOUNT myzset [b [f -(integer) 5 -``` diff --git a/commands/zmpop.md b/commands/zmpop.md deleted file mode 100644 index 3bd2c06f..00000000 --- a/commands/zmpop.md +++ /dev/null @@ -1,62 +0,0 @@ -Pops one or more elements, that are member-score pairs, from the first non-empty sorted set in the provided list of key names. - -`ZMPOP` and `BZMPOP` are similar to the following, more limited, commands: - -- `ZPOPMIN` or `ZPOPMAX` which take only one key, and can return multiple elements. -- `BZPOPMIN` or `BZPOPMAX` which take multiple keys, but return only one element from just one key. - -See `BZMPOP` for the blocking variant of this command. - -When the `MIN` modifier is used, the elements popped are those with the lowest scores from the first non-empty sorted set. The `MAX` modifier causes elements with the highest scores to be popped. -The optional `COUNT` can be used to specify the number of elements to pop, and is set to 1 by default. - -The number of popped elements is the minimum from the sorted set's cardinality and `COUNT`'s value. - -## Reply - -One of the following: - -* Null: when no element could be popped. -* Two-element array with the first element being the name of the key from which elements were popped, and the second element is an array of the popped elements. Every entry in the elements array is also an array that contains the member and its score. - -## Examples - -``` -127.0.0.1:6379> ZMPOP 1 notsuchkey MIN -(nil) -127.0.0.1:6379> ZADD myzset 1 "one" 2 "two" 3 "three" -(integer) 3 -127.0.0.1:6379> ZMPOP 1 myzset MIN -1) "myzset" -2) 1) 1) "one" - 2) "1" -127.0.0.1:6379> ZRANGE myzset 0 -1 WITHSCORES -1) "two" -2) "2" -3) "three" -4) "3" -127.0.0.1:6379> ZMPOP 1 myzset MAX COUNT 10 -1) "myzset" -2) 1) 1) "three" - 2) "3" - 2) 1) "two" - 2) "2" -127.0.0.1:6379> ZADD myzset2 4 "four" 5 "five" 6 "six" -(integer) 3 -127.0.0.1:6379> ZMPOP 2 myzset myzset2 MIN COUNT 10 -1) "myzset2" -2) 1) 1) "four" - 2) "4" - 2) 1) "five" - 2) "5" - 3) 1) "six" - 2) "6" -127.0.0.1:6379> ZRANGE myzset 0 -1 WITHSCORES -(empty array) -127.0.0.1:6379> ZMPOP 2 myzset myzset2 MAX COUNT 10 -(nil) -127.0.0.1:6379> ZRANGE myzset2 0 -1 WITHSCORES -(empty array) -127.0.0.1:6379> EXISTS myzset myzset2 -(integer) 0 -``` diff --git a/commands/zmscore.md b/commands/zmscore.md deleted file mode 100644 index 970712fa..00000000 --- a/commands/zmscore.md +++ /dev/null @@ -1,23 +0,0 @@ -Returns the scores associated with the specified `members` in the sorted set stored at `key`. - -For every `member` that does not exist in the sorted set, a `nil` value is returned. - -## Reply - -One of the following: - -* Null: if the member does not exist in the sorted set. -* Array of double _member_ scores as double-precision floating point numbers. - -## Examples - -``` -127.0.0.1:6379> ZADD myzset 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD myzset 2 "two" -(integer) 1 -127.0.0.1:6379> ZMSCORE myzset "one" "two" "nofield" -1) "1" -2) "2" -3) (nil) -``` diff --git a/commands/zpopmax.md b/commands/zpopmax.md deleted file mode 100644 index 9f179712..00000000 --- a/commands/zpopmax.md +++ /dev/null @@ -1,25 +0,0 @@ -Removes and returns up to `count` members with the highest scores in the sorted -set stored at `key`. - -When left unspecified, the default value for `count` is 1. Specifying a `count` -value that is higher than the sorted set's cardinality will not produce an -error. When returning multiple elements, the one with the highest score will -be the first, followed by the elements with lower scores. - -## Reply - -* Array of popped elements and scores. - -## Examples - -``` -127.0.0.1:6379> ZADD myzset 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD myzset 2 "two" -(integer) 1 -127.0.0.1:6379> ZADD myzset 3 "three" -(integer) 1 -127.0.0.1:6379> ZPOPMAX myzset -1) "three" -2) "3" -``` diff --git a/commands/zpopmin.md b/commands/zpopmin.md deleted file mode 100644 index 8b6ae3ab..00000000 --- a/commands/zpopmin.md +++ /dev/null @@ -1,25 +0,0 @@ -Removes and returns up to `count` members with the lowest scores in the sorted -set stored at `key`. - -When left unspecified, the default value for `count` is 1. Specifying a `count` -value that is higher than the sorted set's cardinality will not produce an -error. When returning multiple elements, the one with the lowest score will -be the first, followed by the elements with greater scores. - -## Reply - -* Array of popped elements and scores. - -## Examples - -``` -127.0.0.1:6379> ZADD myzset 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD myzset 2 "two" -(integer) 1 -127.0.0.1:6379> ZADD myzset 3 "three" -(integer) 1 -127.0.0.1:6379> ZPOPMIN myzset -1) "one" -2) "1" -``` diff --git a/commands/zrandmember.md b/commands/zrandmember.md deleted file mode 100644 index ceef3b59..00000000 --- a/commands/zrandmember.md +++ /dev/null @@ -1,51 +0,0 @@ -When called with just the `key` argument, return a random element from the sorted set value stored at `key`. - -If the provided `count` argument is positive, return an array of **distinct elements**. -The array's length is either `count` or the sorted set's cardinality (`ZCARD`), whichever is lower. - -If called with a negative `count`, the behavior changes and the command is allowed to return the **same element multiple times**. -In this case, the number of returned elements is the absolute value of the specified `count`. - -The optional `WITHSCORES` modifier changes the reply so it includes the respective scores of the randomly selected elements from the sorted set. - -## Reply - -String: without the additional _count_ argument, the command returns a randomly selected member, or null when _key_ doesn't exist. - -Array: when the additional _count_ argument is passed, the command returns an array of members, or an empty array when _key_ doesn't exist. If the _WITHSCORES_ modifier is used, the reply is a list of members and their scores from the sorted set. - -## Examples - -``` -127.0.0.1:6379> ZADD dadi 1 uno 2 due 3 tre 4 quattro 5 cinque 6 sei -(integer) 6 -127.0.0.1:6379> ZRANDMEMBER dadi -"uno" -127.0.0.1:6379> ZRANDMEMBER dadi -"uno" -127.0.0.1:6379> ZRANDMEMBER dadi -5 WITHSCORES - 1) "cinque" - 2) "5" - 3) "sei" - 4) "6" - 5) "quattro" - 6) "4" - 7) "quattro" - 8) "4" - 9) "sei" -10) "6" -``` - -## Specification of the behavior when count is passed - -When the `count` argument is a positive value this command behaves as follows: - -* No repeated elements are returned. -* If `count` is bigger than the cardinality of the sorted set, the command will only return the whole sorted set without additional elements. -* The order of elements in the reply is not truly random, so it is up to the client to shuffle them if needed. - -When the `count` is a negative value, the behavior changes as follows: - -* Repeating elements are possible. -* Exactly `count` elements, or an empty array if the sorted set is empty (non-existing key), are always returned. -* The order of elements in the reply is truly random. diff --git a/commands/zrange.md b/commands/zrange.md deleted file mode 100644 index aac61ac0..00000000 --- a/commands/zrange.md +++ /dev/null @@ -1,156 +0,0 @@ -Returns the specified range of elements in the sorted set stored at ``. - -`ZRANGE` can perform different types of range queries: by index (rank), by the score, or by lexicographical order. - -This command can replace the following commands: `ZREVRANGE`, `ZRANGEBYSCORE`, `ZREVRANGEBYSCORE`, `ZRANGEBYLEX` and `ZREVRANGEBYLEX`. - -## Common behavior and options - -The order of elements is from the lowest to the highest score. Elements with the same score are ordered lexicographically. - -The optional `REV` argument reverses the ordering, so elements are ordered from highest to lowest score, and score ties are resolved by reverse lexicographical ordering. - -The optional `LIMIT` argument can be used to obtain a sub-range from the matching elements (similar to _SELECT LIMIT offset, count_ in SQL). -A negative `` returns all elements from the ``. Keep in mind that if `` is large, the sorted set needs to be traversed for `` elements before getting to the elements to return, which can add up to O(N) time complexity. - -The optional `WITHSCORES` argument supplements the command's reply with the scores of elements returned. In RESP2 the returned list contains `value1,score1,...,valueN,scoreN` instead of `value1,...,valueN`. Client libraries are free to return a more appropriate data type (suggestion: an array with (value, score) arrays/tuples). - -## Index ranges - -By default, the command performs an index range query. The `` and `` arguments represent zero-based indexes, where `0` is the first element, `1` is the next element, and so on. These arguments specify an **inclusive range**, so for example, `ZRANGE myzset 0 1` will return both the first and the second element of the sorted set. - -The indexes can also be negative numbers indicating offsets from the end of the sorted set, with `-1` being the last element of the sorted set, `-2` the penultimate element, and so on. - -Out of range indexes do not produce an error. - -If `` is greater than either the end index of the sorted set or ``, an empty list is returned. - -If `` is greater than the end index of the sorted set, Valkey will use the last element of the sorted set. - -## Score ranges - -When the `BYSCORE` option is provided, the command behaves like `ZRANGEBYSCORE` and returns the range of elements from the sorted set having scores equal or between `` and ``. - -`` and `` can be `-inf` and `+inf`, denoting the negative and positive infinities, respectively. This means that you are not required to know the highest or lowest score in the sorted set to get all elements from or up to a certain score. - -By default, the score intervals specified by `` and `` are closed (inclusive). -It is possible to specify an open interval (exclusive) by prefixing the score -with the character `(`. - -For example: - -``` -ZRANGE zset (1 5 BYSCORE -``` - -Will return all elements with `1 < score <= 5` while: - -``` -ZRANGE zset (5 (10 BYSCORE -``` - -Will return all the elements with `5 < score < 10` (5 and 10 excluded). - -## Reverse ranges - -Using the `REV` option reverses the sorted set, with index 0 as the element with the highest score. - -By default, `` must be less than or equal to `` to return anything. -However, if the `BYSCORE`, or `BYLEX` options are selected, the `` is the highest score to consider, and `` is the lowest score to consider, therefore `` must be greater than or equal to `` in order to return anything. - -For example: - -``` -ZRANGE zset 5 10 REV -``` - -Will return the elements between index 5 and 10 in the reversed index. - -``` -ZRANGE zset 10 5 REV BYSCORE -``` - -Will return all elements with scores less than 10 and greater than 5. - -## Lexicographical ranges - -When the `BYLEX` option is used, the command behaves like `ZRANGEBYLEX` and returns the range of elements from the sorted set between the `` and `` lexicographical closed range intervals. - -Note that lexicographical ordering relies on all elements having the same score. The reply is unspecified when the elements have different scores. - -Valid `` and `` must start with `(` or `[`, in order to specify -whether the range interval is exclusive or inclusive, respectively. - -The special values of `+` or `-` for `` and `` mean positive and negative infinite strings, respectively, so for instance the command `ZRANGE myzset - + BYLEX` is guaranteed to return all the elements in the sorted set, providing that all the elements have the same score. - -The `REV` options reverses the order of the `` and `` elements, where `` must be lexicographically greater than `` to produce a non-empty result. - -### Lexicographical comparison of strings - -Strings are compared as a binary array of bytes. Because of how the ASCII character set is specified, this means that usually this also have the effect of comparing normal ASCII characters in an obvious dictionary way. However, this is not true if non-plain ASCII strings are used (for example, utf8 strings). - -However, the user can apply a transformation to the encoded string so that the first part of the element inserted in the sorted set will compare as the user requires for the specific application. For example, if I want to -add strings that will be compared in a case-insensitive way, but I still -want to retrieve the real case when querying, I can add strings in the -following way: - - ZADD autocomplete 0 foo:Foo 0 bar:BAR 0 zap:zap - -Because of the first *normalized* part in every element (before the colon character), we are forcing a given comparison. However, after the range is queried using `ZRANGE ... BYLEX`, the application can display to the user the second part of the string, after the colon. - -The binary nature of the comparison allows to use sorted sets as a general purpose index, for example, the first part of the element can be a 64-bit big-endian number. Since big-endian numbers have the most significant bytes in the initial positions, the binary comparison will match the numerical comparison of the numbers. This can be used in order to implement range queries on 64-bit values. As in the example below, after the first 8 bytes, we can store the value of the element we are indexing. - -## Reply - -Array of members in the specified range with, optionally, their scores when the _WITHSCORES_ option is given. When _WITHSCORES_ is used, each entry is a 2-element array containing the member and its score as a double. In RESP2, the reply is instead a flat array where each member is immediately followed by its score as a string. - -## Examples - -``` -127.0.0.1:6379> ZADD myzset 1 "one" 2 "two" 3 "three" -(integer) 3 -127.0.0.1:6379> ZRANGE myzset 0 -1 -1) "one" -2) "two" -3) "three" -127.0.0.1:6379> ZRANGE myzset 2 3 -1) "three" -127.0.0.1:6379> ZRANGE myzset -2 -1 -1) "two" -2) "three" -``` - -The following examples using `WITHSCORES` show how the response format differs by protocol version. - -In RESP2, the reply is a flat interleaved array of *element_1*, *score_1*, *element_2*, *score_2*, ..., *element_N*, *score_N* where scores are returned as strings: - -``` -127.0.0.1:6379> ZADD myzset 1 "one" 2 "two" 3 "three" -(integer) 3 -127.0.0.1:6379> ZRANGE myzset 0 1 WITHSCORES -1) "one" -2) "1" -3) "two" -4) "2" -``` - -In RESP3, using `valkey-cli -3`, the reply is an array of 2-element arrays where scores are returned as doubles: - -``` -127.0.0.1:6379> ZADD myzset 1 "one" 2 "two" 3 "three" -(integer) 3 -127.0.0.1:6379> ZRANGE myzset 0 1 WITHSCORES -1) 1) "one" - 2) (double) 1 -2) 1) "two" - 2) (double) 2 -``` - -This example shows how to query the sorted set by score, excluding the value `1` and up to infinity, returning only the second element of the result: - -``` -127.0.0.1:6379> ZADD myzset 1 "one" 2 "two" 3 "three" -(integer) 3 -127.0.0.1:6379> ZRANGE myzset (1 +inf BYSCORE LIMIT 1 1 -1) "three" -``` diff --git a/commands/zrangebylex.md b/commands/zrangebylex.md deleted file mode 100644 index c20bacba..00000000 --- a/commands/zrangebylex.md +++ /dev/null @@ -1,76 +0,0 @@ -When all the elements in a sorted set are inserted with the same score, in order to force lexicographical ordering, this command returns all the elements in the sorted set at `key` with a value between `min` and `max`. - -If the elements in the sorted set have different scores, the returned elements are unspecified. - -The elements are considered to be ordered from lower to higher strings as compared byte-by-byte using the `memcmp()` C function. Longer strings are considered greater than shorter strings if the common part is identical. - -The optional `LIMIT` argument can be used to only get a range of the matching -elements (similar to _SELECT LIMIT offset, count_ in SQL). A negative `count` -returns all elements from the `offset`. -Keep in mind that if `offset` is large, the sorted set needs to be traversed for -`offset` elements before getting to the elements to return, which can add up to -O(N) time complexity. - -## How to specify intervals - -Valid *start* and *stop* must start with `(` or `[`, in order to specify -if the range item is respectively exclusive or inclusive. -The special values of `+` or `-` for *start* and *stop* have the special -meaning or positively infinite and negatively infinite strings, so for -instance the command **ZRANGEBYLEX myzset - +** is guaranteed to return -all the elements in the sorted set, if all the elements have the same -score. - -## Details on strings comparison - -Strings are compared as binary array of bytes. Because of how the ASCII character -set is specified, this means that usually this also have the effect of comparing -normal ASCII characters in an obvious dictionary way. However this is not true -if non plain ASCII strings are used (for example utf8 strings). - -However the user can apply a transformation to the encoded string so that -the first part of the element inserted in the sorted set will compare as the -user requires for the specific application. For example if I want to -add strings that will be compared in a case-insensitive way, but I still -want to retrieve the real case when querying, I can add strings in the -following way: - - ZADD autocomplete 0 foo:Foo 0 bar:BAR 0 zap:zap - -Because of the first *normalized* part in every element (before the colon character), we are forcing a given comparison, however after the range is queries using `ZRANGEBYLEX` the application can display to the user the second part of the string, after the colon. - -The binary nature of the comparison allows to use sorted sets as a general -purpose index, for example the first part of the element can be a 64 bit -big endian number: since big endian numbers have the most significant bytes -in the initial positions, the binary comparison will match the numerical -comparison of the numbers. This can be used in order to implement range -queries on 64 bit values. As in the example below, after the first 8 bytes -we can store the value of the element we are actually indexing. - -## Alternative - -`ZRANGE` with the `BYLEX` argument. - -## Reply - -Array of elements in the specified score range. - -## Examples - -``` -127.0.0.1:6379> ZADD myzset 0 a 0 b 0 c 0 d 0 e 0 f 0 g -(integer) 7 -127.0.0.1:6379> ZRANGEBYLEX myzset - [c -1) "a" -2) "b" -3) "c" -127.0.0.1:6379> ZRANGEBYLEX myzset - (c -1) "a" -2) "b" -127.0.0.1:6379> ZRANGEBYLEX myzset [aaa (g -1) "b" -2) "c" -3) "d" -4) "e" -5) "f" -``` diff --git a/commands/zrangebyscore.md b/commands/zrangebyscore.md deleted file mode 100644 index 2921db71..00000000 --- a/commands/zrangebyscore.md +++ /dev/null @@ -1,114 +0,0 @@ -Returns all the elements in the sorted set at `key` with a score between `min` -and `max` (including elements with score equal to `min` or `max`). -The elements are considered to be ordered from low to high scores. - -The elements having the same score are returned in lexicographical order (this -follows from a property of the sorted set implementation in Valkey and does not -involve further computation). - -The optional `LIMIT` argument can be used to only get a range of the matching -elements (similar to _SELECT LIMIT offset, count_ in SQL). A negative `count` -returns all elements from the `offset`. -Keep in mind that if `offset` is large, the sorted set needs to be traversed for -`offset` elements before getting to the elements to return, which can add up to -O(N) time complexity. - -The optional `WITHSCORES` argument makes the command return both the element and -its score, instead of the element alone. - -## Exclusive intervals and infinity - -`min` and `max` can be `-inf` and `+inf`, so that you are not required to know -the highest or lowest score in the sorted set to get all elements from or up to -a certain score. - -By default, the interval specified by `min` and `max` is closed (inclusive). -It is possible to specify an open interval (exclusive) by prefixing the score -with the character `(`. -For example: - -``` -ZRANGEBYSCORE zset (1 5 -``` - -Will return all elements with `1 < score <= 5` while: - -``` -ZRANGEBYSCORE zset (5 (10 -``` - -Will return all the elements with `5 < score < 10` (5 and 10 excluded). - -## Alternative - -`ZRANGE` with the `BYSCORE` argument. - -## Reply - -* Array of the members with, optionally, their scores in the specified score range. - -## Examples - -``` -127.0.0.1:6379> ZADD myzset 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD myzset 2 "two" -(integer) 1 -127.0.0.1:6379> ZADD myzset 3 "three" -(integer) 1 -127.0.0.1:6379> ZRANGEBYSCORE myzset -inf +inf -1) "one" -2) "two" -3) "three" -127.0.0.1:6379> ZRANGEBYSCORE myzset 1 2 -1) "one" -2) "two" -127.0.0.1:6379> ZRANGEBYSCORE myzset (1 2 -1) "two" -127.0.0.1:6379> ZRANGEBYSCORE myzset (1 (2 -(empty array) -``` - -## Pattern: weighted random selection of an element - -Normally `ZRANGEBYSCORE` is simply used in order to get range of items -where the score is the indexed integer key, however it is possible to do less -obvious things with the command. - -For example a common problem when implementing Markov chains and other algorithms -is to select an element at random from a set, but different elements may have -different weights that change how likely it is they are picked. - -This is how we use this command in order to mount such an algorithm: - -Imagine you have elements A, B and C with weights 1, 2 and 3. -You compute the sum of the weights, which is 1+2+3 = 6 - -At this point you add all the elements into a sorted set using this algorithm: - -``` -SUM = ELEMENTS.TOTAL_WEIGHT // 6 in this case. -SCORE = 0 -FOREACH ELE in ELEMENTS - SCORE += ELE.weight / SUM - ZADD KEY SCORE ELE -END -``` - -This means that you set: - -``` -A to score 0.16 -B to score .5 -C to score 1 -``` - -Since this involves approximations, in order to avoid C is set to, -like, 0.998 instead of 1, we just modify the above algorithm to make sure -the last score is 1 (left as an exercise for the reader...). - -At this point, each time you want to get a weighted random element, -just compute a random number between 0 and 1 (which is like calling -`rand()` in most languages), so you can just do: - - RANDOM_ELE = ZRANGEBYSCORE key RAND() +inf LIMIT 0 1 diff --git a/commands/zrangestore.md b/commands/zrangestore.md deleted file mode 100644 index fa38c1b4..00000000 --- a/commands/zrangestore.md +++ /dev/null @@ -1,17 +0,0 @@ -This command is like `ZRANGE`, but stores the result in the `` destination key. - -## Reply - -Integer: the number of elements in the resulting sorted set. - -## Examples - -``` -127.0.0.1:6379> ZADD srczset 1 "one" 2 "two" 3 "three" 4 "four" -(integer) 4 -127.0.0.1:6379> ZRANGESTORE dstzset srczset 2 -1 -(integer) 2 -127.0.0.1:6379> ZRANGE dstzset 0 -1 -1) "three" -2) "four" -``` diff --git a/commands/zrank.md b/commands/zrank.md deleted file mode 100644 index 7312d56e..00000000 --- a/commands/zrank.md +++ /dev/null @@ -1,37 +0,0 @@ -Returns the rank of `member` in the sorted set stored at `key`, with the scores -ordered from low to high. -The rank (or index) is 0-based, which means that the member with the lowest -score has rank `0`. - -The optional `WITHSCORE` argument supplements the command's reply with the score of the element returned. - -Use `ZREVRANK` to get the rank of an element with the scores ordered from high -to low. - -## Reply - -One of the following: - -* Null: if the key does not exist or the member does not exist in the sorted set. -* Integer: the rank of the member when _WITHSCORE_ is not used. -* Array: the rank and score of the member when _WITHSCORE_ is used. - -## Examples - -``` -127.0.0.1:6379> ZADD myzset 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD myzset 2 "two" -(integer) 1 -127.0.0.1:6379> ZADD myzset 3 "three" -(integer) 1 -127.0.0.1:6379> ZRANK myzset "three" -(integer) 2 -127.0.0.1:6379> ZRANK myzset "four" -(nil) -127.0.0.1:6379> ZRANK myzset "three" WITHSCORE -1) (integer) 2 -2) "3" -127.0.0.1:6379> ZRANK myzset "four" WITHSCORE -(nil) -``` diff --git a/commands/zrem.md b/commands/zrem.md deleted file mode 100644 index 02dc994c..00000000 --- a/commands/zrem.md +++ /dev/null @@ -1,26 +0,0 @@ -Removes the specified members from the sorted set stored at `key`. -Non existing members are ignored. - -An error is returned when `key` exists and does not hold a sorted set. - -## Reply - -Integer: the number of members removed from the sorted set, not including non-existing members. - -## Examples - -``` -127.0.0.1:6379> ZADD myzset 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD myzset 2 "two" -(integer) 1 -127.0.0.1:6379> ZADD myzset 3 "three" -(integer) 1 -127.0.0.1:6379> ZREM myzset "two" -(integer) 1 -127.0.0.1:6379> ZRANGE myzset 0 -1 WITHSCORES -1) "one" -2) "1" -3) "three" -4) "3" -``` diff --git a/commands/zremrangebylex.md b/commands/zremrangebylex.md deleted file mode 100644 index 9a533b64..00000000 --- a/commands/zremrangebylex.md +++ /dev/null @@ -1,34 +0,0 @@ -When all the elements in a sorted set are inserted with the same score, in order to force lexicographical ordering, this command removes all elements in the sorted set stored at `key` between the lexicographical range specified by `min` and `max`. - -The meaning of `min` and `max` are the same of the `ZRANGEBYLEX` command. Similarly, this command actually removes the same elements that `ZRANGEBYLEX` would return if called with the same `min` and `max` arguments. - -## Reply - -Integer: the number of members removed. - -## Examples - -``` -127.0.0.1:6379> ZADD myzset 0 aaaa 0 b 0 c 0 d 0 e -(integer) 5 -127.0.0.1:6379> ZADD myzset 0 foo 0 zap 0 zip 0 ALPHA 0 alpha -(integer) 5 -127.0.0.1:6379> ZRANGE myzset 0 -1 - 1) "ALPHA" - 2) "aaaa" - 3) "alpha" - 4) "b" - 5) "c" - 6) "d" - 7) "e" - 8) "foo" - 9) "zap" -10) "zip" -127.0.0.1:6379> ZREMRANGEBYLEX myzset [alpha [omega -(integer) 6 -127.0.0.1:6379> ZRANGE myzset 0 -1 -1) "ALPHA" -2) "aaaa" -3) "zap" -4) "zip" -``` diff --git a/commands/zremrangebyrank.md b/commands/zremrangebyrank.md deleted file mode 100644 index 35f01cc4..00000000 --- a/commands/zremrangebyrank.md +++ /dev/null @@ -1,28 +0,0 @@ -Removes all elements in the sorted set stored at `key` with rank between `start` -and `stop`. -Both `start` and `stop` are `0` -based indexes with `0` being the element with -the lowest score. -These indexes can be negative numbers, where they indicate offsets starting at -the element with the highest score. -For example: `-1` is the element with the highest score, `-2` the element with -the second highest score and so forth. - -## Reply - -Integer: the number of members removed. - -## Examples - -``` -127.0.0.1:6379> ZADD myzset 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD myzset 2 "two" -(integer) 1 -127.0.0.1:6379> ZADD myzset 3 "three" -(integer) 1 -127.0.0.1:6379> ZREMRANGEBYRANK myzset 0 1 -(integer) 2 -127.0.0.1:6379> ZRANGE myzset 0 -1 WITHSCORES -1) "three" -2) "3" -``` diff --git a/commands/zremrangebyscore.md b/commands/zremrangebyscore.md deleted file mode 100644 index f33bd025..00000000 --- a/commands/zremrangebyscore.md +++ /dev/null @@ -1,24 +0,0 @@ -Removes all elements in the sorted set stored at `key` with a score between -`min` and `max` (inclusive). - -## Reply - -Integer: the number of members removed. - -## Examples - -``` -127.0.0.1:6379> ZADD myzset 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD myzset 2 "two" -(integer) 1 -127.0.0.1:6379> ZADD myzset 3 "three" -(integer) 1 -127.0.0.1:6379> ZREMRANGEBYSCORE myzset -inf (2 -(integer) 1 -127.0.0.1:6379> ZRANGE myzset 0 -1 WITHSCORES -1) "two" -2) "2" -3) "three" -4) "3" -``` diff --git a/commands/zrevrange.md b/commands/zrevrange.md deleted file mode 100644 index dd095523..00000000 --- a/commands/zrevrange.md +++ /dev/null @@ -1,33 +0,0 @@ -Returns the specified range of elements in the sorted set stored at `key`. -The elements are considered to be ordered from the highest to the lowest score. -Descending lexicographical order is used for elements with equal score. - -Apart from the reversed ordering, `ZREVRANGE` is similar to `ZRANGE`. - -## Alternative - -`ZRANGE` with the `REV` argument. - -## Reply - -* Array of the members in the specified range, optionally with their scores if _WITHSCORE_ was used. - -## Examples - -``` -127.0.0.1:6379> ZADD myzset 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD myzset 2 "two" -(integer) 1 -127.0.0.1:6379> ZADD myzset 3 "three" -(integer) 1 -127.0.0.1:6379> ZREVRANGE myzset 0 -1 -1) "three" -2) "two" -3) "one" -127.0.0.1:6379> ZREVRANGE myzset 2 3 -1) "one" -127.0.0.1:6379> ZREVRANGE myzset -2 -1 -1) "two" -2) "one" -``` diff --git a/commands/zrevrangebylex.md b/commands/zrevrangebylex.md deleted file mode 100644 index b093053b..00000000 --- a/commands/zrevrangebylex.md +++ /dev/null @@ -1,31 +0,0 @@ -When all the elements in a sorted set are inserted with the same score, in order to force lexicographical ordering, this command returns all the elements in the sorted set at `key` with a value between `max` and `min`. - -Apart from the reversed ordering, `ZREVRANGEBYLEX` is similar to `ZRANGEBYLEX`. - -## Alternative - -`ZRANGE` with the `REV` and `BYLEX` arguments. - -## Reply - -Array of the members in the specified score range. - -## Examples - -``` -127.0.0.1:6379> ZADD myzset 0 a 0 b 0 c 0 d 0 e 0 f 0 g -(integer) 7 -127.0.0.1:6379> ZREVRANGEBYLEX myzset [c - -1) "c" -2) "b" -3) "a" -127.0.0.1:6379> ZREVRANGEBYLEX myzset (c - -1) "b" -2) "a" -127.0.0.1:6379> ZREVRANGEBYLEX myzset (g [aaa -1) "f" -2) "e" -3) "d" -4) "c" -5) "b" -``` diff --git a/commands/zrevrangebyscore.md b/commands/zrevrangebyscore.md deleted file mode 100644 index 4bdbac6b..00000000 --- a/commands/zrevrangebyscore.md +++ /dev/null @@ -1,40 +0,0 @@ -Returns all the elements in the sorted set at `key` with a score between `max` -and `min` (including elements with score equal to `max` or `min`). -In contrary to the default ordering of sorted sets, for this command the -elements are considered to be ordered from high to low scores. - -The elements having the same score are returned in reverse lexicographical -order. - -Apart from the reversed ordering, `ZREVRANGEBYSCORE` is similar to -`ZRANGEBYSCORE`. - -## Alternative - -`ZRANGE` with the `REV` and `BYSCORE` arguments. - -## Reply - -* Array of the members and, optionally, their scores in the specified score range. - -## Examples - -``` -127.0.0.1:6379> ZADD myzset 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD myzset 2 "two" -(integer) 1 -127.0.0.1:6379> ZADD myzset 3 "three" -(integer) 1 -127.0.0.1:6379> ZREVRANGEBYSCORE myzset +inf -inf -1) "three" -2) "two" -3) "one" -127.0.0.1:6379> ZREVRANGEBYSCORE myzset 2 1 -1) "two" -2) "one" -127.0.0.1:6379> ZREVRANGEBYSCORE myzset 2 (1 -1) "two" -127.0.0.1:6379> ZREVRANGEBYSCORE myzset (2 (1 -(empty array) -``` diff --git a/commands/zrevrank.md b/commands/zrevrank.md deleted file mode 100644 index eb041bf7..00000000 --- a/commands/zrevrank.md +++ /dev/null @@ -1,37 +0,0 @@ -Returns the rank of `member` in the sorted set stored at `key`, with the scores -ordered from high to low. -The rank (or index) is 0-based, which means that the member with the highest -score has rank `0`. - -The optional `WITHSCORE` argument supplements the command's reply with the score of the element returned. - -Use `ZRANK` to get the rank of an element with the scores ordered from low to -high. - -## Reply - -One of the following: - -* Null: if the key does not exist or the member does not exist in the sorted set. -* Integer: The rank of the member when _WITHSCORE_ is not used. -* Array: The rank and score of the member when _WITHSCORE_ is used. - -## Examples - -``` -127.0.0.1:6379> ZADD myzset 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD myzset 2 "two" -(integer) 1 -127.0.0.1:6379> ZADD myzset 3 "three" -(integer) 1 -127.0.0.1:6379> ZREVRANK myzset "one" -(integer) 2 -127.0.0.1:6379> ZREVRANK myzset "four" -(nil) -127.0.0.1:6379> ZREVRANK myzset "three" WITHSCORE -1) (integer) 0 -2) "3" -127.0.0.1:6379> ZREVRANK myzset "four" WITHSCORE -(nil) -``` diff --git a/commands/zscan.md b/commands/zscan.md deleted file mode 100644 index bd9d8906..00000000 --- a/commands/zscan.md +++ /dev/null @@ -1,8 +0,0 @@ -See [`SCAN`](scan.md) for `ZSCAN` documentation. - -## Reply - -Two-element array. - -* The first element is a string that represents an unsigned 64-bit number, the cursor. -* The second element is an array of member/score pairs that were scanned. When `NOSCORES` option is on, a list of members from the sorted set. diff --git a/commands/zscore.md b/commands/zscore.md deleted file mode 100644 index b489c0bc..00000000 --- a/commands/zscore.md +++ /dev/null @@ -1,20 +0,0 @@ -Returns the score of `member` in the sorted set at `key`. - -If `member` does not exist in the sorted set, or `key` does not exist, `nil` is -returned. - -## Reply - -One of the following: - -* Double: the score of the member (a double-precision floating point number). -* Null: if _member_ does not exist in the sorted set, or the key does not exist. - -## Examples - -``` -127.0.0.1:6379> ZADD myzset 1 "one" -(integer) 1 -127.0.0.1:6379> ZSCORE myzset "one" -"1" -``` diff --git a/commands/zunion.md b/commands/zunion.md deleted file mode 100644 index e36ba6b9..00000000 --- a/commands/zunion.md +++ /dev/null @@ -1,34 +0,0 @@ -This command is similar to `ZUNIONSTORE`, but instead of storing the resulting -sorted set, it is returned to the client. - -For a description of the `WEIGHTS` and `AGGREGATE` options, see `ZUNIONSTORE`. - -## Reply - -Array: the result of the union with, optionally, their scores when _WITHSCORES_ is used. - -## Examples - -``` -127.0.0.1:6379> ZADD zset1 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD zset1 2 "two" -(integer) 1 -127.0.0.1:6379> ZADD zset2 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD zset2 2 "two" -(integer) 1 -127.0.0.1:6379> ZADD zset2 3 "three" -(integer) 1 -127.0.0.1:6379> ZUNION 2 zset1 zset2 -1) "one" -2) "three" -3) "two" -127.0.0.1:6379> ZUNION 2 zset1 zset2 WITHSCORES -1) "one" -2) "2" -3) "three" -4) "3" -5) "two" -6) "4" -``` diff --git a/commands/zunionstore.md b/commands/zunionstore.md deleted file mode 100644 index 30d111e8..00000000 --- a/commands/zunionstore.md +++ /dev/null @@ -1,55 +0,0 @@ -Computes the union of `numkeys` sorted sets given by the specified keys, and -stores the result in `destination`. -It is mandatory to provide the number of input keys (`numkeys`) before passing -the input keys and the other (optional) arguments. - -By default, the resulting score of an element is the sum of its scores in the -sorted sets where it exists. - -Using the `WEIGHTS` option, it is possible to specify a multiplication factor -for each input sorted set. -This means that the score of every element in every input sorted set is -multiplied by this factor before being passed to the aggregation function. -When `WEIGHTS` is not given, the multiplication factors default to `1`. - -With the `AGGREGATE` option, it is possible to specify how the results of the -union are aggregated. -This option defaults to `SUM`, where the score of an element is summed across -the inputs where it exists. -When this option is set to either `MIN` or `MAX`, the resulting set will contain -the minimum or maximum score of an element across the inputs where it exists. - -If `destination` already exists, it is overwritten. - -## Reply - -Integer: the number of elements in the resulting sorted set. - -## Notes - -If an option `WEIGHTS` or `AGGREGATE` is given multiple times, it is undefined -which option takes precedence. - -## Examples - -``` -127.0.0.1:6379> ZADD zset1 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD zset1 2 "two" -(integer) 1 -127.0.0.1:6379> ZADD zset2 1 "one" -(integer) 1 -127.0.0.1:6379> ZADD zset2 2 "two" -(integer) 1 -127.0.0.1:6379> ZADD zset2 3 "three" -(integer) 1 -127.0.0.1:6379> ZUNIONSTORE out 2 zset1 zset2 WEIGHTS 2 3 -(integer) 3 -127.0.0.1:6379> ZRANGE out 0 -1 WITHSCORES -1) "one" -2) "5" -3) "three" -4) "9" -5) "two" -6) "10" -``` diff --git a/groups.json b/groups.json deleted file mode 100644 index 8bb391de..00000000 --- a/groups.json +++ /dev/null @@ -1,86 +0,0 @@ -{ - "bitmap": { - "display": "Bitmap", - "description": "Operations on the Bitmap data type" - }, - "bloom": { - "display": "Bloom filter", - "description": "Operations on the Bloom filter data type" - }, - "search": { - "display": "Search", - "description": "Vector Similarity Search engine optimized for AI-driven workloads" - }, - "cluster": { - "display": "Cluster", - "description": "Valkey Cluster management" - }, - "connection": { - "display": "Connection", - "description": "Client connections management" - }, - "generic": { - "display": "Generic", - "description": "Generic commands" - }, - "geo": { - "display": "Geospatial indices", - "description": "Operations on the Geospatial Index data type" - }, - "hash": { - "display": "Hash", - "description": "Operations on the Hash data type" - }, - "hyperloglog": { - "display": "HyperLogLog", - "description": "Operations on the HyperLogLog data type" - }, - "json": { - "display": "JSON", - "description": "Operations on the JSON data type" - }, - "large-object": { - "display": "Large object", - "description": "Operations on the large object data type" - }, - "list": { - "display": "List", - "description": "Operations on the List data type" - }, - "pubsub": { - "display": "Pub/Sub", - "description": "Pub/Sub commands" - }, - "scripting": { - "display": "Scripting and Functions", - "description": "Valkey server-side scripting and functions" - }, - "sentinel": { - "display": "Sentinel", - "description": "Valkey Sentinel commands" - }, - "server": { - "display": "Server", - "description": "Server management commands" - }, - "set": { - "display": "Set", - "description": "Operations on the Set data type" - }, - "sorted-set": { - "display": "Sorted Set", - "description": "Operations on the Sorted Set data type" - }, - "stream": { - "display": "Stream", - "description": "Operations on the Stream data type" - }, - "string": { - "display": "String", - "description": "Operations on the String data type" - }, - "transactions": { - "display": "Transactions", - "description": "Valkey Transaction management" - } -} diff --git a/modules-nav/valkey-bloom.yml b/modules-nav/valkey-bloom.yml deleted file mode 100644 index 6b8af698..00000000 --- a/modules-nav/valkey-bloom.yml +++ /dev/null @@ -1,6 +0,0 @@ -# Menu entries for the valkey-bloom module, merged into the core menu (nav.yml). -# "section" adds topics to a section defined in the core menu. -- section: data-types - topics: - - topic: bloomfilters - commands: [bloom] diff --git a/modules-nav/valkey-json.yml b/modules-nav/valkey-json.yml deleted file mode 100644 index 111a1bf5..00000000 --- a/modules-nav/valkey-json.yml +++ /dev/null @@ -1,7 +0,0 @@ -# Menu entries for the valkey-json module, merged into the core menu (nav.yml). -# "section" adds topics to a section defined in the core menu. -- section: data-types - topics: - - topic: valkey-json - title: JSON - commands: [json] diff --git a/modules-nav/valkey-large-object.yml b/modules-nav/valkey-large-object.yml deleted file mode 100644 index 02ec6cf2..00000000 --- a/modules-nav/valkey-large-object.yml +++ /dev/null @@ -1,17 +0,0 @@ -# Menu entries for the valkey-large-object module, merged into the core menu (nav.yml). -# An entry with "id" creates a new section. "after" places it after a section -# in the core menu; without it, the section goes at the end. -- id: large-object - title: Large object - after: programmability - landing: large-object - commands: [large_object] - topics: - - topic: large-object-getting-started - title: Getting started - - topic: large-object-use-cases - title: Use cases and examples - - topic: large-object-rdma - title: RDMA transfers - - topic: large-object-configuration - title: Configuration and monitoring diff --git a/modules-nav/valkey-ldap.yml b/modules-nav/valkey-ldap.yml deleted file mode 100644 index 5c65945a..00000000 --- a/modules-nav/valkey-ldap.yml +++ /dev/null @@ -1,5 +0,0 @@ -# Menu entries for the valkey-ldap module, merged into the core menu (nav.yml). -- section: security - topics: - - topic: ldap - title: LDAP authentication diff --git a/modules-nav/valkey-search.yml b/modules-nav/valkey-search.yml deleted file mode 100644 index 607ab297..00000000 --- a/modules-nav/valkey-search.yml +++ /dev/null @@ -1,25 +0,0 @@ -# Menu entries for the valkey-search module, merged into the core menu (nav.yml). -# An entry with "id" creates a new section. "after" places it after a section -# in the core menu; without it, the section goes at the end. -- id: search - title: Search - after: programmability - landing: search - commands: [search] - topics: - - topic: search-query - title: Queries - - topic: search-scoring - title: Scoring - - topic: search-scoring-examples - title: Scoring examples - - topic: search-expressions - title: Aggregation expressions - - topic: search-data-formats - title: Data formats - - topic: search-configurables - title: Configuration - - topic: search-monitoring - title: Metrics and configurations - - topic: search-observables - title: INFO SEARCH metrics diff --git a/nav.yml b/nav.yml deleted file mode 100644 index e57714fd..00000000 --- a/nav.yml +++ /dev/null @@ -1,181 +0,0 @@ -# Menu structure for the documentation: topics and the commands related to them. -# -# Each entry is a first-level menu section: -# -# id: Stable identifier. Module docs use it to add topics to a section, -# so don't rename it without updating them. -# title: Label shown in the menu. -# landing: Optional topic shown as the section's overview page. -# commands: Optional commands belonging to the section as a whole (see below). -# They're related to the landing page, if there is one. -# topics: Topics in menu order. Either a topic name (a file name in -# topics/ without .md), or a mapping with "topic", an optional -# shorter menu "title" and optional "commands". -# -# The section with the id "command-reference" is filled by the website with -# links to the command reference and its command categories. It has no -# topics. Without it, the website adds it at the end of the menu. -# -# "commands" relates commands to a topic, for breadcrumbs and the topic's command -# list in the menu. -# Each item is one of: -# -# - a command group in lowercase, e.g. "list" (the "group" in the command JSON) -# - a container command in uppercase, e.g. "ACL" for all ACL subcommands -# - a command name in uppercase, e.g. "BGSAVE" -# -# The most specific item wins: a name over a container, a container over a group. -# -# Every topic should be listed exactly once, and every documented command (one -# with a page in commands/) should be covered exactly once at its most specific -# level. Topics and commands from modules are listed in the modules' own menu -# files. The website leaves out what doesn't fit; pages missing from the menu -# are still listed in the topic index and the command reference. - -- id: getting-started - title: Getting started - topics: - - introduction - - quickstart - - installation - - faq - - migration - -- id: command-reference - title: Command reference - -- id: data-types - title: Data types - landing: data-types - topics: - - topic: strings - commands: [string] - - topic: lists - commands: [list] - - topic: sets - commands: [set] - - topic: hashes - commands: [hash] - - topic: sorted-sets - commands: [sorted_set] - - topic: streams-intro - commands: [stream] - - topic: geospatial - commands: [geo] - - topic: bitmaps - commands: [bitmap] - - topic: bitfields - commands: [BITFIELD, BITFIELD_RO] - - topic: hyperloglogs - commands: [hyperloglog] - -- id: application-development - title: Application development - topics: - - topic: keyspace - commands: [generic, FLUSHDB, FLUSHALL, SWAPDB, DBSIZE] - - pipelining - - topic: transactions - commands: [transactions] - - topic: pubsub - commands: [pubsub] - - notifications - -- id: patterns - title: Patterns and tutorials - topics: - - lru-cache - - client-side-caching - - distlock - - indexing - - twitter-clone - -- id: programmability - title: Scripting and functions - landing: programmability - commands: [scripting] - topics: - - eval-intro - - functions-intro - - lua-api - - ldb - -- id: administration - title: Administration - commands: [server] - topics: - - server - - cli - - topic: valkey.conf - commands: [CONFIG] - - topic: persistence - commands: [SAVE, BGSAVE, BGREWRITEAOF, LASTSAVE] - - topic: replication - commands: [REPLICAOF, SLAVEOF, PSYNC, SYNC, REPLCONF, ROLE, FAILOVER] - - forkless - - topic: sentinel - commands: [sentinel] - - admin - - topic: clients - commands: [connection] - - signals - - ARM - - RDMA - -- id: cluster - title: Cluster - topics: - - topic: cluster-tutorial - commands: [cluster] - - cluster-spec - - atomic-slot-migration - -- id: security - title: Security - landing: security - topics: - - topic: acl - commands: [ACL] - - tls - -- id: performance - title: Performance and troubleshooting - topics: - - problems - - topic: memory-optimization - commands: [MEMORY] - - topic: latency-monitor - commands: [LATENCY] - - topic: latency - commands: [COMMANDLOG, SLOWLOG] - - topic: hotkeys - commands: [HOTKEYS] - - benchmark - - performance-on-cpu - - debugging - - mass-insertion - -- id: modules-api - title: Module development - landing: modules-intro - commands: [MODULE] - topics: - - modules-native-types - - modules-blocking-ops - - modules-api-ref - -- id: client-development - title: Client development - topics: - - protocol - - topic: command-arguments - commands: [COMMAND] - - key-specs - - command-tips - - sentinel-clients - -- id: about - title: About Valkey - topics: - - releases - - history diff --git a/topics/2idx_0.png b/topics/2idx_0.png deleted file mode 100644 index 8cf87088..00000000 Binary files a/topics/2idx_0.png and /dev/null differ diff --git a/topics/2idx_1.png b/topics/2idx_1.png deleted file mode 100644 index 637b6a6a..00000000 Binary files a/topics/2idx_1.png and /dev/null differ diff --git a/topics/2idx_2.png b/topics/2idx_2.png deleted file mode 100644 index 70dc6c38..00000000 Binary files a/topics/2idx_2.png and /dev/null differ diff --git a/topics/ARM.md b/topics/ARM.md deleted file mode 100644 index baceba82..00000000 --- a/topics/ARM.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: "ARM support" -description: > - Exploring Valkey on the ARM CPU Architecture ---- - -Valkey supports the ARM processor, for example -the Raspberry Pi, as a main platform. -While Valkey does run on Android, in the future we look forward to extend our testing efforts to Android -to also make it an officially supported platform. - -We believe that Valkey is ideal for IoT and embedded devices for several -reasons: - -* Valkey has a very small memory footprint and CPU requirements. It can run in small devices like the Raspberry Pi Zero without impacting the overall performance, using a small amount of memory while delivering good performance for many use cases. -* The data structures of Valkey are often an ideal way to model IoT/embedded use cases. Some examples include accumulating time series data, receiving or queuing commands to execute or respond to send back to the remote servers, and so forth. -* Modeling data inside Valkey can be very useful in order to make in-device decisions for appliances that must respond very quickly or when the remote servers are offline. -* Valkey can be used as a communication system between the processes running in the device. -* The append-only file storage of Valkey is well suited for SSD cards. -* The stream data structure was specifically designed for time series applications and has a very low memory overhead. - -## Valkey /proc/cpu/alignment requirements - -Linux on ARM allows to trap unaligned accesses and fix them inside the kernel -in order to continue the execution of the offending program instead of -generating a `SIGBUS`. Valkey avoids any kind -of unaligned access, so there is no need to have a specific value for this -kernel configuration. Even when kernel alignment fixing set as disabled Valkey should -run as expected. - -## Building Valkey in the Pi - -* Download Valkey. -* Use `make` as usual to create the executable. - -There is nothing special in the process. The only difference is that by -default, Valkey uses the `libc` allocator instead of defaulting to `jemalloc` -as it does in other Linux based environments. This is because we believe -that for the small use cases inside embedded devices, memory fragmentation -is unlikely to be a problem. Moreover `jemalloc` on ARM may not be as tested -as the `libc` allocator. - -## Performance - -Performance testing of Valkey was performed on the Raspberry Pi 3 and Pi 1 model B. The difference between the two Pis in terms of delivered performance is quite big. The benchmarks were performed via the -loopback interface, since most use cases will probably use Valkey from within -the device and not via the network. The following numbers were obtained using -Redis OSS 4.0. - -Raspberry Pi 3: - -* Test 1 : 5 millions writes with 1 million keys (even distribution among keys). No persistence, no pipelining. 28,000 ops/sec. -* Test 2: Like test 1 but with pipelining using groups of 8 operations: 80,000 ops/sec. -* Test 3: Like test 1 but with AOF enabled, fsync 1 sec: 23,000 ops/sec -* Test 4: Like test 3, but with an AOF rewrite in progress: 21,000 ops/sec - -Raspberry Pi 1 model B: - -* Test 1 : 5 millions writes with 1 million keys (even distribution among keys). No persistence, no pipelining. 2,200 ops/sec. -* Test 2: Like test 1 but with pipelining using groups of 8 operations: 8,500 ops/sec. -* Test 3: Like test 1 but with AOF enabled, fsync 1 sec: 1,820 ops/sec -* Test 4: Like test 3, but with an AOF rewrite in progress: 1,000 ops/sec - -The benchmarks above are referring to simple `SET`/`GET` operations. The performance is similar for all the Valkey fast operations (not running in linear time). However sorted sets may show slightly slower numbers. diff --git a/topics/Connections_chart.png b/topics/Connections_chart.png deleted file mode 100644 index e3133b90..00000000 Binary files a/topics/Connections_chart.png and /dev/null differ diff --git a/topics/Data_size.png b/topics/Data_size.png deleted file mode 100644 index 1acff3f2..00000000 Binary files a/topics/Data_size.png and /dev/null differ diff --git a/topics/NUMA_chart.gif b/topics/NUMA_chart.gif deleted file mode 100644 index 0bc346e1..00000000 Binary files a/topics/NUMA_chart.gif and /dev/null differ diff --git a/topics/RDMA.md b/topics/RDMA.md deleted file mode 100644 index 44ff708d..00000000 --- a/topics/RDMA.md +++ /dev/null @@ -1,262 +0,0 @@ ---- -title: "RDMA experimental support" -description: Valkey Over RDMA experimental support ---- - -Valkey supports the Remote Direct Memory Access (RDMA) connection type via a -Valkey module that can be dynamically loaded on demand. - -For bulk transfer of large objects between server memory and client memory with the large object module, see [Valkey Large Object - RDMA Transfers](large-object-rdma.md). -That module uses its own RDMA path, which is independent of the connection type on this page. - -## Getting Started - -[RDMA](https://en.wikipedia.org/wiki/Remote_direct_memory_access) -enables direct data exchange between networked computers' main memory, -bypassing processors and operating systems. - -As a result, RDMA offers better performance compared to TCP/IP. Test results indicate that -Valkey Over RDMA achieves approximately 2 times higher QPS and lower latency. - -Please note that Valkey Over RDMA is currently supported only on Linux. -Also, before using Valkey Over RDMA, you must understand how to configure -RDMA on your server and client machines. - -## Running manually - -To run a Valkey server with RDMA mode: - - ./src/valkey-server --protected-mode no \ - --loadmodule src/valkey-rdma.so bind=192.168.122.100 port=6379 - -Bind address/port of RDMA can be modified at runtime using the following command: - - 192.168.122.100:6379> CONFIG SET rdma-port 6380 - -Valkey can run both RDMA and TCP/IP concurrently on the same port: - - ./src/valkey-server --protected-mode no \ - --loadmodule src/valkey-rdma.so bind=192.168.122.100 port=6379 \ - --port 6379 - -Or append `loadmodule src/valkey-rdma.so bind=192.168.122.100 port=6379` in valkey.conf, then: - - ./src/valkey-server valkey.conf - -Starting from version 9.0, `valkey-cli` and `valkey-benchmark` support the `--rdma` parameter. - - ./src/valkey-cli -h 192.168.122.100 --rdma - - ./src/valkey-benchmark -h 192.168.122.100 --rdma - -### Prerequisites -Note that the network interface (192.168.122.100 of this example) should support -RDMA. To test a server supports RDMA or not: - - rdma dev show (a new version iproute2 package) -Or: - - ibv_devices (ibverbs-utils package of Debian/Ubuntu) - -## Performance tuning -The RDMA completion queue will use the completion vector to signal completion events -via hardware interrupts. A large number of hardware interrupts can affect CPU performance. -It is possible to tune the performance using `rdma-comp-vector`. - -See [RDMA CQ completion vector](https://man7.org/linux/man-pages/man3/ibv_create_cq.3.html) - -### Example 1 - -- Pin hardware interrupt vectors [0, 3] to CPU [0, 3]. -- Set CPU affinity for valkey to CPU [4, X]. -- Any valkey server uses a random RDMA completion vector [-1]. - -All valkey servers will not affect each other and will be isolated from kernel interrupts. - -``` - SYS SYS SYS SYS VALKEY VALKEY VALKEY - | | | | | | | - CPU0 CPU1 CPU2 CPU3 CPU4 CPU5 ... CPUX - | | | | - INTR0 INTR1 INTR2 INTR3 -``` - -### Example 2 - -- Pin hardware interrupt vectors [0, X] to CPU [0, X]. -- Set CPU affinity for valkey [M] to CPU [M]. -- Valkey server [M] uses RDMA completion vector [M]. - -A single CPU [M] handles hardware interrupts, the RDMA completion vector [M], -and the valkey server [M] within its context only. -This avoids overhead and function calls across multiple CPUs, fully isolating -each valkey server from one another. - -``` -VALKEY VALKEY VALKEY VALKEY VALKEY VALKEY VALKEY - | | | | | | | - CPU0 CPU1 CPU2 CPU3 CPU4 CPU5 ... CPUX - | | | | | | | - INTR0 INTR1 INTR2 INTR3 INTR4 INTR5 INTRX -``` - -Use 0 and positive numbers to specify the RDMA completion vector, or specify -1 to allow -the server to use a random vector for a new connection. The default vector is -1. - - -## Protocol - -The protocol defines the Queue Pairs (QP) type reliable connection (RC), -like TCP, communication commands, and payload exchange mechanism. -This dependency is based solely on the RDMA (aka Infiniband) specification -and is independent of both software (including the OS and user libraries) -and hardware (including vendors and low-level transports). - -Valkey Over RDMA has control-plane (control messages) and data-plane (payload transfer). - -### Control message - -Control messages use fixed 32-byte big-endian message structures: -```C -typedef struct ValkeyRdmaFeature { - /* defined as following Opcodes */ - uint16_t opcode; - /* select features */ - uint16_t select; - uint8_t reserved[20]; - /* feature bits */ - uint64_t features; -} ValkeyRdmaFeature; - -typedef struct ValkeyRdmaKeepalive { - /* defined as following Opcodes */ - uint16_t opcode; - uint8_t reserved[30]; -} ValkeyRdmaKeepalive; - -typedef struct ValkeyRdmaMemory { - /* defined as following Opcodes */ - uint16_t opcode; - uint8_t reserved[14]; - /* address of a transfer buffer which is used to receive remote streaming data, - * aka 'RX buffer address'. The remote side should use this as 'TX buffer address' */ - uint64_t addr; - /* length of the 'RX buffer' */ - uint32_t length; - /* the RDMA remote key of 'RX buffer' */ - uint32_t key; -} ValkeyRdmaMemory; - -typedef union ValkeyRdmaCmd { - ValkeyRdmaFeature feature; - ValkeyRdmaKeepalive keepalive; - ValkeyRdmaMemory memory; -} ValkeyRdmaCmd; -``` - -### Opcodes -|Command| Value | Description | -| :----: | :----: | :----: | -| `GetServerFeature` | 0 | required, get the features offered by Valkey server | -| `SetClientFeature` | 1 | required, negotiate features and set it to Valkey server | -| `Keepalive` | 2 | required, detect unexpected orphan connection | -| `RegisterXferMemory` | 3 | required, tell the 'RX transfer buffer' information to the remote side, and the remote side uses this as 'TX transfer buffer' | - -Once any new feature and command are introduced into `Valkey Over RDMA`, the client should -detect the new feature `VALKEY_RDMA_FEATURE_FOO` through the `GetServerFeature` command, -and then use the `SetClientFeature` command to enable the feature `VALKEY_RDMA_FEATURE_FOO`. -Once `VALKEY_RDMA_FEATURE_FOO` is negotiated successfully, the optional -`ValkeyRdmaFoo` command will be supported within the connection. - -### RDMA Operations -- Send a control message by RDMA '**`ibv_post_send`**' with opcode '**`IBV_WR_SEND`**' with structure - 'ValkeyRdmaCmd'. -- Receive a control message by RDMA '**`ibv_post_recv`**', and the received buffer - size should be size of 'ValkeyRdmaCmd'. -- Transfer stream data by RDMA '**`ibv_post_send`**' with opcode '**`IBV_WR_RDMA_WRITE`**' (optional) and - '**`IBV_WR_RDMA_WRITE_WITH_IMM`**' (required), to write data segments into a connection by - RDMA [WRITE][WRITE][WRITE]...[WRITE WITH IMM], the length of total buffer is described by - immediate data (unsigned int 32). For example: - a, [WRITE 128 bytes][WRITE 256 bytes][WRITE 128 bytes WITH IMM 512] writes 512 bytes to the - remote side, the remote side is notified only once. - b, [WRITE 128 bytes WITH IMM 128][WRITE 256 bytes WITH IMM 256][WRITE 128 bytes WITH IMM 128] - writes 512 bytes to the remote side, the remote side is notified three times. - Both example a and b write the same 512 bytes, - example a has better performance, however b is easier to implement. - - -### Maximum WQEs of RDMA -No specific limit, 1024 recommended for WQEs. -Flow control for WQE MAY be defined/implemented in the future. - - -### The workflow of this protocol -``` - valkey-server - listen RDMA port - valkey-client - -------------------RDMA connect--------------------> - accept connection - <--------------- Establish RDMA -------------------- - - --------Get server feature [@IBV_WR_SEND] ---------> - - --------Set client feature [@IBV_WR_SEND] ---------> - setup RX buffer - <---- Register transfer memory [@IBV_WR_SEND] ------ -[@ibv_post_recv] -setup TX buffer - ----- Register transfer memory [@IBV_WR_SEND] -----> - [@ibv_post_recv] - setup TX buffer - -- Valkey commands [@IBV_WR_RDMA_WRITE_WITH_IMM] --> - <- Valkey response [@IBV_WR_RDMA_WRITE_WITH_IMM] --- - ....... - -- Valkey commands [@IBV_WR_RDMA_WRITE_WITH_IMM] --> - <- Valkey response [@IBV_WR_RDMA_WRITE_WITH_IMM] --- - ....... - - -RX is full - ----- Register transfer memory [@IBV_WR_SEND] -----> - [@ibv_post_recv] - setup TX buffer - <- Valkey response [@IBV_WR_RDMA_WRITE_WITH_IMM] --- - ....... - - RX is full - <---- Register transfer memory [@IBV_WR_SEND] ------ -[@ibv_post_recv] -setup TX buffer - -- Valkey commands [@IBV_WR_RDMA_WRITE_WITH_IMM] --> - <- Valkey response [@IBV_WR_RDMA_WRITE_WITH_IMM] --- - ....... - - -------------------RDMA disconnect-----------------> - <------------------RDMA disconnect------------------ -``` - -The Valkey Over RDMA protocol is designed to efficiently transfer stream data and -bears similarities to several mechanisms introduced in academic papers with some differences: - -* [Socksdirect: datacenter sockets can be fast and compatible](https://dl.acm.org/doi/10.1145/3341302.3342071) -* [LITE Kernel RDMA Support for Datacenter Applications](https://dl.acm.org/doi/abs/10.1145/3132747.3132762) -* [FaRM: Fast Remote Memory](https://www.usenix.org/system/files/conference/nsdi14/nsdi14-paper-dragojevic.pdf) - - -## How does Valkey use RDMA -Valkey supports a connection abstraction framework that hides listen/connect/accept/shutdown/read/write, -and so on. This allows the connection types to register into Valkey core during startup time. -What's more, a connection type is either Valkey built-in (Ex, TCP/IP and Unix domain socket) or -Valkey module (Ex, TLS). -Enabling RDMA support needs to link additional libraries, rather than valkey-server's additional dependence -on the shared libraries, build Valkey Over RDMA into Valkey module, -Then a user starts valkey-server with RDMA module, valkey-server loads the additional shared libraries on demand. - - -## Limitations -* Valkey Over RDMA is experimental, it may be changed or be removed in any minor or major version. -* TLS is not supported by Valkey Over RDMA. But it is workable in theory by a certain amount of work. -* Valkey Over RDMA is supported on Linux only. -* Not compatible with replication currently, TCP/TLS is needed for replication. -* Depending on different hardware, too many active queue pairs may lead performance drop. diff --git a/topics/acl.md b/topics/acl.md deleted file mode 100644 index f2e42cae..00000000 --- a/topics/acl.md +++ /dev/null @@ -1,730 +0,0 @@ ---- -title: "ACL" -description: Valkey Access Control List ---- - -The Valkey ACL, short for Access Control List, is a feature that allows certain connections to be limited in terms of the commands that can be executed and the keys that can be accessed. -The way it works is that, after connecting, a client is required to either provide a username and a valid password, or a valid TLS certificate to authenticate. -If authentication succeeded, the connection is associated with a given user and the limits the user has. -Valkey can be configured so that new connections are already authenticated with a "default" user (this is the default configuration). -Configuring the default user has, as a side effect, the ability to provide only a specific subset of functionalities to connections that are not explicitly authenticated. - -The standard way to authenticate is the two-argument form of the `AUTH` command: - - AUTH - -If the password is valid matches, the connection will be authenticated to the user with the name ``. - -When the single argument form of the command is used, where only the password is specified, it is assumed that the implicit username is "default". - - AUTH - -This form authenticates against the "default" user's password, either set by ACLs or by setting `requirepass`. - -## When ACLs are useful - -Before using ACLs, you may want to ask yourself what's the goal you want to -accomplish by implementing this layer of protection. Normally there are -two main goals that are well served by ACLs: - -1. You want to improve security by restricting the access to commands and keys, so that untrusted clients have no access and trusted clients have just the minimum access level to the database in order to perform the work needed. For instance, certain clients may just be able to execute read only commands. -2. You want to improve operational safety, so that processes or humans accessing Valkey are not allowed to damage the data or the configuration due to software errors or manual mistakes. For instance, there is no reason for a worker that fetches delayed jobs from Valkey to be able to call the `FLUSHALL` command. - -Another typical usage of ACLs is related to managed Valkey instances. Valkey is -often provided as a managed service both by internal company teams that handle -the Valkey infrastructure for the other internal customers they have, or is -provided in a software-as-a-service setup by cloud providers. In both -setups, we want to be sure that configuration commands are excluded for the -customers. - -## Configure ACLs with the ACL command - -ACLs are defined using a DSL (domain specific language) that describes what -a given user is allowed to do. Such rules are always implemented from the -first to the last, left-to-right, because sometimes the order of the rules is -important to understand what the user is really able to do. - -By default there is a single user defined, called *default*. We -can use the `ACL LIST` command in order to check the currently active ACLs -and verify what the configuration of a freshly started, defaults-configured -Valkey instance is: - - > ACL LIST - 1) "user default on nopass ~* &* +@all" - -The command above reports the list of users in the same format that is -used in the Valkey configuration files, by translating the current ACLs set -for the users back into their description. If [roles](#roles) are defined, -they are reported first, in lines starting with "role". - -The first two words in each line are "user" followed by the username. The -next words are ACL rules that describe different things. We'll show how the rules work in detail, but for now it is enough to say that the default -user is configured to be active (on), to require no password (nopass), to -access every possible key (`~*`) and Pub/Sub channel (`&*`), every -database, and be able to call every possible command (`+@all`). - -Also, in the special case of the default user, having the *nopass* rule means -that new connections are automatically authenticated with the default user -without any explicit `AUTH` call needed. - -## ACL rules - -The following is the list of valid ACL rules. Certain rules are just -single words that are used in order to activate or remove a flag, or to -perform a given change to the user ACL. Other rules are char prefixes that -are concatenated with command or category names, key patterns, and -so forth. - -Enable and disallow users: - -* `on`: Enable the user: it is possible to authenticate as this user. -* `off`: Disallow the user: it's no longer possible to authenticate with this user; however, previously authenticated connections will still work. Note that if the default user is flagged as *off*, new connections will start as not authenticated and will require the user to send `AUTH` or `HELLO` with the AUTH option in order to authenticate in some way, regardless of the default user configuration. - -Allow and disallow commands: - -* `+`: Add the command to the list of commands the user can call. Can be used with `|` for allowing subcommands (e.g "+config|get"). -* `-`: Remove the command to the list of commands the user can call. Starting Valkey 7.0, it can be used with `|` for blocking subcommands (e.g "-config|set"). Note that commands which do not require authentication cannot be removed, e.g. AUTH, HELLO, and RESET. -* `+@`: Add all the commands in such category to be called by the user, with valid categories being like @admin, @set, @sortedset, ... and so forth, see the full list by calling the `ACL CAT` command. The special category @all means all the commands, both the ones currently present in the server, and the ones that will be loaded in the future via modules. -* `-@`: Like `+@` but removes the commands from the list of commands the client can call. -* `+|first-arg`: Allow a specific first argument of an otherwise disabled command. It is only supported on commands with no sub-commands, and is not allowed as negative form like -SELECT|1, only additive starting with "+". This feature is deprecated and may be removed in the future. -* `allcommands`: Alias for +@all. Note that it implies the ability to execute all the future commands loaded via the modules system. -* `nocommands`: Alias for -@all. - -Allow and disallow certain keys and key permissions: - -* `~`: Add a pattern of keys that can be mentioned as part of commands. For instance `~*` allows all the keys. The pattern is a glob-style pattern like the one of `KEYS`. It is possible to specify multiple patterns. -* `%R~`: Add the specified read key pattern. This behaves similar to the regular key pattern but only grants permission to read from keys that match the given pattern. See [key permissions](#key-permissions) for more information. -* `%W~`: Add the specified write key pattern. This behaves similar to the regular key pattern but only grants permission to write to keys that match the given pattern. See [key permissions](#key-permissions) for more information. -* `%RW~`: Alias for `~`. -* `allkeys`: Alias for `~*`. -* `resetkeys`: Flush the list of allowed keys patterns. For instance the ACL `~foo:* ~bar:* resetkeys ~objects:*`, will only allow the client to access keys that match the pattern `objects:*`. - -Allow and disallow Pub/Sub channels: - -* `&`: Add a glob style pattern of Pub/Sub channels that can be accessed by the user. It is possible to specify multiple channel patterns. Note that pattern matching is done only for channels mentioned by `PUBLISH` and `SUBSCRIBE`, whereas `PSUBSCRIBE` requires a literal match between its channel patterns and those allowed for user. -* `allchannels`: Alias for `&*` that allows the user to access all Pub/Sub channels. -* `resetchannels`: Flush the list of allowed channel patterns and disconnect the user's Pub/Sub clients if these are no longer able to access their respective channels and/or channel patterns. - -Allow and disallow logical databases: - -* `db=[,...]`: Sets the specified database id(s) as the databases the user is allowed to access. - Multiple ids are separated by commas, e.g. `db=0,1,2`; at least one id is required. - Clears the `alldbs` flag and any previously configured database ids on the selector. - See [database permissions](#database-permissions) for more information. -* `alldbs`: Allow the user to access all databases. This is the default for newly created selectors and is omitted from generated ACL strings. -* `resetdbs`: Flush the list of allowed databases and clear the `alldbs` flag. After `resetdbs`, the user (or selector) cannot access any database until additional `db=` rules or `alldbs` are added. - -Configure valid passwords for the user: - -* `>`: Add this password to the list of valid passwords for the user. For example `>mypass` will add "mypass" to the list of valid passwords. This directive clears the *nopass* flag (see later). Every user can have any number of passwords. -* `<`: Remove this password from the list of valid passwords. Emits an error in case the password you are trying to remove is actually not set. -* `#`: Add this SHA-256 hash value to the list of valid passwords for the user. This hash value will be compared to the hash of a password entered for an ACL user. This allows users to store hashes in the `acl.conf` file rather than storing cleartext passwords. Only SHA-256 hash values are accepted as the password hash must be 64 characters and only contain lowercase hexadecimal characters. -* `!`: Remove this hash value from the list of valid passwords. This is useful when you do not know the password specified by the hash value but would like to remove the password from the user. -* `nopass`: All the set passwords of the user are removed, and the user is flagged as requiring no password: it means that every password will work against this user. If this directive is used for the default user, every new connection will be immediately authenticated with the default user without any explicit AUTH command required. Note that the *resetpass* directive will clear this condition. -* `resetpass`: Flushes the list of allowed passwords and removes the *nopass* status. After *resetpass*, the user has no associated passwords and can only authenticate using client certificates, if `tls-auth-clients-user` is enabled. - -*Note: if a user is not flagged with nopass and has no list of valid passwords, that user is impossible to authenticate via password. Such users can still be authenticated through mTLS certificate fields if `tls-auth-clients-user` is enabled.* - -Configure selectors for the user: - -* `()`: Create a new selector to match rules against. Selectors are evaluated after the user permissions, and are evaluated according to the order they are defined. If a command matches either the user permissions or any selector, it is allowed. See [selectors](#selectors) for more information. -* `clearselectors`: Delete all of the selectors attached to the user. - -Assign roles to the user (Added in version 9.2): - -* `role=[, ...]`: Assign the named roles to the user, replacing any role the user already had. At least one role has to be named, and every named role must already exist. See [roles](#roles) for more information. -* `resetroles`: Remove every role from the user. - -Reset the user: - -* `reset` Performs the following actions: resetpass, resetkeys, resetchannels, allchannels (if acl-pubsub-default is set), resetdbs, alldbs, off, clearselectors, -@all, resetroles. The user returns to the same state it had immediately after its creation. - -## Create and edit user ACLs with the ACL SETUSER command - -Users can be created and modified in two main ways: - -1. Using the ACL command and its `ACL SETUSER` subcommand. -2. Modifying the server configuration, where users can be defined, and restarting the server. With an *external ACL file*, just call `ACL LOAD`. - -In this section we'll learn how to define users using the `ACL` command. -With such knowledge, it will be trivial to do the same things via the -configuration files. Defining users in the configuration deserves its own -section and will be discussed later separately. - -To start, try the simplest `ACL SETUSER` command call: - - > ACL SETUSER alice - OK - -The `ACL SETUSER` command takes the username and a list of ACL rules to apply -to the user. However the above example did not specify any rule at all. -This will just create the user if it did not exist, using the defaults for new -users. If the user already exists, the command above will do nothing at all. - -Check the default user status: - - > ACL LIST - 1) "user alice off resetchannels -@all" - 2) "user default on nopass ~* &* +@all" - -The new user "alice" is: - -* In the off status, so `AUTH` will not work for the user "alice". -* The user also has no passwords set. -* Cannot access any command. Note that the user is created by default without the ability to access any command, so the `-@all` in the output above could be omitted; however, `ACL LIST` attempts to be explicit rather than implicit. -* There are no key patterns that the user can access. -* There are no Pub/Sub channels that the user can access. - -Such user is completely useless. Let's try to define the user so that -it is active, has a password, and can access with only the `GET` command -to key names starting with the string "cached:". - - > ACL SETUSER alice on >p1pp0 ~cached:* +get - OK - -Now the user can do something, but will refuse to do other things: - - > AUTH alice p1pp0 - OK - > GET foo - (error) NOPERM this user has no permissions to access one of the keys used as arguments - > GET cached:1234 - (nil) - > SET cached:1234 zap - (error) NOPERM this user has no permissions to run the 'set' command - -Things are working as expected. In order to inspect the configuration of the -user alice (remember that user names are case sensitive), it is possible to -use an alternative to `ACL LIST` which is designed to be more suitable for -computers to read, while `ACL GETUSER` is more human readable. - - > ACL GETUSER alice - 1) "flags" - 2) 1) "on" - 3) "passwords" - 4) 1) "2d9c75..." - 5) "commands" - 6) "-@all +get" - 7) "keys" - 8) "~cached:*" - 9) "channels" - 10) "" - 11) "databases" - 12) "alldbs" - 13) "selectors" - 14) (empty array) - -The `ACL GETUSER` returns a field-value array that describes the user in more parsable terms. The output includes the set of flags, a list of key patterns, passwords, and so forth. New fields may be added over time. For example, Valkey 9.1 added the `databases` field. The output is probably more readable if we use RESP3, so that it is returned as a map reply: - - > ACL GETUSER alice - 1# "flags" => 1~ "on" - 2# "passwords" => 1) "2d9c75273d72b32df726fb545c8a4edc719f0a95a6fd993950b10c474ad9c927" - 3# "commands" => "-@all +get" - 4# "keys" => "~cached:*" - 5# "channels" => "" - 6# "databases" => "alldbs" - 7# "selectors" => (empty array) - -*Note: from now on, we'll continue using the Valkey default protocol, version 2* - -Using another `ACL SETUSER` command (from a different user, because alice cannot run the `ACL` command), we can add multiple patterns to the user: - - > ACL SETUSER alice ~objects:* ~items:* ~public:* - OK - > ACL LIST - 1) "user alice on #2d9c75... ~cached:* ~objects:* ~items:* ~public:* resetchannels -@all +get" - 2) "user default on nopass ~* &* +@all" - -The user representation in memory is now as we expect it to be. - -## Multiple calls to ACL SETUSER - -It is very important to understand what happens when `ACL SETUSER` is called -multiple times. What is critical to know is that every `ACL SETUSER` call will -NOT reset the user, but will just apply the ACL rules to the existing user. -The user is reset only if it was not known before. In that case, a brand new -user is created with zeroed-ACLs. The user cannot do anything, is -disallowed, has no passwords, and so forth. This is the best default for safety. - -However later calls will just modify the user incrementally. For instance, -the following sequence: - - > ACL SETUSER myuser +set - OK - > ACL SETUSER myuser +get - OK - -Will result in myuser being able to call both `GET` and `SET`: - - > ACL LIST - 1) "user default on nopass ~* &* +@all" - 2) "user myuser off resetchannels -@all +get +set" - -## Command categories - -Setting user ACLs by specifying all the commands one after the other is -really annoying, so instead we do things like this: - - > ACL SETUSER antirez on +@all -@dangerous >42a979... ~* - -By saying +@all and -@dangerous, we included all the commands and later removed -all the commands that are tagged as dangerous inside the Valkey command table. -Note that command categories **never include modules commands** with -the exception of +@all. If you say +@all, all the commands can be executed by -the user, even future commands loaded via the modules system. However if you -use the ACL rule +@read or any other, the modules commands are always -excluded. This is very important because you should just trust the Valkey -internal command table. Modules may expose dangerous things and in -the case of an ACL that is just additive, that is, in the form of `+@all -...` -You should be absolutely sure that you'll never include what you did not mean -to. - -The following is a list of command categories and their meanings: - -* **admin** - Administrative commands. Normal applications will never need to use - these. Includes `REPLICAOF`, `CONFIG`, `DEBUG`, `SAVE`, `MONITOR`, `ACL`, `SHUTDOWN`, etc. -* **bitmap** - Data type: bitmaps related. -* **blocking** - Potentially blocking the connection until released by another - command. -* **connection** - Commands affecting the connection or other connections. - This includes `AUTH`, `SELECT`, `COMMAND`, `CLIENT`, `ECHO`, `PING`, etc. -* **dangerous** - Potentially dangerous commands (each should be considered with care for - various reasons). This includes `FLUSHALL`, `MIGRATE`, `RESTORE`, `SORT`, `KEYS`, - `CLIENT`, `DEBUG`, `INFO`, `CONFIG`, `SAVE`, `REPLICAOF`, etc. -* **geo** - Data type: geospatial indexes related. -* **hash** - Data type: hashes related. -* **hyperloglog** - Data type: hyperloglog related. -* **fast** - Fast O(1) commands. May loop on the number of arguments, but not the - number of elements in the key. -* **keyspace** - Writing or reading from keys, databases, or their metadata - in a type agnostic way. Includes `DEL`, `RESTORE`, `DUMP`, `RENAME`, `EXISTS`, `DBSIZE`, - `KEYS`, `EXPIRE`, `TTL`, `FLUSHALL`, etc. Commands that may modify the keyspace, - key, or metadata will also have the `write` category. Commands that only read - the keyspace, key, or metadata will have the `read` category. -* **list** - Data type: lists related. -* **pubsub** - PubSub-related commands. -* **read** - Reading from keys (values or metadata). Note that commands that don't - interact with keys, will not have either `read` or `write`. -* **scripting** - Scripting related. -* **set** - Data type: sets related. -* **sortedset** - Data type: sorted sets related. -* **slow** - All commands that are not `fast`. -* **stream** - Data type: streams related. -* **string** - Data type: strings related. -* **transaction** - `WATCH` / `MULTI` / `EXEC` related commands. -* **write** - Writing to keys (values or metadata). - -Valkey can also show you a list of all categories and the exact commands each category includes using the Valkey `ACL CAT` command. It can be used in two forms: - - ACL CAT -- Will just list all the categories available - ACL CAT -- Will list all the commands inside the category - -Examples: - - > ACL CAT - 1) "keyspace" - 2) "read" - 3) "write" - 4) "set" - 5) "sortedset" - 6) "list" - 7) "hash" - 8) "string" - 9) "bitmap" - 10) "hyperloglog" - 11) "geo" - 12) "stream" - 13) "pubsub" - 14) "admin" - 15) "fast" - 16) "slow" - 17) "blocking" - 18) "dangerous" - 19) "connection" - 20) "transaction" - 21) "scripting" - -As you can see, so far there are 21 distinct categories. Now let's check what -command is part of the *geo* category: - - > ACL CAT geo - 1) "geohash" - 2) "georadius_ro" - 3) "georadiusbymember" - 4) "geopos" - 5) "geoadd" - 6) "georadiusbymember_ro" - 7) "geodist" - 8) "georadius" - 9) "geosearch" - 10) "geosearchstore" - -Note that commands may be part of multiple categories. For example, an -ACL rule like `+@geo -@read` will result in certain geo commands to be -excluded because they are read-only commands. - -## Allow/block subcommands - -Subcommands can be allowed/blocked just like other -commands (by using the separator `|` between the command and subcommand, for -example: `+config|get` or `-config|set`) - -That is true for all commands except DEBUG. In order to allow/block specific DEBUG subcommands, see the next section. - -## Allow the first-arg of a blocked command - -**Note: This feature is deprecated and may be removed in the future.** - -Sometimes the ability to exclude or include a command or a subcommand as a whole is not enough. -Many deployments may not be happy providing the ability to execute a `SELECT` for any DB, but may -still want to be able to run `SELECT 0`. -Database permissions are the preferred way to restrict which databases a user -can access; see [database permissions](#database-permissions). - -For versions without database permissions, we could alter the ACL of a user in the following way: - - ACL SETUSER myuser -select +select|0 - -First, remove the `SELECT` command and then add the allowed -first-arg. Note that **it is not possible to do the reverse** since first-args -can be only added, not excluded. It is safer to specify all the first-args -that are valid for some user since it is possible that -new first-args may be added in the future. - -Another example: - - ACL SETUSER myuser -debug +debug|digest - -Note that first-arg matching may add some performance penalty; however, it is hard to measure even with synthetic benchmarks. The -additional CPU cost is only paid when such commands are called, and not when -other commands are called. - -It is possible to use this mechanism in order to allow subcommands in Valkey -versions prior to 7.0 (see above section). - -## +@all VS -@all - -In the previous section, it was observed how it is possible to define command -ACLs based on adding/removing single commands. - -## Selectors - -Valkey supports adding multiple sets of rules that are evaluated independently of each other. -These secondary sets of permissions are called selectors and added by wrapping a set of rules within parentheses. -In order to execute a command, either the root permissions (rules defined outside of parenthesis) or any of the selectors (rules defined inside parenthesis) must match the given command. -Internally, the root permissions are checked first followed by selectors in the order they were added. - -For example, consider a user with the ACL rules `+GET ~key1 (+SET ~key2)`. -This user is able to execute `GET key1` and `SET key2 hello`, but not `GET key2` or `SET key1 world`. - -Unlike the user's root permissions, selectors cannot be modified after they are added. -Instead, selectors can be removed with the `clearselectors` keyword, which removes all of the added selectors. -Note that `clearselectors` does not remove the root permissions. - -## Roles - -Starting with Valkey 9.2, permissions can be defined once in a named _role_ and assigned to any number of users, instead of being repeated in every user. -A role holds the same kind of permissions a user does: commands, key patterns, channel patterns, databases and selectors. -Roles are created and modified with [`ACL SETROLE`](../commands/acl-setrole.md), which accepts the same rules as [`ACL SETUSER`](../commands/acl-setuser.md) except for the ones that only make sense for a user: `on`, `off`, `reset`, the password rules, `role=` and `resetroles`. -Roles are assigned to a user with the `role=` rule, and removed with `resetroles`: - - > ACL SETROLE reader ~app:* +@read - OK - > ACL SETROLE writer ~app:* +@write - OK - > ACL SETUSER alice on >alicepass role=reader - OK - > ACL SETUSER bob on >bobpass role=reader,writer - OK - > ACL DRYRUN alice SET app:1 x - "User alice has no permissions to run the 'set' command" - > ACL DRYRUN bob SET app:1 x - OK - -The `role=` rule replaces the whole set of roles held by the user, so `ACL SETUSER bob role=writer` leaves bob with the writer role only. - -A user's own permissions and the permissions of each of its roles are evaluated independently, and a command is allowed if any of them allows it, in the same way [selectors](#selectors) work. -The user's own permissions are checked first, followed by the roles in the order they were assigned. -This means a user can be granted permissions on top of a role, but cannot be restricted below what a role grants. - -Other things to know about roles: - -* Changes to a role with [`ACL SETROLE`](../commands/acl-setrole.md) take effect immediately for every user holding it. Pub/Sub clients of those users that lose access to their channels are disconnected. -* Roles cannot be nested, cannot have passwords, and cannot be authenticated against. -* A role cannot be deleted with [`ACL DELROLE`](../commands/acl-delrole.md) while it is assigned to a user. [`ACL GETROLE`](../commands/acl-getrole.md) lists the users holding a role. -* [`ACL ROLES`](../commands/acl-roles.md) lists the role names, [`ACL USERS`](../commands/acl-users.md) lists only the users. [`ACL LIST`](../commands/acl-list.md) reports both, with the `role` lines listed before the `user` lines. -* [`ACL GETUSER`](../commands/acl-getuser.md) reports the roles held by a user in the `roles` field, but the other fields only describe the user's own rules. Use [`ACL DRYRUN`](../commands/acl-dryrun.md) to check the effective permissions of a user. -* Role names are case sensitive and may contain any printable ASCII character except for spaces, commas, quotes and backslashes. Roles have their own namespace, so a role may share its name with a user, a command, or a category. - -**Note:** like a new user, a new role starts with access to all databases (`alldbs`, see [database permissions](#database-permissions)), and to all Pub/Sub channels if `acl-pubsub-default` is set to `allchannels`. -Since permissions are combined with OR logic, such a role grants all databases (and channels) to its users, even to a user restricted with `resetdbs`, `db=` or `resetchannels`. -To limit what a role grants, restrict the role itself, for example: - - > ACL SETROLE reader ~app:* +@read db=0 resetchannels - OK - -## Key permissions - -key patterns can also be used to define how a command is able to touch a key. -This is achieved through rules that define key permissions. -The key permission rules take the form of `%()~`. -Permissions are defined as individual characters that map to the following key permissions: - -* W (Write): The data stored within the key may be updated or deleted. -* R (Read): User supplied data from the key is processed, copied or returned. Note that this does not include metadata such as size information (example `STRLEN`), type information (example `TYPE`) or information about whether a value exists within a collection (example `SISMEMBER`). - -Permissions can be composed together by specifying multiple characters. -Specifying the permission as 'RW' is considered full access and is analogous to just passing in `~`. - -For a concrete example, consider a user with ACL rules `+@all ~app1:* (+@read ~app2:*)`. -This user has full access on `app1:*` and readonly access on `app2:*`. -However, some commands support reading data from one key, doing some transformation, and storing it into another key. -One such command is the `COPY` command, which copies the data from the source key into the destination key. -The example set of ACL rules is unable to handle a request copying data from `app2:user` into `app1:user`, since neither the root permission nor the selector fully matches the command. -However, using key selectors you can define a set of ACL rules that can handle this request `+@all ~app1:* %R~app2:*`. -The first pattern is able to match `app1:user` and the second pattern is able to match `app2:user`. - -Which type of permission is required for a command is documented through [key specifications](key-specs.md#logical-operation-flags). -The type of permission is based off the keys logical operation flags. -The insert, update, and delete flags map to the write key permission. -The access flag maps to the read key permission. -If the key has no logical operation flags, such as `EXISTS`, the user still needs either key read or key write permissions to execute the command. - -Note: Side channels to accessing user data are ignored when it comes to evaluating whether read permissions are required to execute a command. -This means that some write commands that return metadata about the modified key only require write permission on the key to execute. -For example, consider the following two commands: - -* `LPUSH key1 data`: modifies "key1" but only returns metadata about it, the size of the list after the push, so the command only requires write permission on "key1" to execute. -* `LPOP key2`: modifies "key2" but also returns data from it, the left most item in the list, so the command requires both read and write permission on "key2" to execute. - -If an application needs to make sure no data is accessed from a key, including side channels, it's recommended to not provide any access to the key. - -## Database permissions - -In addition to commands, keys, and Pub/Sub channels, ACL rules can restrict -which databases (see [`SELECT`](../commands/select.md)) a user is -allowed to access. By default a newly created selector has the `alldbs` flag -set, meaning the user can use any database. A `db=[,...]` rule -restricts the selector to only the listed databases. - -The default scope for database permissions is `alldbs`. The following rules -control database access: - -* `db=[,...]`: Allow access only to the listed database ids. - At least one id is required. - This replaces any previously configured database ids and clears `alldbs`. -* `alldbs`: Allow access to every database (default for new selectors). -* `resetdbs`: Remove every database from the allowed list and clear `alldbs`. - -For example, to create a user that may only operate on databases 0 and 1: - -``` -> ACL SETUSER alice on +@all ~* db=0,1 nopass -OK -> ACL LIST -1) "user alice on nopass ~* resetchannels db=0,1 +@all" -2) "user default on nopass ~* &* +@all" -``` - -A later `db=` rule replaces the previous database list: - -``` -> ACL SETUSER alice db=2,3 -OK -> ACL LIST -1) "user alice on nopass ~* resetchannels db=2,3 +@all" -2) "user default on nopass ~* &* +@all" -``` - -Use `resetdbs` to remove database access from an existing user: - -``` -> ACL SETUSER alice resetdbs -OK -> ACL LIST -1) "user alice on nopass ~* resetchannels resetdbs +@all" -2) "user default on nopass ~* &* +@all" -``` - -Database permissions can also be combined with [selectors](#selectors) so that -different rule sets apply to different databases: - -``` -> ACL SETUSER bob on nopass (db=0,1 +@write +select ~*) (db=2,3 +@read +select ~*) -OK -> ACL LIST -1) "user bob on nopass resetchannels -@all (~* resetchannels db=0,1 -@all +@write +select) (~* resetchannels db=2,3 -@all +@read +select)" -2) "user default on nopass ~* &* +@all" -``` - -The `ACL LIST` output shows three sets of permissions for `bob`: the root -permissions (`-@all`, with implicit `alldbs`) and two selectors, one for each -parenthesized rule set. A command is allowed when the root permissions or any selector matches it. -See [selectors](#selectors) for more information. - -### How database permissions are evaluated - -When a command is executed, the user must have access both to the command -itself and to every database the command touches. Two groups of commands -are checked specifically against the database list: - -Commands that explicitly reference a database id in their arguments require -the user to have access to that id: - -* [`SELECT`](../commands/select.md) - target database id. -* [`SWAPDB`](../commands/swapdb.md) - both database ids. -* [`MOVE`](../commands/move.md) - destination database id, and the source - database which is the currently selected database. -* [`COPY`](../commands/copy.md) - the destination database id when the `DB` - option is used. - -Commands that do not specify a database id but operate across the entire -keyspace require the user to have `alldbs`: - -* [`FLUSHALL`](../commands/flushall.md) -* [`CLUSTER CANCELSLOTMIGRATIONS`](../commands/cluster-cancelslotmigrations.md) -* [`CLUSTER MIGRATESLOTS`](../commands/cluster-migrateslots.md) - -When access is denied because of database permissions, the server replies with -a `NOPERM` error mentioning the database, and the event is recorded in -[`ACL LOG`](../commands/acl-log.md) with the reason `database`. - -### Connection establishment - -Authentication and authorization are decoupled from the currently selected -database. New client connections are placed in database 0 by default, even if -the authenticated user is not allowed to access database 0. This lets a client -authenticate first and then issue [`SELECT`](../commands/select.md) (or any -command that does not access the keyspace) to switch to a database the user is -allowed to use. - -## How passwords are stored internally - -Valkey internally stores passwords hashed with SHA256. If you set a password -and check the output of `ACL LIST` or `ACL GETUSER`, you'll see a long hex -string that looks pseudo random. Here is an example, because in the previous -examples, for the sake of brevity, the long hex string was trimmed: - - > ACL GETUSER default - 1) "flags" - 2) 1) "on" - 3) "passwords" - 4) 1) "2d9c75273d72b32df726fb545c8a4edc719f0a95a6fd993950b10c474ad9c927" - 5) "commands" - 6) "+@all" - 7) "keys" - 8) "~*" - 9) "channels" - 10) "&*" - 11) "selectors" - 12) (empty array) - -Using SHA256 provides the ability to avoid storing the password in clear text -while still allowing for a very fast `AUTH` command, which is a very important -feature of Valkey and is coherent with what clients expect from Valkey. - -However ACL *passwords* are not really passwords. They are shared secrets -between the server and the client, because the password is -not an authentication token used by a human being. For instance: - -* There are no length limits, the password will just be memorized in some client software. There is no human that needs to recall a password in this context. -* The ACL password does not protect any other thing. For example, it will never be the password for some email account. -* Often when you are able to access the hashed password itself, by having full access to the Valkey commands of a given server, or corrupting the system itself, you already have access to what the password is protecting: the Valkey instance stability and the data it contains. - -For this reason, slowing down the password authentication, in order to use an -algorithm that uses time and space to make password cracking hard, -is a very poor choice. What we suggest instead is to generate strong -passwords, so that nobody will be able to crack it using a -dictionary or a brute force attack even if they have the hash. To do so, there is a special ACL -command `ACL GENPASS` that generates passwords using the system cryptographic pseudorandom -generator: - - > ACL GENPASS - "dd721260bfe1b3d9601e7fbab36de6d04e2e67b0ef1c53de59d45950db0dd3cc" - -The command outputs a 32-byte (256-bit) pseudorandom string converted to a -64-byte alphanumerical string. This is long enough to avoid attacks and short -enough to be easy to manage, cut & paste, store, and so forth. This is what -you should use in order to generate Valkey passwords. - -## Use an external ACL file - -There are two ways to store users inside the Valkey configuration: - -1. Users can be specified directly inside the `valkey.conf` file. -2. It is possible to specify an external ACL file. - -The two methods are *mutually incompatible*, so Valkey will ask you to use one -or the other. Specifying users inside `valkey.conf` is -good for simple use cases. When there are multiple users to define, in a -complex environment, we recommend you use the ACL file instead. - -The format used inside `valkey.conf` and in the external ACL file is exactly -the same, so it is trivial to switch from one to the other, and is -the following: - - user ... acl rules ... - -For instance: - - user worker +@list +@connection ~jobs:* on >ffa9203c493aa99 - -[Roles](#roles) are defined in the same way, using the `role` keyword: - - role ... acl rules ... - -For instance: - - role jobs +@list ~jobs:* - user worker +@connection on >ffa9203c493aa99 role=jobs - -Roles are loaded before users, so the `role` and `user` lines may appear in -any order. `ACL SAVE` writes the roles before the users. - -When you want to use an external ACL file, you are required to specify -the configuration directive called `aclfile`, like this: - - aclfile /etc/valkey/users.acl - -When you are just specifying a few users directly inside the `valkey.conf` -file, you can use `CONFIG REWRITE` in order to store the new user configuration -inside the file by rewriting it. - -The external ACL file however is more powerful. You can do the following: - -* Use `ACL LOAD` if you modified the ACL file manually and you want Valkey to reload the new configuration. Note that this command is able to load the file *only if all the users are correctly specified*. Otherwise, an error is reported to the user, and the old configuration will remain valid. -* Use `ACL SAVE` to save the current ACL configuration to the ACL file. - -Note that `CONFIG REWRITE` does not also trigger `ACL SAVE`. When you use -an ACL file, the configuration and the ACLs are handled separately. - -## ACL rules for Sentinel and Replicas - -In case you don't want to provide Valkey replicas and Valkey Sentinel instances -full access to your Valkey instances, the following is the set of commands -that must be allowed in order for everything to work correctly. - -For Sentinel, allow the user to access the following commands both in the primary and replica instances: - -* AUTH, CLIENT, SUBSCRIBE, SCRIPT, PUBLISH, PING, INFO, MULTI, SLAVEOF, CONFIG, CLIENT, EXEC. - -Sentinel does not need to access any key in the database but does use Pub/Sub, so the ACL rule would be the following (note: `AUTH` is not needed since it is always allowed): - - ACL SETUSER sentinel-user on >somepassword allchannels +multi +slaveof +ping +exec +subscribe +config|rewrite +role +publish +info +client|setname +client|kill +script|kill - -Valkey replicas require the following commands to be allowed on the primary instance: - -* SYNC, PSYNC, REPLCONF, PING - -Although `SYNC` is deprecated, it is still used in dual-channel replication when the RDB channel requests a full resynchronization. `PSYNC` is the preferred command for other replication scenarios. - -For cluster deployments, Valkey 9.0 introduces the Atomic Slot Migration feature, which requires additional permissions: - -* CLUSTER SYNCSLOTS, @write, SELECT - -Since `@write` also includes dangerous commands such as `FLUSHALL` and `FLUSHDB`, you will need to exclude them. -This translate to the following rules: - - ACL setuser replica-user on >somepassword +@write ~* -@dangerous +ping +select +sync +psync +replconf +cluster|syncslots -flushall -flushdb -restore -restore-asking - -Note that you don't need to configure the replicas to allow the primary to be able to execute any set of commands. The primary is always authenticated as the root user from the point of view of replicas. diff --git a/topics/admin.md b/topics/admin.md deleted file mode 100644 index 6874e70c..00000000 --- a/topics/admin.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: Administration -description: Advice for configuring and managing Valkey in production ---- - -## Valkey setup tips - -### Linux - -* Deploy Valkey using the Linux operating system. - Valkey is also regularly tested on macOS and FreeBSD, and from time to time on other OpenBSD, NetBSD, DragonFlyBSD and Solaris-derived systems. - However, Linux is where most of the stress testing is performed, and where most production deployments are run. - -* Set the Linux kernel overcommit memory setting to 1. Add `vm.overcommit_memory = 1` to `/etc/sysctl.conf`. Then, reboot or run the command `sysctl vm.overcommit_memory=1` to activate the setting. See [FAQ: Background saving fails with a fork() error on Linux?](faq.md#background-saving-fails-with-a-fork-error-on-linux) for details. - -* To ensure the Linux kernel feature Transparent Huge Pages does not impact Valkey memory usage and latency, run the command: `echo never > /sys/kernel/mm/transparent_hugepage/enabled` to disable it. See [Latency Diagnosis - Latency induced by transparent huge pages](latency.md#latency-induced-by-transparent-huge-pages) for additional context. - -### Memory - -* Ensured that swap is enabled and that your swap file size is equal to amount of memory on your system. If Linux does not have swap set up, and your Valkey instance accidentally consumes too much memory, Valkey can crash when it is out of memory, or the Linux kernel OOM killer can kill the Valkey process. When swapping is enabled, you can detect latency spikes and act on them. - -* Set an explicit `maxmemory` option limit in your instance to make sure that it will report errors instead of failing when the system memory limit is near to be reached. Note that `maxmemory` should be set by calculating the overhead for Valkey, other than data, and the fragmentation overhead. So if you think you have 10 GB of free memory, set it to 8 or 9. - -* If you are using Valkey in a write-heavy application, while saving an RDB file on disk or rewriting the AOF log, Valkey can use up to 2 times the memory normally used. The additional memory used is proportional to the number of memory pages modified by writes during the saving process, so it is often proportional to the number of keys (or aggregate types items) touched during this time. Make sure to size your memory accordingly. - -* See the `LATENCY DOCTOR` and `MEMORY DOCTOR` commands to assist in troubleshooting. - -### Imaging - -* When running under daemontools, use `daemonize no`. - -### Replication - -* Set up a non-trivial replication backlog in proportion to the amount of memory Valkey is using. The backlog allows replicas to sync with the primary instance much more easily. - -* If you use replication, Valkey performs RDB saves even if persistence is disabled. (This does not apply to diskless replication.) If you don't have disk usage on the primary, enable diskless replication. - -* If you are using replication, ensure that either your primary has persistence enabled, or that it does not automatically restart on crashes. Replicas will try to maintain an exact copy of the primary, so if a primary restarts with an empty data set, replicas will be wiped as well. - -### Security - -* By default, Valkey does not require any authentication and listens to all the network interfaces. This is a big security issue if you leave Valkey exposed on the internet or other places where attackers can reach it. Please check our [security page](security.md) and the [quick start](quickstart.md) for information about how to secure Valkey. - -## Running Valkey on EC2 - -* Use HVM based instances, not PV based instances. -* The use of Valkey persistence with EC2 EBS volumes needs to be handled with care because sometimes EBS volumes have high latency characteristics. -* You may want to try diskless replication if you have issues when replicas are synchronizing with the primary. - -## Upgrading or restarting a Valkey instance without downtime - -Valkey is designed to be a long-running process in your server. You can modify many configuration options without a restart using the `CONFIG SET` command. You can also switch from AOF to RDB snapshots persistence, or the other way around, without restarting Valkey. Check the output of the `CONFIG GET *` command for more information. - -From time to time, a restart is required, for example, to upgrade the Valkey process to a newer version, or when you need to modify a configuration parameter that is currently not supported by the `CONFIG` command. - -Follow these steps to avoid downtime. - -* Set up your new Valkey instance as a replica for your current Valkey instance. In order to do so, you need a different server, or a server that has enough RAM to keep two instances of Valkey running at the same time. - -* If you use a single server, ensure that the replica is started on a different port than the primary instance, otherwise the replica cannot start. - -* Wait for the replication initial synchronization to complete. Check the replica's log file. - -* Using `INFO`, ensure the primary and replica have the same number of keys. Use `valkey-cli` to check that the replica is working as expected and is replying to your commands. - -* Allow writes to the replica using `CONFIG SET replica-read-only no`. - -* Configure all your clients to use the new instance (the replica). Note that you may want to use the `CLIENT PAUSE` command to ensure that no client can write to the old primary during the switch. - -* Once you confirm that the primary is no longer receiving any queries (you can check this using the `MONITOR` command), elect the replica to primary using the `REPLICAOF NO ONE` command, and then shut down your primary. - -If you are using [Valkey Sentinel](sentinel.md) or [Valkey Cluster](cluster-tutorial.md), the simplest way to upgrade to newer versions is to upgrade one replica after the other. Then you can perform a manual failover to promote one of the upgraded replicas to primary, and finally promote the last replica. diff --git a/topics/atomic-slot-migration.md b/topics/atomic-slot-migration.md deleted file mode 100644 index 10ebd998..00000000 --- a/topics/atomic-slot-migration.md +++ /dev/null @@ -1,157 +0,0 @@ ---- -title: Atomic slot migration -description: Overview of atomic slot migration ---- - -In [Valkey Cluster](cluster-spec.md), you can use a process known as slot -migration to scale your cluster in or out. During slot migration, one or more of -the 16384 hash slots are moved from a source node to a target node. Valkey 9.0 -introduced a option for migrating hash slots known as **atomic slot -migration**, which is faster, more reliable, and has less impact on client -applications than the legacy `CLUSTER SETSLOT`-based migration. - -## Performing an atomic slot migration using `CLUSTER MIGRATESLOTS` - -Valkey 9.0 does not get rid of the legacy slot migration option, but it does -introduce atomic slot migration as a second option. To perform an atomic slot -migration, an operator performs the following steps: - -1. Send `` - `CLUSTER MIGRATESLOTS SLOTSRANGE NODE ` -2. Poll `` for progress using `CLUSTER GETSLOTMIGRATIONS` - -`CLUSTER MIGRATESLOTS` initiates a migration of the designated slot range to the -specified target node. The slot migration process is then performed -asynchronously. - -For more details on `CLUSTER MIGRATESLOTS` see the -[command documentation](../commands/cluster-migrateslots.md). - -## Polling atomic slot migrations - -The `CLUSTER GETSLOTMIGRATIONS` command allows you to poll the status of your -migration. `CLUSTER GETSLOTMIGRATIONS` can be executed on either the source node -or the target node. In progress migrations will always be shown, and recently -completed migrations will be visible up to a configurable threshold. In the case -of a failure, the slot migration will also include a short description of the -failure to allow for retry decisions. - -For more details on `CLUSTER GETSLOTMIGRATIONS` see the -[command documentation](../commands/cluster-getslotmigrations.md). - -## Canceling atomic slot migrations - -If you need to cancel a slot migration after the process was started, Valkey -provides the `CLUSTER CANCELSLOTMIGRATIONS` command to cancel all active atomic -slot migrations for which that node is the source node. This command can be sent -to the whole cluster to cancel all slot migrations everywhere. - -For more details on `CLUSTER CANCELSLOTMIGRATIONS` see the -[command documentation](../commands/cluster-cancelslotmigrations.md). - -## Behind the scenes of atomic slot migration - -Atomic slot migration utilizes a completely different process than -`CLUSTER SETSLOT`-based migrations: - -1. Immediately after `CLUSTER MIGRATESLOTS` is received by the source node, it - initiates a connection to the target node and performs authentication, - similar to how a replication link is initialized. -2. Once established, the source node uses a new internal command - - `CLUSTER SYNCSLOTS` - to inform the target of the migration. -3. The source node then forks a child process to do a one-time snapshot of the - slot contents. The fork iterates all hash slots and serializes their contents - over the slot migration link. The contents are subsequently replicated to any - replicas of the target node. -4. While the child process is doing the snapshot, the parent process tracks all - mutations performed on the migrating hash slots. -5. Once the child process snapshot finishes, the parent process sends all - accumulated mutations. Any new mutations received during this step are also - sent. -6. Once the amount of in-flight mutations goes below a configured threshold, the - parent process pauses write commands temporarily to allow final - synchronization of the hash slots. -7. Once the target node is completely caught up, it takes over the hash slots - and broadcasts ownership to the cluster -8. When the source node finds out about the migration, it deletes the keys in - the hash slot and unpauses write commands. Clients will now get `MOVED` - redirections to the target node, which now owns the hash slots. The slot - migration is completed. - -### Isolation of importing hash slots from clients - -Since slot ownership is not moved until the very end of the migration, commands -targeting migrating hash slots on the target node will receive `MOVED` -redirections per the cluster specification. But there are some commands that -operate on the entire database: - -1. `KEYS`/`SCAN`: These commands allow a client to list out all keys on a shard. -2. `DBSIZE`/`INFO`: These commands provide statistical information about how - many keys are on a shard. -3. `FLUSHDB`/`FLUSHALL`: These commands allow a client to drop all data in a - database, or on all databases, on a node. - -To handle this, all importing hash slots are marked specially and hidden from -read operations on both the target primary and the target replica. - -`FLUSHDB` and `FLUSHALL` present a special case where we fail the slot migration -when being executed on **both the source and target node**. It is expected that -operators would retry the migration after flushing, which should now succeed -almost instantly due to an empty database. - -## Configuring atomic slot migration - -Some configurations may be worth tuning based on your workload: - -- `client-output-buffer-limit`: Since atomic slot migration uses the - replication process to migrate the slots, the amount of accumulated mutations - while snapshotting could exceed that of the configured replication output - buffer limit. Both the hard and soft limits of the `replica` client output - buffer should be configured large enough to accumulate the accumulated - mutations. -- `slot-migration-max-failover-repl-bytes`: By default, atomic slot migration - will only proceed to pausing mutations on the source node once all in-flight - mutations have been sent to the target node. However, for workloads with - persistently high write throughput, atomic slot migration can be configured to - do the pause so long as all in-flight mutations are under a given threshold. -- `cluster-slot-migration-log-max-len`: atomic slot migration keeps track of all - in progress migrations and recently completed or failed migrations. These can - be viewed with `CLUSTER GETSLOTMIGRATIONS`. The number of recently completed - migrations stored can be increased using this configuration. - -## ACL requirements for atomic slot migration - -Since atomic slot migration reuses much of Valkey's replication infrastructure, it's natural to assume the replication user only needs the same permissions as a normal replica: - -```bash -+psync +replconf +ping +cluster|syncslots -``` - -However, migrating a hash slot that contains data requires additional permissions in Valkey 9.0. -Unlike normal replication, where incoming data is applied by an internal superuser client that does not require write permissions, atomic slot migration pushes data to the target node using the user configured by the `primaryuser` configuration parameter. -During atomic slot migration, commands used to apply the migrated data on the target are executed through the authenticated replication connection and are subject to the configured replication user's ACL. - -The user configured by `primaryuser` needs the following ACL permissions for atomic slot migration to succeed: - -```bash -+@write ~* -@dangerous +ping +select +psync +replconf +cluster|syncslots -flushall -flushdb -restore -restore-asking -``` - -The above command includes: - -- `+@write ~*`: to apply the migrated key data as ordinary write commands. -- `-@dangerous`: excludes destructive/administrative commands from `@write`. -- `+select`: required because Valkey 9.0 supports multiple databases in cluster mode, and the migration command stream can contain [`SELECT`](https://valkey.io/commands/select/). -- `-flushall -flushdb -restore -restore-asking`: explicitly re-excluded, since they would otherwise be reintroduced by `@write`. -However, `DEL` and `UNLINK` are intentionally not excluded because they can appear while replaying the command stream during migration. - -**Note:** The ACL rule order matters: rules are applied left to right, so `+psync -@dangerous` and `-@dangerous +psync` produce different results. -Be careful with ordering if customizing this ACL string. - -If the replication user lacks write permissions, the target node may log an error similar to: - -```text -This slot-import-target is sending an error to its slot-import-source: '-NOPERM User replicator has no permissions to run the 'set' command' after processing the command 'set' -``` - -This means that the target rejected a migrated command because the replication user does not have the required ACL permission. diff --git a/topics/benchmark.md b/topics/benchmark.md deleted file mode 100644 index 9548c35f..00000000 --- a/topics/benchmark.md +++ /dev/null @@ -1,544 +0,0 @@ ---- -title: "Benchmarking tool" -description: > - Using the valkey-benchmark utility on a Valkey server ---- - -## Usage - -**`valkey-benchmark`** [ _OPTIONS_ ] [**`--`**] [ _COMMAND_ _ARGS_... ] - -## Description - -Simulates sending commands using multiple clients. The utility provides a -default set of tests. You can run a subset of the tests using the `-t` option or -supply one or more custom commands on the command line. - -To supply multiple commands on the command line, separate them with `;` as in -`SET foo bar ';' GET foo`. (Quote `';'` to protect it from expansion by the shell.) -You can prefix a command in the sequence with a number N to repeat the command N times. -In command arguments, the following placeholders are substituted: - -`__rand_int__` -: Replaced with a zero-padded random integer in the range selected using the -r option. - Multiple occurrences within a single command each get different values. - -`__rand_1st__` -: Similar to `__rand_int__` but multiple occurrences will have the same - value. `__rand_2nd__` through `__rand_9th__` are also available. - -`__data__` -: Replaced with data of the size specified by the -d option. - -`__field:colname__` -: Replaced with data from the specified field/column in the - dataset. Requires the `--dataset` option. - -`{tag}` -: Replaced with a tag that routes the command to the right cluster node. - Include this in key names when running in cluster mode. - -## Options - -**`-h`** _hostname_ -: Server hostname (default 127.0.0.1) - -**`-p`** _port_ -: Server port (default 6379) - -**`-s`** _socket_ -: Server socket (overrides host and port) - -**`-a`** _password_ -: Password for Valkey Auth - -**`--user`** _username_ -: Used to send ACL style 'AUTH username pass'. Needs -a. - -**`-u`** _uri_ -: Server URI on format `valkey://user:password@host:port/dbnum`. - User, password and dbnum are optional. For authentication - without a username, use username 'default'. For TLS, use - the scheme 'valkeys'. - -**`-c`** _clients_ -: Number of parallel connections (default 50). - Note: If `--cluster` is used then number of clients has to be - the same or higher than the number of nodes. - -**`-n`** _requests_ -: Total number of requests (default 100000) - -**`--duration`** _seconds_ -: Run benchmark for specified number of seconds (mutually exclusive with `-n`) - -**`--warmup`** _seconds_ -: Run benchmark for specified warmup period before recording data. - -**`-d`** _size_ -: Data size of SET/GET value in bytes (default 3) - -**`--dbnum`** _db_ -: SELECT the specified db number (default 0) - -**`-3`** -: Start session in RESP3 protocol mode. - -**`--threads`** _num_ -: Enable multi-thread mode. - -**`--cluster`** -: Enable cluster mode. - If the command is supplied on the command line in cluster - mode, the key must contain "{tag}". Otherwise, the - command will not be sent to the right cluster node. - -**`--rfr`** _mode_ -: Enable read from replicas in cluster mode. - This command must be used with the `--cluster` option. - There are three modes for reading from replicas: - - **no** - sends read requests to primaries only (default). - - **yes** - sends read requests to replicas only. - - **all** - sends read requests to all nodes. - - Since write commands will be rejected by replicas, - it is recommended to enable read from replicas only for read command tests. - -**`--enable-tracking`** -: Send CLIENT TRACKING ON before starting benchmark. - -**`-k`** _boolean_ -: 1=keep alive 0=reconnect (default 1) - -**`-r`** _keyspacelen_ -: Use random keys for SET/GET/INCR, random values for SADD, - random members and scores for ZADD. - Using this option the benchmark will replace the string - `__rand_int__` inside an argument with a 12 digits number in - the specified range from 0 to keyspacelen - 1. The - substitution changes every time a command is executed. - Default tests use this to hit random keys in the specified - range. - Note: If `-r` is omitted, all commands in a benchmark will - use the same key. - -**`--sequential`** -: Modifies the -r argument to replace the string `__rand_int__` - with 12 digit numbers sequentially instead of randomly. - `__rand_1st__` through `__rand_9th__` are available with independent counters. - Used to create expected number of elements with multiple replacements. - Example: `ZADD myzset __rand_int__ element:__rand_1st__` - -**`-P`** _numreq_ -: Pipeline _numreq_ requests. Default 1 (no pipeline). - -**`-q`** -: Quiet. Just show query/sec values - -**`--precision`** -: Number of decimal places to display in latency output. - Default: 3. - -**`--csv`** -: Output in CSV format - -**`-l`** -: Loop. Run the tests forever - -**`-t`** _tests_ -: Only run the comma separated list of tests. The test - names are the same as the ones produced as output. - The `-t` option is ignored if a specific command is supplied - on the command line. - -**`-I`** -: Idle mode. Just open N idle connections and wait. - -**`-x`** -: Read last argument from STDIN. - -**`--rps`** _requests_ -: Limit the total number of requests per second. Default 0 (no limit). - -**`--seed`** _num_ -: Set the seed for random number generator. Default seed is based on time. - -**`--num-functions`** _num_ -: Set the number of functions present in the Lua lib that is loaded when running the `function_load` test. - Default: 10. - -**`--num-keys-in-fcall`** _num_ -: Set the number of keys passed to FCALL command when running the `fcall` test. - Default: 1. - -**`--dataset`** _file_ -: The path to the CSV/TSV dataset file for the field placeholder replacement. - All fields are auto-detected with natural content lengths. - -**`--maxdocs`** _num_ -: Maximum number of documents to load from dataset file. - Default: unlimited. - -**`--tls`** -: Establish a secure TLS connection. - -**`--sni`** _host_ -: Server name indication for TLS. - -**`--cacert`** _file_ -: CA Certificate file to verify with. - -**`--cacertdir`** _dir_ -: Directory where trusted CA certificates are stored. - If neither cacert nor cacertdir are specified, the default - system-wide trusted root certs configuration will apply. - -**`--insecure`** -: Allow insecure TLS connection by skipping cert validation. - -**`--cert`** _file_ -: Client certificate to authenticate with. - -**`--key`** _file_ -: Private key file to authenticate with. - -**`--tls-ciphers`** _list_ -: Sets the list of preferred ciphers (TLSv1.2 and below) - in order of preference from highest to lowest separated by colon (":"). - See the **ciphers**(1ssl) manpage for more information about the syntax of this string. - -**`--tls-ciphersuites`** _list_ -: Sets the list of preferred ciphersuites (TLSv1.3) - in order of preference from highest to lowest separated by colon (":"). - See the **ciphers**(1ssl) manpage for more information about the syntax of this string, - and specifically for TLSv1.3 ciphersuites. - -**`--rdma`** -: Establish an RDMA connection. - -**`--mptcp`** -: Establish an MPTCP connection. - -**`--fuzz`** -: Enable fuzzy mode to generate random commands. - WARNING: Use for testing only, it is not recommended to use with production data. - -**`--fuzz-mode`** _modes_ -: Sets fuzzing modes (comma-separated): `malformed-commands`, `config-commands`. - `malformed-commands`: Generates also malformed commands. - `config-commands`: Allows CONFIG SET commands. - Default: valid commands only. - -**`--fuzz-loglevel`** _level_ -: Sets the log level for fuzzer (none, error, info, debug). - Default is 'info'. - -**`--help`** -: Output help and exit. - -**`--version`** -: Output version and exit. - -## Examples - -Run the benchmark with the default configuration against 127.0.0.1:6379. You -need to have a running Valkey instance before launching the benchmark: - - $ valkey-benchmark - -Run a benchmark with 20 parallel clients, pipelining 10 commands at a time, -using 2 threads and less verbose output: - - $ valkey-benchmark -c 20 -P 10 --threads 2 -q - -Use 20 parallel clients, for a total of 100k requests, against 192.168.1.1: - - $ valkey-benchmark -h 192.168.1.1 -p 6379 -n 100000 -c 20 - -Fill 127.0.0.1:6379 with about 1 million keys only using the SET test: - - $ valkey-benchmark -t set -n 1000000 -r 100000000 - -Benchmark 127.0.0.1:6379 for a few commands producing CSV output: - - $ valkey-benchmark -t ping,set,get -n 100000 --csv - -Benchmark a specific command line: - - $ valkey-benchmark -r 10000 -n 10000 eval 'return redis.call("ping")' 0 - -Fill a list with 10000 random elements: - - $ valkey-benchmark -r 10000 -n 10000 lpush mylist __rand_int__ - -Benchmark a specific transaction: - - $ valkey-benchmark -- multi ';' set key:__rand_int__ __data__ ';' \ - incr counter ';' exec - -Run a time-based benchmark with warmup: - - $ valkey-benchmark --warmup 10 --duration 60 -c 100 -t set,get - -Run a rate-limited benchmark: - - $ valkey-benchmark -c 100 -n 500000 --rps 10000 -t set,get - -Benchmark using real data from a CSV dataset file: - - $ valkey-benchmark --dataset /path/to/data.csv -r 100000 -n 50000 \ - SET doc:__rand_int__ __field:content__ - -### Running only a subset of the tests - -You don't need to run all the default tests every time you execute `valkey-benchmark`. -For example, to select only a subset of tests, use the `-t` option -as in the following example: - - $ valkey-benchmark -t set,lpush -n 100000 -q - SET: 74239.05 requests per second - LPUSH: 79239.30 requests per second - -This example runs the tests for the `SET` and `LPUSH` commands and uses quiet mode (see the `-q` switch). - -You can even benchmark a specific command: - - $ valkey-benchmark -n 100000 -q script load "server.call('set','foo','bar')" - script load server.call('set','foo','bar'): 69881.20 requests per second - -### Selecting the size of the key space - -By default, the benchmark runs against a single key. In Valkey the difference -between such a synthetic benchmark and a real one is not huge since it is an -in-memory system, however it is possible to stress cache misses and in general -to simulate a more real-world work load by using a large key space. - -This is obtained by using the `-r` switch. For instance if I want to run -one million SET operations, using a random key for every operation out of -100k possible keys, I'll use the following command line: - - $ valkey-cli flushall - OK - - $ valkey-benchmark -t set -r 100000 -n 1000000 - ====== SET ====== - 1000000 requests completed in 13.86 seconds - 50 parallel clients - 3 bytes payload - keep alive: 1 - - 99.76% <= 1 milliseconds - 99.98% <= 2 milliseconds - 100.00% <= 3 milliseconds - 100.00% <= 3 milliseconds - 72144.87 requests per second - - $ valkey-cli dbsize - (integer) 99993 - -### Using pipelining - -By default every client (the benchmark simulates 50 clients if not otherwise -specified with `-c`) sends the next command only when the reply of the previous -command is received, this means that the server will likely need a read call -in order to read each command from every client. Also RTT is paid as well. - -Valkey supports [pipelining](pipelining.md), so it is possible to send -multiple commands at once, a feature often exploited by real world applications. -Valkey pipelining is able to dramatically improve the number of operations per -second a server is able do deliver. - -Consider this example of running the benchmark using a -pipelining of 16 commands: - - $ valkey-benchmark -n 1000000 -t set,get -P 16 -q - SET: 403063.28 requests per second - GET: 508388.41 requests per second - -Using pipelining results in a significant increase in performance. - -## Notes - -### Pitfalls and misconceptions - -The first point is obvious: the golden rule of a useful benchmark is to -only compare apples and apples. You can compare different versions of Valkey on the same workload or the same version of Valkey, but with -different options. If you plan to compare Valkey to something else, then it is -important to evaluate the functional and technical differences, and take them -in account. - -+ Valkey is a server: all commands involve network or IPC round trips. It is meaningless to compare it to embedded data stores, because the cost of most operations is primarily in network/protocol management. -+ Valkey commands return an acknowledgment for all usual commands. Some other data stores do not. Comparing Valkey to stores involving one-way queries is only mildly useful. -+ Naively iterating on synchronous Valkey commands does not benchmark Valkey itself, but rather measure your network (or IPC) latency and the client library intrinsic latency. To really test Valkey, you need multiple connections (like valkey-benchmark) and/or to use pipelining to aggregate several commands and/or multiple threads or processes. -+ Valkey is an in-memory data store with some optional persistence options. If you plan to compare it to transactional servers (MySQL, PostgreSQL, etc ...), then you should consider activating AOF and decide on a suitable fsync policy. -+ Valkey primarily operates as a single-threaded server from the POV of commands execution. While the server can employ threads for I/O operations and command parsing, the core command execution remains sequential. For CPU-intensive workloads requiring multiple cores, users should consider running multiple Valkey instances in parallel. It is not really fair to compare one single Valkey instance to a multi-threaded data store. - -The `valkey-benchmark` program is a quick and useful way to get some figures and -evaluate the performance of a Valkey instance on a given hardware. However, -by default, it does not represent the maximum throughput a Valkey instance can -sustain. Actually, by using pipelining and a fast client (libvalkey), it is fairly -easy to write a program generating more throughput than valkey-benchmark. The -default behavior of valkey-benchmark is to achieve throughput by exploiting -concurrency only (i.e. it creates several connections to the server). -It does not use pipelining or any parallelism at all (one pending query per -connection at most, and no multi-threading), if not explicitly enabled via -the `-P` parameter. So in some way using `valkey-benchmark` and, triggering, for -example, a `BGSAVE` operation in the background at the same time, will provide -the user with numbers more near to the *worst case* than to the best case. - -To run a benchmark using pipelining mode (and achieve higher throughput), -you need to explicitly use the -P option. Please note that it is still a -realistic behavior since a lot of Valkey based applications actively use -pipelining to improve performance. However you should use a pipeline size that -is more or less the average pipeline length you'll be able to use in your -application in order to get realistic numbers. - -The benchmark should apply the same operations, and work in the same way -with the multiple data stores you want to compare. It is absolutely pointless to -compare the result of valkey-benchmark to the result of another benchmark -program and extrapolate. - -For instance, Valkey and memcached in single-threaded mode can be compared on -GET/SET operations. Both are in-memory data stores, working mostly in the same -way at the protocol level. Provided their respective benchmark application is -aggregating queries in the same way (pipelining) and use a similar number of -connections, the comparison is actually meaningful. - -When you're benchmarking a high-performance, in-memory database like Valkey, -it may be difficult to saturate -the server. Sometimes, the performance bottleneck is on the client side, -and not the server-side. In that case, the client (i.e., the benchmarking program itself) -must be fixed, or perhaps scaled out, to reach the maximum throughput. - -### Factors impacting Valkey performance - -There are multiple factors having direct consequences on Valkey performance. -We mention them here, since they can alter the result of any benchmarks. -Please note however, that a typical Valkey instance running on a low end, -untuned box usually provides good enough performance for most applications. - -+ Network bandwidth and latency usually have a direct impact on the performance. -It is a good practice to use the ping program to quickly check the latency -between the client and server hosts is normal before launching the benchmark. -Regarding the bandwidth, it is generally useful to estimate -the throughput in Gbit/s and compare it to the theoretical bandwidth -of the network. For instance a benchmark setting 4 KB strings -in Valkey at 100000 q/s, would actually consume 3.2 Gbit/s of bandwidth -and probably fit within a 10 Gbit/s link, but not a 1 Gbit/s one. In many real -world scenarios, Valkey throughput is limited by the network well before being -limited by the CPU. To consolidate several high-throughput Valkey instances -on a single server, it worth considering putting a 10 Gbit/s NIC -or multiple 1 Gbit/s NICs with TCP/IP bonding. -+ CPU is another important factor. -+ Speed of RAM and memory bandwidth seem less critical for global performance -especially for small objects. For large objects (>10 KB), it may become -noticeable though. Usually, it is not really cost-effective to buy expensive -fast memory modules to optimize Valkey. -+ Valkey runs slower on a VM compared to running without virtualization using -the same hardware. If you have the chance to run Valkey on a physical machine -this is preferred. However this does not mean that Valkey is slow in -virtualized environments, the delivered performances are still very good -and most of the serious performance issues you may incur in virtualized -environments are due to over-provisioning, non-local disks with high latency, -or old hypervisor software that have slow `fork` syscall implementation. -+ When the server and client benchmark programs run on the same box, both -the TCP/IP loopback and unix domain sockets can be used. Depending on the -platform, unix domain sockets can achieve around 50% more throughput than -the TCP/IP loopback (on Linux for instance). The default behavior of -valkey-benchmark is to use the TCP/IP loopback. -+ The performance benefit of unix domain sockets compared to TCP/IP loopback -tends to decrease when pipelining is heavily used (i.e. long pipelines). -+ When an ethernet network is used to access Valkey, aggregating commands using -pipelining is especially efficient when the size of the data is kept under -the ethernet packet size (about 1500 bytes). Actually, processing 10 bytes, -100 bytes, or 1000 bytes queries almost result in the same throughput. -See the graph below. - - ![Data size impact](Data_size.png) - -+ On multi CPU sockets servers, Valkey performance becomes dependent on the -NUMA configuration and process location. The most visible effect is that -valkey-benchmark results seem non-deterministic because client and server -processes are distributed randomly on the cores. To get deterministic results, -it is required to use process placement tools (on Linux: taskset or numactl). -The most efficient combination is always to put the client and server on two -different cores of the same CPU to benefit from the L3 cache. -Here are some results of 4 KB SET benchmark for 3 server CPUs (AMD Istanbul, -Intel Nehalem EX, and Intel Westmere) with different relative placements. -Please note this benchmark is not meant to compare CPU models between themselves -(CPUs exact model and frequency are therefore not disclosed). - - ![NUMA chart](NUMA_chart.gif) - -+ With high-end configurations, the number of client connections is also an -important factor. Being based on epoll/kqueue, the Valkey event loop is quite -scalable. Valkey has already been benchmarked at more than 60000 connections, -and was still able to sustain 50000 q/s in these conditions. As a rule of thumb, -an instance with 30000 connections can only process half the throughput -achievable with 100 connections. Here is an example showing the throughput of -a Valkey instance per number of connections: - - ![connections chart](Connections_chart.png) - -+ With high-end configurations, it is possible to achieve higher throughput by -tuning the NIC(s) configuration and associated interruptions. Best throughput -is achieved by setting an affinity between Rx/Tx NIC queues and CPU cores, -and activating RPS (Receive Packet Steering) support. More information in this -[thread](https://groups.google.com/forum/#!msg/redis-db/gUhc19gnYgc/BruTPCOroiMJ). -Jumbo frames may also provide a performance boost when large objects are used. -+ Depending on the platform, Valkey can be compiled against different memory -allocators (libc malloc, jemalloc, tcmalloc), which may have different behaviors -in term of raw speed, internal and external fragmentation. -If you did not compile Valkey yourself, you can use the INFO command to check -the `mem_allocator` field. Please note most benchmarks do not run long enough to -generate significant external fragmentation (contrary to production Valkey -instances). - -### Other things to consider - -One important goal of any benchmark is to get reproducible results, so they -can be compared to the results of other tests. - -+ A good practice is to try to run tests on isolated hardware as much as possible. -If it is not possible, then the system must be monitored to check the benchmark -is not impacted by some external activity. -+ Some configurations (desktops and laptops for sure, some servers as well) -have a variable CPU core frequency mechanism. The policy controlling this -mechanism can be set at the OS level. Some CPU models are more aggressive than -others at adapting the frequency of the CPU cores to the workload. To get -reproducible results, it is better to set the highest possible fixed frequency -for all the CPU cores involved in the benchmark. -+ An important point is to size the system accordingly to the benchmark. -The system must have enough RAM and must not swap. On Linux, do not forget -to set the `overcommit_memory` parameter correctly. Please note 32 and 64 bit -Valkey instances do not have the same memory footprint. -+ If you plan to use RDB or AOF for your benchmark, please check there is no other -I/O activity in the system. Avoid putting RDB or AOF files on NAS or NFS shares, -or on any other devices impacting your network bandwidth and/or latency -(for instance, EBS on Amazon EC2). -+ Set Valkey logging level (loglevel parameter) to warning or notice. Avoid putting -the generated log file on a remote filesystem. -+ Avoid using monitoring tools which can alter the result of the benchmark. For -instance using INFO at regular interval to gather statistics is probably fine, -but MONITOR will impact the measured performance significantly. -+ When running `valkey-benchmark` on the same machine as the `valkey-server` -being tested, you may need to run the benchmark with at least two threads -(`--threads 2`) to prevent the benchmarking tool itself from being the -bottleneck, i.e. prevent that `valkey-benchmark` is running on 100% CPU while -`valkey-server` is using less than 100% CPU. - -### Other Valkey benchmarking tools - -There are several third-party tools that can be used for benchmarking Valkey. Refer to each tool's -documentation for more information about its goals and capabilities. - -* [memtier_benchmark](https://github.com/redislabs/memtier_benchmark) from [Redis Ltd.](https://twitter.com/RedisInc) is a NoSQL Valkey, Redis and Memcache traffic generation and benchmarking tool. -* [rpc-perf](https://github.com/twitter/rpc-perf) from [Twitter](https://twitter.com/twitter) is a tool for benchmarking RPC services that supports Valkey and Memcache. -* [YCSB](https://github.com/brianfrankcooper/YCSB) from [Yahoo @Yahoo](https://twitter.com/Yahoo) is a benchmarking framework with clients to many databases, including Valkey. - -## See also - -[valkey-cli](cli.md), [valkey-server](server.md) diff --git a/topics/bitfields.md b/topics/bitfields.md deleted file mode 100644 index 72852f2b..00000000 --- a/topics/bitfields.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: "Bitfields" -description: > - Introduction to Bitfields ---- - -Bitfields let you set, increment, and get integer values of arbitrary bit length. -For example, you can operate on anything from unsigned 1-bit integers to signed 63-bit integers. - -These values are stored using binary-encoded Strings. -Bitfields support atomic read, write and increment operations, making them a good choice for managing counters and similar numerical values. - - -## Basic commands - -* `BITFIELD` atomically sets, increments and reads one or more values. -* `BITFIELD_RO` is a read-only variant of `BITFIELD`. - - -## Example - -Suppose you want to maintain two metrics for various bicycles: the current price and the number of owners over time. You can represent these counters with a 32-bit wide bitfield per for each bike. - -* Bike 1 initially costs 1,000 (counter in offset 0) and has never had an owner. After being sold, it's now considered used and the price instantly drops to reflect its new condition, and it now has an owner (offset 1). After quite some time, the bike becomes a classic. The original owner sells it for a profit, so the price goes up and the number of owners does as well.Finally, you can look at the bike's current price and number of owners. - -``` -127.0.0.1:6379> BITFIELD bike:1:stats SET u32 #0 1000 -1) (integer) 0 -127.0.0.1:6379> BITFIELD bike:1:stats INCRBY u32 #0 -50 INCRBY u32 #1 1 -1) (integer) 950 -2) (integer) 1 -127.0.0.1:6379> BITFIELD bike:1:stats INCRBY u32 #0 500 INCRBY u32 #1 1 -1) (integer) 1450 -2) (integer) 2 -127.0.0.1:6379> BITFIELD bike:1:stats GET u32 #0 GET u32 #1 -1) (integer) 1450 -2) (integer) 2 -``` - - -## Performance - -`BITFIELD` is O(n), where _n_ is the number of counters accessed. diff --git a/topics/bitmaps.md b/topics/bitmaps.md deleted file mode 100644 index 14943a94..00000000 --- a/topics/bitmaps.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -title: "Bitmaps" -description: > - Introduction to Bitmaps ---- - -Bitmaps are not an actual data type, but a set of bit-oriented operations -defined on the String type which is treated like a bit vector. -Since strings are binary safe blobs and their maximum length is 512 MB, -they are suitable to set up to 2^32 different bits. - -You can perform bitwise operations on one or more strings. -Some examples of bitmap use cases include: - -* Efficient set representations for cases where the members of a set correspond to the integers 0-N. -* Object permissions, where each bit represents a particular permission, similar to the way that file systems store permissions. - -## Basic commands - -* `SETBIT` sets a bit at the provided offset to 0 or 1. -* `GETBIT` returns the value of a bit at a given offset. - -See the [complete list of bitmap commands](../commands/#bitmap). - - -## Example - -Suppose you have 1000 cyclists racing through the country-side, with sensors on their bikes labeled 0-999. -You want to quickly determine whether a given sensor has pinged a tracking server within the hour to check in on a rider. - -You can represent this scenario using a bitmap whose key references the current hour. - -* Rider 123 pings the server on January 1, 2024 within the 00:00 hour. You can then confirm that rider 123 pinged the server. You can also check to see if rider 456 has pinged the server for that same hour. - -``` -127.0.0.1:6379> SETBIT pings:2024-01-01-00:00 123 1 -(integer) 0 -127.0.0.1:6379> GETBIT pings:2024-01-01-00:00 123 -(integer) 1 -127.0.0.1:6379> GETBIT pings:2024-01-01-00:00 456 -(integer) 0 -``` - - -## Bit Operations - -Bit operations are divided into two groups: constant-time single bit -operations, like setting a bit to 1 or 0, or getting its value, and -operations on groups of bits, for example counting the number of set -bits in a given range of bits (e.g., population counting). - -One of the biggest advantages of bitmaps is that they often provide -extreme space savings when storing information. For example in a system -where different users are represented by incremental user IDs, it is possible -to remember a single bit information (for example, knowing whether -a user wants to receive a newsletter) of 4 billion users using just 512 MB of memory. - -The `SETBIT` command takes as its first argument the bit number, and as its second -argument the value to set the bit to, which is 1 or 0. The command -automatically enlarges the string if the addressed bit is outside the -current string length. - -`GETBIT` just returns the value of the bit at the specified index. -Out of range bits (addressing a bit that is outside the length of the string -stored into the target key) are always considered to be zero. - -There are three commands operating on group of bits: - -1. `BITOP` performs bit-wise operations between different strings. The provided operations are AND, OR, XOR and NOT. -2. `BITCOUNT` performs population counting, reporting the number of bits set to 1. -3. `BITPOS` finds the first bit having the specified value of 0 or 1. - -Both `BITPOS` and `BITCOUNT` are able to operate with byte ranges of the -string, instead of running for the whole length of the string. We can trivially see the number of bits that have been set in a bitmap. - -``` -127.0.0.1:6379> BITCOUNT pings:2024-01-01-00:00 -(integer) 1 -``` - -For example imagine you want to know the longest streak of daily visits of -your web site users. You start counting days starting from zero, that is the -day you made your web site public, and set a bit with `SETBIT` every time -the user visits the web site. As a bit index you simply take the current unix -time, subtract the initial offset, and divide by the number of seconds in a day -(normally, 3600\*24). - -This way for each user you have a small string containing the visit -information for each day. With `BITCOUNT` it is possible to easily get -the number of days a given user visited the web site, while with -a few `BITPOS` calls, or simply fetching and analyzing the bitmap client-side, -it is possible to easily compute the longest streak. - -Bitmaps are trivial to split into multiple keys, for example for -the sake of sharding the data set and because in general it is better to -avoid working with huge keys. To split a bitmap across different keys -instead of setting all the bits into a key, a trivial strategy is just -to store M bits per key and obtain the key name with `bit-number/M` and -the Nth bit to address inside the key with `bit-number MOD M`. - - - -## Performance - -`SETBIT` and `GETBIT` are O(1). -`BITOP` is O(n), where _n_ is the length of the longest string in the comparison. diff --git a/topics/bloomfilters.md b/topics/bloomfilters.md deleted file mode 100644 index 7a5cf3bf..00000000 --- a/topics/bloomfilters.md +++ /dev/null @@ -1,364 +0,0 @@ ---- -title: "Bloom Filters" -description: > - Introduction to Bloom Filters ---- - -In Valkey, the bloom filter data type / commands are implemented in the [valkey-bloom module](https://github.com/valkey-io/valkey-bloom) which is an official valkey module compatible with versions 8.0 and above. Users will need to load this module onto their valkey server in order to use this feature. - -Bloom filters are a space efficient probabilistic data structure that allows adding elements and checking whether elements exist. False positives are possible where a filter incorrectly indicates that an element exists, even though it was not added. However, Bloom Filters guarantee that false negatives (incorrectly indicating that an element does not exist, even though it was added) do not occur. - -## Basic Bloom commands - -* [`BF.ADD`](../commands/bf.add.md) - adds an item to a bloom filter -* [`BF.CARD`](../commands/bf.card.md) - returns the cardinality of a bloom filter -* [`BF.EXISTS`](../commands/bf.exists.md) - checks if an item has been added to a bloom filter -* [`BF.INFO`](../commands/bf.info.md) - returns information about a bloom filter - -See the [complete list of bloom filter commands](../commands/#bloom). - -## Common use cases for bloom filters - -### Advertisement / Campaign placement and deduplication - -Bloom filters can help e-commerce sites, streaming services, advertising networks, or marketing platforms answer the following questions: - -* Has an advertisement already been shown to a user? -* Has a promotional email or notification already been sent to a user? -* Has a product already been purchased by a user? - -Example: For each user, use a Bloom filter to store all the products they have purchased. The recommendation engine can then suggest a new product and check if it is present in the user's Bloom filter. - -* If the product is not in the filter, the ad is shown to the user, and the product is added to the filter. -* If the product is already in the filter, it means the ad has already been shown to the user and the recommendation engine finds a different ad to show. - -### Fraud detection - -Bloom filters can be used to answer the question, "Has this card been flagged as stolen?". To do this, use a bloom filter that contains cards reported as stolen. When a card is used, check whether it is present in the bloom filter. If the card is not found, it means it is not marked as stolen. If the card is present in the filter, a check can be made against the main database, or the purchase can be denied. - -### Filtering Spam / Harmful Content -Bloom filters provide an efficient way to screen content for potential threats and harmful material. Here's how they can be effectively used: - -Example: Bloom filters can answer the question "is a URL malicious?". Any URL inputted would be checked against a malicious URL bloom filter. - -* If no, then we allow access to the site. -* If yes, then we can deny access or perform a full check of the URL. - -Example: Bloom filters can answer the question is this content harmful or spam. Create a bloom filter that contains spam email addresses or spam phone numbers. When an email or text is received then check if the number or email is present in the bloom filter. - -* If no, then the message can be displayed to the user. -* If yes, then we can send the message to the spam folder or perform a full check on the email or number. - -### Check if a username is taken - -Bloom filters can answer the question: Has this username/email/domain name/slug already been used? - -In this username example, we can use a Bloom filter to track every username that has signed up. When a new user attempts to sign up with their desired username, the app checks if the username exists in the Bloom filter. - -* If no, the user is created and the username is added to the Bloom filter. -* If yes, the app can decide to either check the main database or reject the username. - -## Tutorial - -**There are two ways to run valkey-bloom:** - - **Docker**: Follow the steps here for using the [valkey bundle](valkey-bundle.md) - - **Build from source**: Follow the [build instructions](https://github.com/valkey-io/valkey-bloom/blob/unstable/README.md#build-instructions) - - -### Usage example with CLI - -* Create a bloom filter to track the usernames which are taken with a 1 in 1000 chance of a false positive and 10000 as the initial capacity. -```bash -127.0.0.1:6379> BF.RESERVE usernames 0.001 10000 -OK -``` -* Add usernames which now have signed up to the bloom filters -```bash -# Add one user to the bloom filter -127.0.0.1:6379> BF.ADD usernames johnsmith -(integer) 1 - -# Add multiple users at once -127.0.0.1:6379> BF.MADD usernames JaneDoe valkeyFan bloomEnjoyer -1) (integer) 1 -2) (integer) 1 -3) (integer) 1 -``` - -* Check if usernames have been taken already -```bash -# Check if as single user has been added -127.0.0.1:6379> BF.EXISTS usernames johnsmith -(integer) 1 -127.0.0.1:6379> BF.EXISTS usernames fake_user -(integer) 0 - -# Check if multiple users are present in the bloomfilter at once -127.0.0.1:6379> BF.MEXISTS usernames johnsmith fake_user JaneDoe -1) (integer) 1 -2) (integer) 0 -3) (integer) 1 -``` - -* Check how many users have been added to the filter -```bash -127.0.0.1:6379> BF.CARD usernames -(integer) 4 -``` -* View your bloom filter object's usage: -```bash -127.0.0.1:6379> BF.INFO usernames - 1) Capacity - 2) (integer) 10000 - 3) Size - 4) (integer) 23912 - 5) Number of filters - 6) (integer) 1 - 7) Number of items inserted - 8) (integer) 4 - 9) Error rate -10) "0.001" -11) Expansion rate -12) (integer) 2 -13) Tightening ratio -14) "0.5" -15) Max scaled capacity -16) (integer) 26214300 -``` -* If you know the exact number of users who will sign up, or if want to limit the number of items regardless, you can create a non scaling bloom filter. This will create a filter that has capacity for only 1000 items with a 1 in 100,000 chance of a false positive. -```bash -127.0.0.1:6379> BF.RESERVE limited_users 0.00001 1000 NONSCALING -OK -``` -* If you anticipate that, once initial users have signed up, you will get a large increase in users after a while, you can set a custom expansion rate. -```bash -127.0.0.1:6379> BF.RESERVE expanding_users 0.001 10000 EXPANSION 4 -OK -``` - -## Scaling and non scaling bloom filters - -The bloom filter data type can act either as a "scaling bloom filter" or "non scaling bloom filter" depending on user configuration. - -The difference between scaling and non scaling bloom filters is that scaling bloom filters do not have a fixed capacity, instead they can grow. Non-scaling bloom filters will have a fixed capacity, meaning only a fixed number of items can be inserted to it. Scaling bloom filters consist of a vector of "Sub filters" with length >= 1, while non scaling will only contain 1 sub filter. - -When a scaling bloom filter reaches its capacity, adding a new unique item will trigger a scale out and a new sub filter is created and added to the vector of sub filters. This new sub filter will have a larger capacity (previous bloom filter's capacity * expansion rate of the bloom object). - -After a non scaling bloom filter reaches its capacity, if a user tries to add a new unique item, an error will be returned - -The expansion rate is the rate that a scaling bloom filter's capacity is increased by upon scale out. For example, we have a bloom filter with capacity 100 at creation with an expansion rate of 2. After adding 101 unique items, it will scale out and create a new sub filter with capacity 200. Then, after adding 200 more unique items (301 items total), a new sub filter of capacity 400 is added upon scale out and so on. - -### When should you use scaling vs non-scaling filters - -If the capacity (number of items we want to add) is known and fixed, using a non-scaling bloom filter is preferred. Likewise the reverse case, if the capacity is unknown / dynamically calculated, using a scaling bloom filters is ideal. - -There are a few benefits for using non scaling filters. A non scaling filter will have better performance than a filter that has scaled out several times (e.g. > 100). Also, non scaling filters in general use less memory for a scaling filter that has scaled out several times to hold the same capacity. - -However, to ensure you do not hit any capacity related errors, and want use-as-you-go capacity, scaling is better. - -## Bloom properties - -* Capacity - The number of unique items that would need to be added before a scale out occurs or (non scaling) before it rejects addition of unique items. - -* False Positive Rate (Error rate) - The rate that controls the probability of bloom check/set operations being false positives. Example: An item addition returning 0 (or an item check returning 1) indicating that the item was already added even though it was not. - -* Expansion - This is a property of scalable bloom filters which controls the growth in overall capacity when a bloom filter scales out by determining the capacity of the new sub filter which gets created. This new capacity is equal to the previous filters capacity * expansion rate - -### Advanced Properties - -The following two properties can be specified in the `BF.INSERT` command: - -* Seed - This is the key with which hash functions are created for the bloom filter. In case of scalable bloom filters, the same seed is used across all sub filters. This property is only useful if you have a specific 32 byte seed that you want your bloom filter to use. By default every bloom filter will use a random seed. - -* Tightening Ratio - This is a property of scalable bloom filters which controls the overall correctness of the bloom filter as it scales out by keeping the actual false positive rate closer to the user requested false positive rate when the bloom filter was created. This is done by using the tightening ratio to set a stricter false positive on the new sub filter which gets created during each scale out. We do not recommend fine tuning this unless there is a specific use case for lower memory usage with higher false positive or vice versa. - -### Default bloom properties - -These are the default bloom properties along with the commands and configs which allow customizing. - -| Property | Default Value | Command Name | Configuration name | -|----------|--------------|--------------|-------------------| -| Capacity | 100 | BF.INSERT, BF.RESERVE | BF.BLOOM-CAPACITY | -| False Positive Rate | 0.01 | BF.INSERT, BF.RESERVE | BF.BLOOM-FP-RATE | -| Scaling / Non Scaling | Scaling | BF.INSERT, BF.RESERVE | BF.BLOOM-EXPANSION | -| Expansion Rate | 2 | BF.INSERT, BF.RESERVE | BF.BLOOM-EXPANSION | -| Tightening Ratio | 0.5 | BF.INSERT | BF.BLOOM-TIGHTENING-RATIO | -| Seed | Random Seed | BF.INSERT | BF.BLOOM-USE-RANDOM-SEED | - - -Since bloom filters have a default expansion of 2, this means any default creation as a result of `BF.ADD`, `BF.MADD`, `BF.INSERT` will be a scalable bloom filter. Users can create a non scaling bloom filter using `BF.RESERVE NONSCALING` or by specifying `NONSCALING` in `BF.INSERT`. Additionally, the other default properties of a bloom filter creation can be seen in the table above and BF.INFO command response below. These default properties can be configured through configs on the bloom module. - -Example of default bloom filter information: - -```bash -127.0.0.1:6379> BF.ADD default_filter item -(integer) 1 -127.0.0.1:6379> BF.INFO default_filter - 1) Capacity - 2) (integer) 100 - 3) Size - 4) (integer) 384 - 5) Number of filters - 6) (integer) 1 - 7) Number of items inserted - 8) (integer) 2 - 9) Error rate -10) "0.01" -11) Expansion rate -12) (integer) 2 -13) Tightening ratio -14) "0.5" -15) Max scaled capacity -16) (integer) 26214300 -``` - -### When to adjust default configurations - -Adjusting the default configurations below can be used to update the behavior of the default bloom object created and are beneficial in different scenarios: - -- **Higher capacity (bf.bloom-capacity)**: Increase this value when you expect to store a larger number of items in all your new bloom filter objects. It increases the overall capacity for non scaling filters. For scaling filters, it increases the starting/initial capacity which potentially reduces the need for additional scaling operations which can improve performance. - -- **Lower false positive rate (bf.bloom-fp-rate)**: Decrease this value when correctness is critical for your application and you want to reduce the number of false positives in all your new bloom filter objects. For example, in fraud detection or security applications where false positives are costly. - -- **Higher expansion rate (bf.bloom-expansion)**: Increase this value when you want faster growth of bloom filters that will scale across all your new scaling bloom filter objects. This reduces the number of scaling operations but uses more memory quicker. - -- **Lower tightening ratio (bf.bloom-tightening-ratio)**: Lower this when you want to maintain a more consistent false positive rate across multiple scaling operations for all your new bloom filter objects. (Not advisable to change this default, as it is already set to a strict value of 0.5) - -- **Fixed seed (bf.bloom-use-random-seed)**: Set to false only when you want the new bloom filter object creations to use a fixed seed for deterministic occurrence of false positives during item add/exists operations. It can be used for testing or reproducibility. - -You can modify these default values using the CONFIG SET command. However, note that the effect of the configuration change is only applicable to the bloom objects created after the configuration change where the property is not specified through the command already. - -Example usage of changing all the different properties: -```bash -127.0.0.1:6379> CONFIG SET bf.bloom-fp-rate 0.001 -OK -127.0.0.1:6379> CONFIG SET bf.bloom-capacity 1000 -OK -127.0.0.1:6379> CONFIG SET bf.bloom-expansion 4 -OK -127.0.0.1:6379> CONFIG SET bf.bloom-tightening-ratio 0.6 -OK -127.0.0.1:6379> CONFIG SET bf.bloom-use-random-seed no -OK -``` - -### Memory usage limit - -The `bf.bloom-memory-usage-limit` configuration (default 128MB) controls the maximum memory that a single bloom filter can use: - -Example usage of increasing the limit: -```bash -127.0.0.1:6379> CONFIG SET bf.bloom-memory-usage-limit 268435456 -OK -``` - -Having a limit on the max memory per bloom object prevents them from growing unbounded, thus maintaining server performance during serialization. - -If your use case requires bloom filters with capacity beyond what this limit supports, you can increase this configuration value. However, be aware it can impact overall system performance and memory availability for other operations. - -When a bloom filter reaches this memory limit, any operation that would cause it to exceed the limit will fail with an error message indicating that the memory limit would be exceeded. - -Example of error returned: -```bash -127.0.0.1:6379> bf.add full_filter ne_item -1) (error) ERR operation exceeds bloom object memory limit -``` - -## Performance - -The bloom commands which involve adding items or checking the existence of items have a time complexity of O(N * K) where N is the number of hash functions used by the bloom filter and K is the number of elements being inserted. This means that both BF.ADD and BF.EXISTS are both O(N) as they only operate on one item. - -In case of scalable bloom filters, with every scale out, we increase the number of checks (using hash functions of each sub filter) performed during any add / exists operation. For this reason, it is recommended that users choose a capacity and expansion rate after evaluating the use case / workload to avoid several scale outs and reduce the number of checks. - -The other bloom filter commands are O(1) time complexity: BF.CARD, BF.INFO, BF.RESERVE, and BF.INSERT (when no items are provided). - -## Monitoring - -To check the server's overall bloom filter metrics, you can use the `INFO BF` or the `INFO MODULES` command. - -Example of `INFO BF` calls in different scenarios: - -```bash -127.0.0.1:6379> INFO BF -# bf_bloom_core_metrics -bf_bloom_total_memory_bytes:0 -bf_bloom_num_objects:0 -bf_bloom_num_filters_across_objects:0 -bf_bloom_num_items_across_objects:0 -bf_bloom_capacity_across_objects:0 - -# bf_bloom_defrag_metrics -bf_bloom_defrag_hits:0 -bf_bloom_defrag_misses:0 -127.0.0.1:6379> bf.add key value -(integer) 1 -127.0.0.1:6379> info bf -# bf_bloom_core_metrics -bf_bloom_total_memory_bytes:384 -bf_bloom_num_objects:1 -bf_bloom_num_filters_across_objects:1 -bf_bloom_num_items_across_objects:1 -bf_bloom_capacity_across_objects:100 - -# bf_bloom_defrag_metrics -bf_bloom_defrag_hits:0 -bf_bloom_defrag_misses:0 -``` - -### Bloom filter core metrics - -* `bf_bloom_total_memory_bytes`: Current total number of bytes used by all bloom filters. - -* `bf_bloom_num_objects`: Current total number of bloom filters. - -* `bf_bloom_num_filters_across_objects`: Current total number of sub filters across all bloom filters. - -* `bf_bloom_num_items_across_objects`: Current total number of items across all bloom filters. - -* `bf_bloom_capacity_across_objects`: Current total capacity across all bloom filters. - -### Bloom filter defrag metrics - -* `bf_bloom_defrag_hits`: Total number of defrag hits that have occurred on bloom filters. - -* `bf_bloom_defrag_misses`: Total number of defrag misses that have occurred on bloom filters. - -## Handling Large Bloom Filters - -There are two notable validations bloom filters faces. - -1. Memory Usage: - - The memory usage limit per bloom filter by default is defined by the `BF.BLOOM-MEMORY-USAGE-LIMIT` module configuration which has a default value of 128 MB. If a command results in a creation / scale out causing the overall memory usage to exceed this limit, the command is rejected. This config is modifiable and can be increased as needed. - -The `BF.INFO` command's `SIZE` field can be used to find out the current size of a bloom filter. - -```bash -127.0.0.1:6379> BF.INFO validate_scale_valid SIZE -(integer) 384 -``` - -2. Number of sub filters (in case of scalable bloom filters): - - When a bloom filter scales out, a new sub filter is added. The limit on the number of sub filters depends on the false positive rate and tightening ratio. Each sub filter has a stricter false positive, and this is controlled by the tightening ratio. If a command attempting a scale out results in the sub filter reaching a false positive of 0, the command is rejected. - - -You can use `VALIDATESCALETO` as an optional arg of `BF.INSERT` to help determine whether the bloom filter can scale out to the reach the specified capacity without hitting either limits mentioned above. It will reject the command otherwise. - -As seen below, when trying to create a bloom filter with a capacity that cannot be achieved through scale outs (given the memory limits), the command is rejected. However, if the capacity can be achieved through scale out (even with the limits), then the creation of the bloom filter will succeed. - -Example: - -```bash -127.0.0.1:6379> BF.INSERT validate_scale_fail VALIDATESCALETO 26214301 -(error) ERR provided VALIDATESCALETO causes bloom object to exceed memory limit -127.0.0.1:6379> BF.INSERT validate_scale_valid VALIDATESCALETO 26214300 -[] -``` - -The `BF.INFO` command's `MAXSCALEDCAPACITY` field can be used to find out the maximum capacity that the scalable bloom filter can expand to hold. - -```bash -127.0.0.1:6379> BF.INFO validate_scale_valid MAXSCALEDCAPACITY -(integer) 26214300 -``` diff --git a/topics/cli.md b/topics/cli.md deleted file mode 100644 index ee05abb8..00000000 --- a/topics/cli.md +++ /dev/null @@ -1,1123 +0,0 @@ ---- -title: "CLI" -description: > - Valkey command line interface ---- - -## Usage - -**`valkey-cli`** [_OPTIONS_] [_cmd_ [_arg_...]] - -## Description - -The Valkey command line interface is used for administration, troubleshooting and experimenting with Valkey. - -In interactive mode, `valkey-cli` has basic line editing capabilities to provide a familiar typing experience. - -To launch the program in special modes, you can use several options, including: - -* Simulate a replica and print the replication stream it receives from the primary. -* Check the latency of a Valkey server and display statistics. -* Request ASCII-art spectrogram of latency samples and frequencies. - -This topic covers the different aspects of `valkey-cli`, starting from the simplest and ending with the more advanced features. - -## Options - -**`-h`** _hostname_ -: Server hostname (default: `$VALKEYCLI_HOST` if set, otherwise 127.0.0.1). - -**`-p`** _port_ -: Server port (default: `$VALKEYCLI_PORT` if set, otherwise 6379). - -**`-t`** _timeout_ -: Server connection timeout in seconds (decimals allowed). - Default timeout is 0, meaning no limit, depending on the OS. - -**`-s`** _socket_ -: Server socket (overrides hostname and port). - -**`-a`** _password_ -: Password to use when connecting to the server. - You can also use the `VALKEYCLI_AUTH` environment - variable to pass this password more safely. - (If both are used, this argument takes precedence.) - -**`--user`** _username_ -: Used to send ACL style 'AUTH username pass'. Needs `-a`. - You can also use the `VALKEYCLI_USER` environment variable. - (If both are used, this argument takes precedence.) - -**`--pass`** _password_ -: Alias of -a for consistency with the new --user option. - -**`--askpass`** -: Force user to input password with mask from STDIN. - If this argument is used, `-a` and the `VALKEYCLI_AUTH` - environment variable will be ignored. - -**`-u`** _uri_ -: Server URI on format `valkey://user:password@host:port/dbnum`. - User, password and dbnum are optional. For authentication - without a username, use username 'default'. For TLS, use - the scheme 'valkeys'. - -**`-r`** _repeat_ -: Execute specified command N times. - -**`-i`** _interval_ -: When `-r` is used, waits _interval_ seconds per command. - It is possible to specify sub-second times like `-i 0.1`. - This interval is also used in `--scan` and `--stat` per cycle. - and in `--bigkeys`, `--memkeys`, and `--hotkeys` per 100 cycles. - -**`-n`** _db_ -: Database number. - -**`-2`** -: Start session in RESP2 protocol mode. - -**`-3`** -: Start session in RESP3 protocol mode. - -**`-x`** -: Read last argument from STDIN (see example below). - -**`-X`** -: Read argument from STDIN (see example below). - -**`-d`** _delimiter_ -: Delimiter between response bulks for raw formatting (default: `\n`). - -**`-D`** _delimiter_ -: Delimiter between responses for raw formatting (default: `\n`). - -**`-c`** -: Enable cluster mode (follow -ASK and -MOVED redirections). - -**`-e`** -: Return exit error code when command execution fails. - -**`-4`** -: Prefer IPv4 over IPv6 on DNS lookup. - -**`-6`** -: Prefer IPv6 over IPv4 on DNS lookup.' - -**`--tls`** -: Establish a secure TLS connection. - -**`--sni`** _host_ -: Server name indication for TLS. - -**`--cacert`** _file_ -: CA Certificate file to verify with. - -**`--cacertdir`** _dir_ -: Directory where trusted CA certificates are stored. - If neither cacert nor cacertdir are specified, the default - system-wide trusted root certs configuration will apply. - -**`--insecure`** -: Allow insecure TLS connection by skipping cert validation. - -**`--cert`** _file_ -: Client certificate to authenticate with. - -**`--key`** _file_ -: Private key file to authenticate with. - -**`--tls-ciphers`** _list_ -: Sets the list of preferred ciphers (TLSv1.2 and below) - in order of preference from highest to lowest separated by colon (":"). - See the **ciphers**(1ssl) manpage for more information about the syntax of this string. - -**`--tls-ciphersuites`** _list_ -: Sets the list of preferred ciphersuites (TLSv1.3) - in order of preference from highest to lowest separated by colon (":"). - See the **ciphers**(1ssl) manpage for more information about the syntax of this string, - and specifically for TLSv1.3 ciphersuites. - -**`--rdma`** -: Establish an RDMA connection. - -**`--mptcp`** -: Establish an MPTCP connection. - -**`--raw`** -: Use raw formatting for replies (default when STDOUT is - not a tty). - -**`--no-raw`** -: Force formatted output even when STDOUT is not a tty. - -**`--quoted-input`** -: Force input to be handled as quoted strings. - -**`--csv`** -: Output in CSV format. - -**`--json`** -: Output in JSON format (default RESP3, use -2 if you want to use with RESP2). - -**`--quoted-json`** -: Same as --json, but produce ASCII-safe quoted strings, not Unicode. - -**`--show-pushes`** **`yes`**|**`no`** -: Whether to print RESP3 PUSH messages. Enabled by default when - STDOUT is a tty but can be overridden with --show-pushes no. - -**`--stat`** -: Print rolling stats about server: mem, clients, ... - -**`--latency`** -: Enter a special mode continuously sampling latency. - If you use this mode in an interactive session it runs - forever displaying real-time stats. Otherwise if `--raw` or - `--csv` is specified, or if you redirect the output to a non - TTY, it samples the latency for 1 second (you can use - `-i` to change the interval), then produces a single output - and exits. - -**`--latency-history`** -: Like `--latency` but tracking latency changes over time. - Default time interval is 15 sec. Change it using `-i`. - -**`--latency-dist`** -: Shows latency as a spectrum, requires xterm 256 colors. - Default time interval is 1 sec. Change it using `-i`. - -**`--lru-test`** _keys_ -: Simulate a cache workload with an 80-20 distribution. - -**`--replica`** -: Simulate a replica showing commands received from the primary. - -**`--rdb`** _filename_ -: Transfer an RDB dump from remote server to local file. - Use filename of "-" to write to stdout. - -**`--functions-rdb`** _filename_ -: Like `--rdb` but only get the functions (not the keys) - when getting the RDB dump file. - -**`--pipe`** -: Transfer raw RESP protocol from stdin to server. - -**`--pipe-timeout`** _n_ -: In `--pipe` mode, abort with error if after sending all data. - no reply is received within _n_ seconds. - Default timeout: 30. Use 0 to wait forever. - -**`--bigkeys`** -: Sample keys looking for keys with many elements (complexity). - -**`--memkeys`** -: Sample keys looking for keys consuming a lot of memory. - -**`--memkeys-samples`** _n_ -: Sample keys looking for keys consuming a lot of memory. - And define number of key elements to sample - -**`--hotkeys`** -: Sample keys looking for hot keys. - Only works when maxmemory-policy is `*lfu`. - This is equivalent to --hotkeys-count 16. - This scans the keyspace from the client and reads each key's LFU counter, a - logarithmic and decaying approximation of access frequency. For server-side - tracking that needs no particular eviction policy and reports a rate over a - recent window, see [Hot key tracking](hotkeys.md). - -**`--hotkeys-count`** _n_ -: Sample keys looking for the n most hot keys. - Only works when maxmemory-policy is `*lfu`. - -**`--scan`** -: List all keys using the SCAN command. - -**`--pattern`** _pat_ -: Keys pattern when using the `--scan`, `--bigkeys` or `--hotkeys` - options (default: `*`). - -**`--count`** _count_ -: Count option when using the `--scan`, `--bigkeys` or `--hotkeys` (default: 10). - -**`--quoted-pattern`** _pat_ -: Same as `--pattern`, but the specified string can be - quoted, in order to pass an otherwise non binary-safe string. - -**`--intrinsic-latency`** _sec_ -: Run a test to measure intrinsic system latency. - The test will run for the specified amount of seconds. - -**`--eval`** _file_ -: Send an EVAL command using the Lua script at _file_. - -**`--ldb`** -: Used with `--eval` enable the Server Lua debugger. - -**`--ldb-sync-mode`** -: Like `--ldb` but uses the synchronous Lua debugger, in - this mode the server is blocked and script changes are - not rolled back from the server memory. - -**`--cluster`** _command_ [_args_...] [_opts_...] -: Cluster Manager command and arguments (see below). - -**`--verbose`** -: Verbose mode. - -**`--no-auth-warning`** -: Don't show warning message when using password on command - line interface. - -**`--help`** -: Output help and exit. - -**`--version`** -: Output version and exit. - -## Cluster Manager commands - -For management of [Valkey Cluster](cluster-tutorial.md), the following syntax is used: - -**`valkey-cli`** **`--cluster`** _command_ [_args_...] [_opts_...] - -``` - Command Args - -------------------------------------------------------------------------------- - create host1:port1 ... hostN:portN - --cluster-replicas - check or - separated by either colon or space - --cluster-search-multiple-owners - info or - separated by either colon or space - fix or - separated by either colon or space - --cluster-search-multiple-owners - --cluster-fix-with-unreachable-masters - reshard or - separated by either colon or space - --cluster-from - --cluster-to - --cluster-slots - --cluster-yes - --cluster-timeout - --cluster-pipeline - --cluster-replace - rebalance or - separated by either colon or space - --cluster-weight - --cluster-use-empty-masters - --cluster-timeout - --cluster-simulate - --cluster-pipeline - --cluster-threshold - --cluster-replace - add-node new_host:new_port existing_host:existing_port - --cluster-replica - --cluster-master-id - del-node host:port node_id - call host:port command arg arg .. arg - --cluster-only-masters - --cluster-only-replicas - set-timeout host:port milliseconds - import host:port - --cluster-from - --cluster-from-user - --cluster-from-pass - --cluster-from-askpass - --cluster-copy - --cluster-replace - backup host:port backup_directory - help -``` - -## Command line usage - -To run a Valkey command and return a standard output at the terminal, include the command to execute as separate arguments of `valkey-cli`: - - $ valkey-cli INCR mycounter - (integer) 7 - -The reply of the command is "7". Since Valkey replies are typed (strings, arrays, integers, nil, errors, etc.), you see the type of the reply between parentheses. This additional information may not be ideal when the output of `valkey-cli` must be used as input of another command or redirected into a file. - -`valkey-cli` only shows additional information for human readability when it detects the standard output is a tty, or terminal. For all other outputs it will auto-enable the *raw output mode*, as in the following example: - - $ valkey-cli INCR mycounter > /tmp/output.txt - $ cat /tmp/output.txt - 8 - -Note that `(integer)` is omitted from the output because `valkey-cli` detects -the output is no longer written to the terminal. You can force raw output -even on the terminal with the `--raw` option: - - $ valkey-cli --raw INCR mycounter - 9 - -You can force human readable output when writing to a file or in -pipe to other commands by using `--no-raw`. - -## String quoting and escaping - -When `valkey-cli` parses a command, whitespace characters automatically delimit the arguments. -In interactive mode, a newline sends the command for parsing and execution. -To input string values that contain whitespaces or non-printable characters, you can use quoted and escaped strings. - -Quoted string values are enclosed in double (`"`) or single (`'`) quotation marks. -Escape sequences are used to put nonprintable characters in character and string literals. - -An escape sequence contains a backslash (`\`) symbol followed by one of the escape sequence characters. - -Doubly-quoted strings support the following escape sequences: - -* `\"` - double-quote -* `\n` - newline -* `\r` - carriage return -* `\t` - horizontal tab -* `\b` - backspace -* `\a` - alert -* `\\` - backslash -* `\xhh` - any ASCII character represented by a hexadecimal number (_hh_) - -Single quotes assume the string is literal, and allow only the following escape sequences: -* `\'` - single quote -* `\\` - backslash - -For example, to return `Hello World` on two lines: - -``` -127.0.0.1:6379> SET mykey "Hello\nWorld" -OK -127.0.0.1:6379> GET mykey -Hello -World -``` - -When you input strings that contain single or double quotes, as you might in passwords, for example, escape the string, like so: - -``` -127.0.0.1:6379> AUTH some_admin_user ">^8T>6Na{u|jp>+v\"55\@_;OU(OR]7mbAYGqsfyu48(j'%hQH7;v*f1H${*gD(Se'" - ``` - -## Host, port, password, and database - -By default, `valkey-cli` connects to the server at the address 127.0.0.1 with port 6379. -You can change the port using several command line options. To specify a different host name or an IP address, use the `-h` option. In order to set a different port, use `-p`. - - $ valkey-cli -h valkey15.example.com -p 6390 PING - PONG - -If your instance is password protected, the `-a ` option will -perform authentication saving the need of explicitly using the `AUTH` command: - - $ valkey-cli -a myUnguessablePazzzzzword123 PING - PONG - -**NOTE:** For security reasons, provide the password to `valkey-cli` automatically via the -`VALKEYCLI_AUTH` environment variable. - -To authenticate as an [ACL user](acl.md), pass the username with `--user`, or set it in -the `VALKEYCLI_USER` environment variable (Valkey 9.2 and later). The username is only -sent together with a password, so also set one with `-a`, `--askpass`, or `VALKEYCLI_AUTH`: - - $ export VALKEYCLI_USER=alice - $ export VALKEYCLI_AUTH=password - $ valkey-cli PING - PONG - -Command line options take precedence over the environment variables. - -Finally, it's possible to send a command that operates on a database number -other than the default number zero by using the `-n ` option: - - $ valkey-cli FLUSHALL - OK - $ valkey-cli -n 1 INCR a - (integer) 1 - $ valkey-cli -n 1 INCR a - (integer) 2 - $ valkey-cli -n 2 INCR a - (integer) 1 - -Some or all of this information can also be provided by using the `-u ` -option and the URI pattern `valkey://user:password@host:port/dbnum`: - - $ valkey-cli -u valkey://LJenkins:p%40ssw0rd@valkey-16379.example.com:16379/0 PING - PONG - -**NOTE:** -User, password and dbnum are optional. -For authentication without a username, use username `default`. -For TLS, use the scheme `valkeys`. - -## SSL/TLS - -By default, `valkey-cli` uses a plain TCP connection to connect to Valkey. -You may enable SSL/TLS using the `--tls` option, along with `--cacert` or -`--cacertdir` to configure a trusted root certificate bundle or directory. - -If the target server requires authentication using a client side certificate, -you can specify a certificate and a corresponding private key using `--cert` and -`--key`. - -## Getting input from other programs - -There are two ways you can use `valkey-cli` in order to receive input from other -commands via the standard input. One is to use the target payload as the last argument -from *stdin*. For example, in order to set the Valkey key `net_services` -to the content of the file `/etc/services` from a local file system, use the `-x` -option: - - $ valkey-cli -x SET net_services < /etc/services - OK - $ valkey-cli GETRANGE net_services 0 50 - "#\n# Network services, Internet style\n#\n# Note that " - -In the first line of the above session, `valkey-cli` was executed with the `-x` option and a file was redirected to the CLI's -standard input as the value to satisfy the `SET net_services` command phrase. This is useful for scripting. - -A different approach is to feed `valkey-cli` a sequence of commands written in a -text file: - - $ cat /tmp/commands.txt - SET item:3374 100 - INCR item:3374 - APPEND item:3374 xxx - GET item:3374 - $ cat /tmp/commands.txt | valkey-cli - OK - (integer) 101 - (integer) 6 - "101xxx" - -All the commands in `commands.txt` are executed consecutively by -`valkey-cli` as if they were typed by the user in interactive mode. Strings can be -quoted inside the file if needed, so that it's possible to have single -arguments with spaces, newlines, or other special characters: - - $ cat /tmp/commands.txt - SET arg_example "This is a single argument" - STRLEN arg_example - $ cat /tmp/commands.txt | valkey-cli - OK - (integer) 25 - -## Continuously run the same command - -It is possible to execute a single command a specified number of times -with a user-selected pause between executions. This is useful in -different contexts - for example when we want to continuously monitor some -key content or `INFO` field output, or when we want to simulate some -recurring write event, such as pushing a new item into a list every 5 seconds. - -This feature is controlled by two options: `-r ` and `-i `. -The `-r` option states how many times to run a command and `-i` sets -the delay between the different command calls in seconds (with the ability -to specify values such as 0.1 to represent 100 milliseconds). - -By default the interval (or delay) is set to 0, so commands are just executed -ASAP: - - $ valkey-cli -r 5 INCR counter_value - (integer) 1 - (integer) 2 - (integer) 3 - (integer) 4 - (integer) 5 - -To run the same command indefinitely, use `-1` as the count value. -To monitor over time the RSS memory size it's possible to use the following command: - - $ valkey-cli -r -1 -i 1 INFO | grep rss_human - used_memory_rss_human:2.71M - used_memory_rss_human:2.73M - used_memory_rss_human:2.73M - used_memory_rss_human:2.73M - ... a new line will be printed each second ... - -## Mass insertion of data using `valkey-cli` - -Mass insertion using `valkey-cli` is covered in a separate page as it is a -worthwhile topic itself. Please refer to our [mass insertion guide](mass-insertion.md). - -## CSV output - -A CSV (Comma Separated Values) output feature exists within `valkey-cli` to export data from Valkey to an external program. - - $ valkey-cli LPUSH mylist a b c d - (integer) 4 - $ valkey-cli --csv LRANGE mylist 0 -1 - "d","c","b","a" - -Note that the `--csv` flag will only work on a single command, not the entirety of a DB as an export. - -## Running Lua scripts - -The `valkey-cli` has extensive support for using the debugging facility -of Lua scripting, available with Valkey 3.2 onwards. For this feature, refer to the [Valkey Lua debugger documentation](ldb.md). - -Even without using the debugger, `valkey-cli` can be used to -run scripts from a file as an argument: - - $ cat /tmp/script.lua - return server.call('SET',KEYS[1],ARGV[1]) - $ valkey-cli --eval /tmp/script.lua location:hastings:temp , 23 - OK - -The Valkey `EVAL` command takes the list of keys the script uses, and the -other non key arguments, as different arrays. When calling `EVAL` you -provide the number of keys as a number. - -When calling `valkey-cli` with the `--eval` option above, there is no need to specify the number of keys -explicitly. Instead it uses the convention of separating keys and arguments -with a comma. This is why in the above call you see `location:hastings:temp , 23` as arguments. - -So `location:hastings:temp` will populate the `KEYS` array, and `23` the `ARGV` array. - -The `--eval` option is useful when writing simple scripts. For more -complex work, the Lua debugger is recommended. It is possible to mix the two approaches, since the debugger can also execute scripts from an external file. - -Interactive mode -=== - -We have explored how to use the Valkey CLI as a command line program. -This is useful for scripts and certain types of testing, however most -people will spend the majority of time in `valkey-cli` using its interactive -mode. - -In interactive mode the user types Valkey commands at the prompt. The command -is sent to the server, processed, and the reply is parsed back and rendered -into a simpler form to read. - -Nothing special is needed for running the `valkey-cli` in interactive mode - -just execute it without any arguments - - $ valkey-cli - 127.0.0.1:6379> PING - PONG - -The string `127.0.0.1:6379>` is the prompt. It displays the connected Valkey server instance's hostname and port. - -The prompt updates as the connected server changes or when operating on a database different from the database number zero: - - 127.0.0.1:6379> SELECT 2 - OK - 127.0.0.1:6379[2]> DBSIZE - (integer) 1 - 127.0.0.1:6379[2]> SELECT 0 - OK - 127.0.0.1:6379> DBSIZE - (integer) 503 - -## Handling connections and reconnections - -Using the `CONNECT` command in interactive mode makes it possible to connect -to a different instance, by specifying the *hostname* and *port* we want -to connect to: - - 127.0.0.1:6379> CONNECT metal 6379 - metal:6379> PING - PONG - -As you can see the prompt changes accordingly when connecting to a different server instance. -If a connection is attempted to an instance that is unreachable, the `valkey-cli` goes into disconnected -mode and attempts to reconnect with each new command: - - 127.0.0.1:6379> CONNECT 127.0.0.1 9999 - Could not connect to Valkey at 127.0.0.1:9999: Connection refused - not connected> PING - Could not connect to Valkey at 127.0.0.1:9999: Connection refused - not connected> PING - Could not connect to Valkey at 127.0.0.1:9999: Connection refused - -Generally after a disconnection is detected, `valkey-cli` always attempts to -reconnect transparently; if the attempt fails, it shows the error and -enters the disconnected state. The following is an example of disconnection -and reconnection: - - 127.0.0.1:6379> INFO SERVER - Could not connect to Valkey at 127.0.0.1:6379: Connection refused - not connected> PING - PONG - 127.0.0.1:6379> - (now we are connected again) - -When a reconnection is performed, `valkey-cli` automatically re-selects the -last database number selected. However, all other states about the -connection is lost, such as within a MULTI/EXEC transaction: - - $ valkey-cli - 127.0.0.1:6379> MULTI - OK - 127.0.0.1:6379> PING - QUEUED - - ( here the server is manually restarted ) - - 127.0.0.1:6379> EXEC - (error) ERR EXEC without MULTI - -This is usually not an issue when using the `valkey-cli` in interactive mode for -testing, but this limitation should be known. - -## Editing, history, completion and hints - -Because `valkey-cli` uses the "linenoise" line editing library shipped with -Valkey, it has line editing capabilities without depending on `libreadline` or -other optional libraries. - -Command execution history can be accessed in order to avoid retyping commands by pressing the arrow keys (up and down). -The history is preserved between restarts of the CLI, in a file named -`.valkeycli_history` inside the user home directory, as specified -by the `HOME` environment variable. It is possible to use a different -history filename by setting the `REDISCLI_HISTFILE` environment variable, -and disable it by setting it to `/dev/null`. - -The `valkey-cli` is also able to perform command-name completion by pressing the TAB -key, as in the following example: - - 127.0.0.1:6379> Z - 127.0.0.1:6379> ZADD - 127.0.0.1:6379> ZCARD - -Once Valkey command name has been entered at the prompt, the `valkey-cli` will display -syntax hints. Like command history, this behavior can be turned on and off via the `valkey-cli` preferences. - -## Preferences - -There are two ways to customize `valkey-cli` behavior. The file `.valkeyclirc` -in the home directory is loaded by the CLI on startup. You can override the -file's default location by setting the `REDISCLI_RCFILE` environment variable to -an alternative path. Preferences can also be set during a CLI session, in which -case they will last only the duration of the session. - -To set preferences, use the special `:set` command. The following preferences -can be set, either by typing the command in the CLI or adding it to the -`.valkeyclirc` file: - -* `:set hints` - enables syntax hints -* `:set nohints` - disables syntax hints - -## Running the same command N times - -It is possible to run the same command multiple times in interactive mode by prefixing the command -name by a number: - - 127.0.0.1:6379> 5 INCR mycounter - (integer) 1 - (integer) 2 - (integer) 3 - (integer) 4 - (integer) 5 - -## Showing help about Valkey commands - -`valkey-cli` provides online help for most Valkey [commands](../commands/), using the `HELP` command. The command can be used -in two forms: - -* `HELP @` shows all the commands about a given category. The -categories are: - - `@generic` - - `@string` - - `@list` - - `@set` - - `@sorted_set` - - `@hash` - - `@pubsub` - - `@transactions` - - `@connection` - - `@server` - - `@scripting` - - `@hyperloglog` - - `@cluster` - - `@geo` - - `@stream` -* `HELP ` shows specific help for the command given as argument. - -For example in order to show help for the `PFADD` command, use: - - 127.0.0.1:6379> HELP PFADD - - PFADD key element [element ...] - summary: Adds the specified elements to the specified HyperLogLog. - since: 2.8.9 - -Note that `HELP` supports TAB completion as well. - -## Clearing the terminal screen - -Using the `CLEAR` command in interactive mode clears the terminal's screen. - -Special modes of operation -=== - -So far we saw two main modes of `valkey-cli`. - -* Command line execution of Valkey commands. -* Interactive "REPL" usage. - -The CLI performs other auxiliary tasks related to Valkey that -are explained in the next sections: - -* Monitoring tool to show continuous stats about a Valkey server. -* Scanning a Valkey database for very large keys. -* Key space scanner with pattern matching. -* Acting as a [Pub/Sub](pubsub.md) client to subscribe to channels. -* Monitoring the commands executed into a Valkey instance. -* Checking the [latency](latency.md) of a Valkey server in different ways. -* Checking the scheduler latency of the local computer. -* Transferring RDB backups from a remote Valkey server locally. -* Acting as a Valkey replica for showing what a replica receives. -* Simulating [LRU](lru-cache.md) workloads for showing stats about keys hits. -* A client for the Lua debugger. - -## Continuous stats mode - -Continuous stats mode is probably one of the lesser known yet very useful features of `valkey-cli` to monitor Valkey instances in real time. To enable this mode, the `--stat` option is used. -The output is very clear about the behavior of the CLI in this mode: - - $ valkey-cli --stat - ------- data ------ --------------------- load -------------------- - child - - keys mem clients blocked requests connections - 506 1015.00K 1 0 24 (+0) 7 - 506 1015.00K 1 0 25 (+1) 7 - 506 3.40M 51 0 60461 (+60436) 57 - 506 3.40M 51 0 146425 (+85964) 107 - 507 3.40M 51 0 233844 (+87419) 157 - 507 3.40M 51 0 321715 (+87871) 207 - 508 3.40M 51 0 408642 (+86927) 257 - 508 3.40M 51 0 497038 (+88396) 257 - -In this mode a new line is printed every second with useful information and differences of request values between old data points. Memory usage, client connection counts, and various other statistics about the connected Valkey database can be easily understood with this auxiliary `valkey-cli` tool. - -The `-i ` option in this case works as a modifier in order to -change the frequency at which new lines are emitted. The default is one -second. - -## Scanning for big keys - -In this special mode, `valkey-cli` works as a key space analyzer. It scans the -dataset for big keys, but also provides information about the data types -that the data set consists of. This mode is enabled with the `--bigkeys` option, -and produces verbose output: - - $ valkey-cli --bigkeys - - # Scanning the entire keyspace to find biggest keys as well as - # average sizes per key type. You can use -i 0.01 to sleep 0.01 sec - # per SCAN command (not usually needed). - - [00.00%] Biggest string found so far 'key-419' with 3 bytes - [05.14%] Biggest list found so far 'mylist' with 100004 items - [35.77%] Biggest string found so far 'counter:__rand_int__' with 6 bytes - [73.91%] Biggest hash found so far 'myobject' with 3 fields - - -------- summary ------- - - Sampled 506 keys in the keyspace! - Total key length in bytes is 3452 (avg len 6.82) - - Biggest string found 'counter:__rand_int__' has 6 bytes - Biggest list found 'mylist' has 100004 items - Biggest hash found 'myobject' has 3 fields - - 504 strings with 1403 bytes (99.60% of keys, avg size 2.78) - 1 lists with 100004 items (00.20% of keys, avg size 100004.00) - 0 sets with 0 members (00.00% of keys, avg size 0.00) - 1 hashs with 3 fields (00.20% of keys, avg size 3.00) - 0 zsets with 0 members (00.00% of keys, avg size 0.00) - -In the first part of the output, each new key larger than the previous larger -key (of the same type) encountered is reported. The summary section -provides general stats about the data inside the Valkey instance. - -The program uses the `SCAN` command, so it can be executed against a busy -server without impacting the operations, however the `-i` option can be -used in order to throttle the scanning process of the specified fraction -of second for each `SCAN` command. - -For example, `-i 0.01` will slow down the program execution considerably, but will also reduce the load on the server -to a negligible amount. - -Note that the summary also reports in a cleaner form the biggest keys found -for each time. The initial output is just to provide some interesting info -ASAP if running against a very large data set. - -## Getting a list of keys - -It is also possible to scan the key space, again in a way that does not -block the Valkey server (which does happen when you use a command -like `KEYS *`), and print all the key names, or filter them for specific -patterns. This mode, like the `--bigkeys` option, uses the `SCAN` command, -so keys may be reported multiple times if the dataset is changing, but no -key would ever be missing, if that key was present since the start of the -iteration. Because of the command that it uses this option is called `--scan`. - - $ valkey-cli --scan | head -10 - key-419 - key-71 - key-236 - key-50 - key-38 - key-458 - key-453 - key-499 - key-446 - key-371 - -Note that `head -10` is used in order to print only the first ten lines of the -output. - -Scanning is able to use the underlying pattern matching capability of -the `SCAN` command with the `--pattern` option. - - $ valkey-cli --scan --pattern '*-11*' - key-114 - key-117 - key-118 - key-113 - key-115 - key-112 - key-119 - key-11 - key-111 - key-110 - key-116 - -Piping the output through the `wc` command can be used to count specific -kind of objects, by key name: - - $ valkey-cli --scan --pattern 'user:*' | wc -l - 3829433 - -You can use `-i 0.01` to add a delay between calls to the `SCAN` command. -This will make the command slower but will significantly reduce load on the server. - -## Pub/sub mode - -The CLI is able to publish messages in Valkey Pub/Sub channels using -the `PUBLISH` command. Subscribing to channels in order to receive -messages is different - the terminal is blocked and waits for -messages, so this is implemented as a special mode in `valkey-cli`. Unlike -other special modes this mode is not enabled by using a special option, -but simply by using the `SUBSCRIBE` or `PSUBSCRIBE` command, which are available in -interactive or command mode: - - $ valkey-cli PSUBSCRIBE '*' - Reading messages... (press Ctrl-C to quit) - 1) "PSUBSCRIBE" - 2) "*" - 3) (integer) 1 - -The *reading messages* message shows that we entered Pub/Sub mode. -When another client publishes some message in some channel, such as with the command `valkey-cli PUBLISH mychannel mymessage`, the CLI in Pub/Sub mode will show something such as: - - 1) "pmessage" - 2) "*" - 3) "mychannel" - 4) "mymessage" - -This is very useful for debugging Pub/Sub issues. -To exit the Pub/Sub mode just process `CTRL-C`. - -## Monitoring commands executed in Valkey - -Similarly to the Pub/Sub mode, the monitoring mode is entered automatically -once you use the `MONITOR` command. All commands received by the active Valkey instance will be printed to the standard output: - - $ valkey-cli MONITOR - OK - 1460100081.165665 [0 127.0.0.1:51706] "set" "shipment:8000736522714:status" "sorting" - 1460100083.053365 [0 127.0.0.1:51707] "get" "shipment:8000736522714:status" - -Note that it is possible to pipe the output, so you can monitor -for specific patterns using tools such as `grep`. - -## Monitoring the latency of Valkey instances - -Valkey is often used in contexts where latency is very critical. Latency -involves multiple moving parts within the application, from the client library -to the network stack, to the Valkey instance itself. - -The `valkey-cli` has multiple facilities for studying the latency of a Valkey -instance and understanding the latency's maximum, average and distribution. - -The basic latency-checking tool is the `--latency` option. Using this -option the CLI runs a loop where the `PING` command is sent to the Valkey -instance and the time to receive a reply is measured. This happens 100 -times per second, and stats are updated in a real time in the console: - - $ valkey-cli --latency - min: 0, max: 1, avg: 0.19 (427 samples) - -The stats are provided in milliseconds. Usually, the average latency of -a very fast instance tends to be overestimated a bit because of the -latency due to the kernel scheduler of the system running `valkey-cli` -itself, so the average latency of 0.19 above may easily be 0.01 or less. -However this is usually not a big problem, since most developers are interested in -events of a few milliseconds or more. - -Sometimes it is useful to study how the maximum and average latencies -evolve during time. The `--latency-history` option is used for that -purpose: it works exactly like `--latency`, but every 15 seconds (by -default) a new sampling session is started from scratch: - - $ valkey-cli --latency-history - min: 0, max: 1, avg: 0.14 (1314 samples) -- 15.01 seconds range - min: 0, max: 1, avg: 0.18 (1299 samples) -- 15.00 seconds range - min: 0, max: 1, avg: 0.20 (113 samples)^C - -Sampling sessions' length can be changed with the `-i ` option. - -The most advanced latency study tool, but also the most complex to -interpret for non-experienced users, is the ability to use color terminals -to show a spectrum of latencies. You'll see a colored output that indicates the -different percentages of samples, and different ASCII characters that indicate -different latency figures. This mode is enabled using the `--latency-dist` -option: - - $ valkey-cli --latency-dist - (output not displayed, requires a color terminal, try it!) - -There is another pretty unusual latency tool implemented inside `valkey-cli`. -It does not check the latency of a Valkey instance, but the latency of the -computer running `valkey-cli`. This latency is intrinsic to the kernel scheduler, -the hypervisor in case of virtualized instances, and so forth. - -Valkey calls it *intrinsic latency* because it's mostly opaque to the programmer. -If the Valkey instance has high latency regardless of all the obvious things -that may be the source cause, it's worth to check what's the best your system -can do by running `valkey-cli` in this special mode directly in the system you -are running Valkey servers on. - -By measuring the intrinsic latency, you know that this is the baseline, -and Valkey cannot outdo your system. In order to run the CLI -in this mode, use the `--intrinsic-latency `. Note that the test time is in seconds and dictates how long the test should run. - - $ ./valkey-cli --intrinsic-latency 5 - Max latency so far: 1 microseconds. - Max latency so far: 7 microseconds. - Max latency so far: 9 microseconds. - Max latency so far: 11 microseconds. - Max latency so far: 13 microseconds. - Max latency so far: 15 microseconds. - Max latency so far: 34 microseconds. - Max latency so far: 82 microseconds. - Max latency so far: 586 microseconds. - Max latency so far: 739 microseconds. - - 65433042 total runs (avg latency: 0.0764 microseconds / 764.14 nanoseconds per run). - Worst run took 9671x longer than the average latency. - -IMPORTANT: this command must be executed on the computer that runs the Valkey server instance, not on a different host. It does not connect to a Valkey instance and performs the test locally. - -In the above case, the system cannot do better than 739 microseconds of worst -case latency, so one can expect certain queries to occasionally run less than 1 millisecond. - -## Remote backups of RDB files - -During a Valkey replication's first synchronization, the primary and the replica -exchange the whole data set in the form of an RDB file. This feature is exploited -by `valkey-cli` in order to provide a remote backup facility that allows a -transfer of an RDB file from any Valkey instance to the local computer running -`valkey-cli`. To use this mode, call the CLI with the `--rdb ` -option: - - $ valkey-cli --rdb /tmp/dump.rdb - SYNC sent to master, writing 13256 bytes to '/tmp/dump.rdb' - Transfer finished with success. - -This is a simple but effective way to ensure disaster recovery -RDB backups exist of your Valkey instance. When using this options in -scripts or `cron` jobs, make sure to check the return value of the command. -If it is non zero, an error occurred as in the following example: - - $ valkey-cli --rdb /tmp/dump.rdb - SYNC with master failed: -ERR Can't SYNC while not connected with my master - $ echo $? - 1 - -## Replica mode - -The replica mode of the CLI is an advanced feature useful for -Valkey developers and for debugging operations. -It allows for the inspection of the content a primary sends to its replicas in the replication -stream in order to propagate the writes to its replicas. The option -name is simply `--replica`. The following is a working example: - - $ valkey-cli --replica - SYNC with master, discarding 13256 bytes of bulk transfer... - SYNC done. Logging commands from master. - "PING" - "SELECT","0" - "SET","last_name","Enigk" - "PING" - "INCR","mycounter" - -The command begins by discarding the RDB file of the first synchronization -and then logs each command received in CSV format. - -If you think some of the commands are not replicated correctly in your replicas -this is a good way to check what's happening, and also useful information -in order to improve the bug report. - -## Performing an LRU simulation - -Valkey is often used as a cache with [LRU eviction](lru-cache.md). -Depending on the number of keys and the amount of memory allocated for the -cache (specified via the `maxmemory` directive), the amount of cache hits -and misses will change. Sometimes, simulating the rate of hits is very -useful to correctly provision your cache. - -The `valkey-cli` has a special mode where it performs a simulation of GET and SET -operations, using an 80-20% power law distribution in the requests pattern. -This means that 20% of keys will be requested 80% of times, which is a -common distribution in caching scenarios. - -Theoretically, given the distribution of the requests and the Valkey memory -overhead, it should be possible to compute the hit rate analytically -with a mathematical formula. However, Valkey can be configured with -different LRU settings (number of samples) and LRU's implementation, which -is approximated in Valkey, changes a lot between different versions. Similarly -the amount of memory per key may change between versions. That is why this -tool was built: its main motivation was for testing the quality of Valkey' LRU -implementation, but now is also useful for testing how a given version -behaves with the settings originally intended for deployment. - -To use this mode, specify the amount of keys in the test and configure a sensible `maxmemory` setting as a first attempt. - -IMPORTANT NOTE: Configuring the `maxmemory` setting in the Valkey configuration -is crucial: if there is no cap to the maximum memory usage, the hit will -eventually be 100% since all the keys can be stored in memory. If too many keys are specified with maximum memory, eventually all of the computer RAM will be used. It is also needed to configure an appropriate -*maxmemory policy*; most of the time `allkeys-lru` is selected. - -In the following example there is a configured a memory limit of 100MB and an LRU -simulation using 10 million keys. - -WARNING: the test uses pipelining and will stress the server, don't use it -with production instances. - - $ ./valkey-cli --lru-test 10000000 - 156000 Gets/sec | Hits: 4552 (2.92%) | Misses: 151448 (97.08%) - 153750 Gets/sec | Hits: 12906 (8.39%) | Misses: 140844 (91.61%) - 159250 Gets/sec | Hits: 21811 (13.70%) | Misses: 137439 (86.30%) - 151000 Gets/sec | Hits: 27615 (18.29%) | Misses: 123385 (81.71%) - 145000 Gets/sec | Hits: 32791 (22.61%) | Misses: 112209 (77.39%) - 157750 Gets/sec | Hits: 42178 (26.74%) | Misses: 115572 (73.26%) - 154500 Gets/sec | Hits: 47418 (30.69%) | Misses: 107082 (69.31%) - 151250 Gets/sec | Hits: 51636 (34.14%) | Misses: 99614 (65.86%) - -The program shows stats every second. In the first seconds the cache starts to be populated. The misses rate later stabilizes into the actual figure that can be expected: - - 120750 Gets/sec | Hits: 48774 (40.39%) | Misses: 71976 (59.61%) - 122500 Gets/sec | Hits: 49052 (40.04%) | Misses: 73448 (59.96%) - 127000 Gets/sec | Hits: 50870 (40.06%) | Misses: 76130 (59.94%) - 124250 Gets/sec | Hits: 50147 (40.36%) | Misses: 74103 (59.64%) - -A miss rate of 59% may not be acceptable for certain use cases therefor -100MB of memory is not enough. Observe an example using a half gigabyte of memory. After several -minutes the output stabilizes to the following figures: - - 140000 Gets/sec | Hits: 135376 (96.70%) | Misses: 4624 (3.30%) - 141250 Gets/sec | Hits: 136523 (96.65%) | Misses: 4727 (3.35%) - 140250 Gets/sec | Hits: 135457 (96.58%) | Misses: 4793 (3.42%) - 140500 Gets/sec | Hits: 135947 (96.76%) | Misses: 4553 (3.24%) - -With 500MB there is sufficient space for the key quantity (10 million) and distribution (80-20 style). diff --git a/topics/client-side-caching.md b/topics/client-side-caching.md deleted file mode 100644 index 177e0154..00000000 --- a/topics/client-side-caching.md +++ /dev/null @@ -1,331 +0,0 @@ ---- -title: "Client-side caching" -description: > - Server-assisted, client-side caching in Valkey ---- - -Client-side caching is a technique used to create high performance services. -It exploits the memory available on application servers, servers that are -usually distinct computers compared to the Valkey nodes, to store some subset -of the Valkey information directly in the application side. - -Normally when data is required, the application servers ask the Valkey about -such information, like in the following diagram: - - - +-------------+ +----------+ - | | ------- GET user:1234 -------> | | - | Application | | Valkey | - | | <---- username = Alice ------- | | - +-------------+ +----------+ - -When client-side caching is used, the application will store the reply of -popular queries directly inside the application memory, so that it can -reuse such replies later, without contacting the Valkey again: - - +-------------+ +----------+ - | | | | - | Application | ( No chat needed ) | Valkey | - | | | | - +-------------+ +----------+ - | Local cache | - | | - | user:1234 = | - | username | - | Alice | - +-------------+ - -While the application memory used for the local cache may not be very big, -the time needed in order to access the local computer memory is orders of -magnitude smaller compared to accessing a networked service like a Valkey. -Since often the same small percentage of data are accessed frequently, -this pattern can greatly reduce the latency for the application to get data -and, at the same time, the load in the Valkey side. - -Moreover there are many datasets where items change very infrequently. -For instance, most user posts in a social network are either immutable or -rarely edited by the user. Adding to this the fact that usually a small -percentage of the posts are very popular, either because a small set of users -have a lot of followers and/or because recent posts have a lot more -visibility, it is clear why such a pattern can be very useful. - -Usually the two key advantages of client-side caching are: - -1. Data is available with a very small latency. -2. The Valkey system receives less queries, allowing it to serve the same dataset with a smaller number of nodes. - -## There are two hard problems in computer science... - -A problem with the above pattern is how to invalidate the information that -the application is holding, in order to avoid presenting stale data to the -user. For example after the application above locally cached the information -for user:1234, Alice may update her username to Flora. Yet the application -may continue to serve the old username for user:1234. - -Sometimes, depending on the exact application we are modeling, this isn't a -big deal, so the client will just use a fixed maximum "time to live" for the -cached information. Once a given amount of time has elapsed, the information -will no longer be considered valid. More complex patterns, when using Valkey, -leverage the Pub/Sub system in order to send invalidation messages to -listening clients. This can be made to work but is tricky and costly from -the point of view of the bandwidth used, because often such patterns involve -sending the invalidation messages to every client in the application, even -if certain clients may not have any copy of the invalidated data. Moreover -every application query altering the data requires to use the `PUBLISH` -command, costing the Valkey more CPU time to process this command. - -Regardless of what schema is used, there is a simple fact: many very large -applications implement some form of client-side caching, because it is the -next logical step to having a fast store or a fast cache server. For this -reason Valkey implements direct support for client-side caching, in order -to make this pattern much simpler to implement, more accessible, reliable, -and efficient. - -## The Valkey implementation of client-side caching - -The Valkey client-side caching support is called _Tracking_, and has two modes: - -* In the default mode, the server remembers what keys a given client accessed, and sends invalidation messages when the same keys are modified. This costs memory in the server side, but sends invalidation messages only for the set of keys that the client might have in memory. -* In the _broadcasting_ mode, the server does not attempt to remember what keys a given client accessed, so this mode costs no memory at all in the server side. Instead clients subscribe to key prefixes such as `object:` or `user:`, and receive a notification message every time a key matching a subscribed prefix is touched. - -To recap, for now let's forget for a moment about the broadcasting mode, to -focus on the first mode. We'll describe broadcasting in more detail later. - -1. Clients can enable tracking if they want. Connections start without tracking enabled. -2. When tracking is enabled, the server remembers what keys each client requested during the connection lifetime (by sending read commands about such keys). -3. When a key is modified by some client, or is evicted because it has an associated expire time, or evicted because of a _maxmemory_ policy, all the clients with tracking enabled that may have the key cached, are notified with an _invalidation message_. -4. When clients receive invalidation messages, they are required to remove the corresponding keys, in order to avoid serving stale data. - -This is an example of the protocol: - -* Client 1 `->` Server: CLIENT TRACKING ON -* Client 1 `->` Server: GET foo -* (The server remembers that Client 1 may have the key "foo" cached) -* (Client 1 may remember the value of "foo" inside its local memory) -* Client 2 `->` Server: SET foo SomeOtherValue -* Server `->` Client 1: INVALIDATE "foo" - -This looks great superficially, but if you imagine 10k connected clients all -asking for millions of keys over long living connection, the server ends up -storing too much information. For this reason Valkey uses two key ideas in -order to limit the amount of memory used server-side and the CPU cost of -handling the data structures implementing the feature: - -* The server remembers the list of clients that may have cached a given key in a single global table. This table is called the **Invalidation Table**. The invalidation table can contain a maximum number of entries. If a new key is inserted, the server may evict an older entry by pretending that such key was modified (even if it was not), and sending an invalidation message to the clients. Doing so, it can reclaim the memory used for this key, even if this will force the clients having a local copy of the key to evict it. -* Inside the invalidation table we don't really need to store pointers to clients' structures, that would force a garbage collection procedure when the client disconnects: instead what we do is just store client IDs (each Valkey client has a unique numerical ID). If a client disconnects, the information will be incrementally garbage collected as caching slots are invalidated. -* There is a single keys namespace, not divided by Valkey numbers. So if a client is caching the key `foo` in Valkey 2, and some other client changes the value of the key `foo` in Valkey 3, an invalidation message will still be sent. This way we can ignore Valkey numbers reducing both the memory usage and the implementation complexity. - -## Two connections mode - -Using the new version of the Valkey protocol, RESP3, it is possible to run the data queries and receive the invalidation messages in the same connection. However many client implementations may prefer to implement client-side caching using two separated connections: one for data, and one for invalidation messages. For this reason when a client enables tracking, it can specify to redirect the invalidation messages to another connection by specifying the "client ID" of a different connection. Many data connections can redirect invalidation messages to the same connection, this is useful for clients implementing connection pooling. The two connections model is the only one that is also supported for RESP2 (which lacks the ability to multiplex different kind of information in the same connection). - -Here's an example of a complete session using the Valkey protocol in the old RESP2 mode involving the following steps: enabling tracking redirecting to another connection, asking for a key, and getting an invalidation message once the key gets modified. - -To start, the client opens a first connection that will be used for invalidations, requests the connection ID, and subscribes via Pub/Sub to the special channel that is used to get invalidation messages when in RESP2 modes (remember that RESP2 is the usual Valkey protocol, and not the more advanced protocol that you can use, optionally, using the `HELLO` command): - -``` -(Connection 1 -- used for invalidations) -CLIENT ID -:4 -SUBSCRIBE __redis__:invalidate -*3 -$9 -subscribe -$20 -__redis__:invalidate -:1 -``` - -Now we can enable tracking from the data connection: - -``` -(Connection 2 -- data connection) -CLIENT TRACKING on REDIRECT 4 -+OK - -GET foo -$3 -bar -``` - -The client may decide to cache `"foo" => "bar"` in the local memory. - -A different client will now modify the value of the "foo" key: - -``` -(Some other unrelated connection) -SET foo bar -+OK -``` - -As a result, the invalidations connection will receive a message that invalidates the specified key. - -``` -(Connection 1 -- used for invalidations) -*3 -$7 -message -$20 -__redis__:invalidate -*1 -$3 -foo -``` -The client will check if there are cached keys in this caching slot, and will evict the information that is no longer valid. - -Note that the third element of the Pub/Sub message is not a single key but -is a Valkey array with just a single element. Since we send an array, if there -are groups of keys to invalidate, we can do that in a single message. -In case of a flush (`FLUSHALL` or `FLUSHDB`), a `null` message will be sent. - -A very important thing to understand about client-side caching used with -RESP2 and a Pub/Sub connection in order to read the invalidation messages, -is that using Pub/Sub is entirely a trick **in order to reuse old client -implementations**, but actually the message is not really sent to a channel -and received by all the clients subscribed to it. Only the connection we -specified in the `REDIRECT` argument of the `CLIENT` command will actually -receive the Pub/Sub message, making the feature a lot more scalable. - -When RESP3 is used instead, invalidation messages are sent (either in the -same connection, or in the secondary connection when redirection is used) -as `push` messages (read the RESP3 specification for more information). - -## What tracking tracks - -As you can see clients do not need, by default, to tell the server what keys -they are caching. Every key that is mentioned in the context of a read-only -command is tracked by the server, because it *could be cached*. - -This has the obvious advantage of not requiring the client to tell the server -what it is caching. Moreover in many clients implementations, this is what -you want, because a good solution could be to just cache everything that is not -already cached, using a first-in first-out approach: we may want to cache a -fixed number of objects, every new data we retrieve, we could cache it, -discarding the oldest cached object. More advanced implementations may instead -drop the least used object or alike. - -Note that anyway if there is write traffic on the server, caching slots -will get invalidated during the course of the time. In general when the -server assumes that what we get we also cache, we are making a tradeoff: - -1. It is more efficient when the client tends to cache many things with a policy that welcomes new objects. -2. The server will be forced to retain more data about the client keys. -3. The client will receive useless invalidation messages about objects it did not cache. - -So there is an alternative described in the next section. - -## Opt-in caching - -Clients implementations may want to cache only selected keys, and communicate -explicitly to the server what they'll cache and what they will not. This will -require more bandwidth when caching new objects, but at the same time reduces -the amount of data that the server has to remember and the amount of -invalidation messages received by the client. - -In order to do this, tracking must be enabled using the OPTIN option: - - CLIENT TRACKING on REDIRECT 1234 OPTIN - -In this mode, by default, keys mentioned in read queries *are not supposed to be cached*, instead when a client wants to cache something, it must send a special command immediately before the actual command to retrieve the data: - - CLIENT CACHING YES - +OK - GET foo - "bar" - -The `CACHING` command affects the command executed immediately after it, -however in case the next command is `MULTI`, all the commands in the -transaction will be tracked. Similarly in case of Lua scripts, all the -commands executed by the script will be tracked. - -## Broadcasting mode - -So far we described the first client-side caching model that Valkey implements. -There is another one, called broadcasting, that sees the problem from the -point of view of a different tradeoff, does not consume any memory on the -server side, but instead sends more invalidation messages to clients. -In this mode we have the following main behaviors: - -* Clients enable client-side caching using the `BCAST` option, specifying one or more prefixes using the `PREFIX` option. For instance: `CLIENT TRACKING on REDIRECT 10 BCAST PREFIX object: PREFIX user:`. If no prefix is specified at all, the prefix is assumed to be the empty string, so the client will receive invalidation messages for every key that gets modified. Instead if one or more prefixes are used, only keys matching one of the specified prefixes will be sent in the invalidation messages. -* The server does not store anything in the invalidation table. Instead it uses a different **Prefixes Table**, where each prefix is associated to a list of clients. -* No two prefixes can track overlapping parts of the keyspace. For instance, having the prefix "foo" and "foob" would not be allowed, since they would both trigger an invalidation for the key "foobar". However, just using the prefix "foo" is sufficient. -* Every time a key matching any of the prefixes is modified, all the clients subscribed to that prefix, will receive the invalidation message. -* The server will consume CPU proportional to the number of registered prefixes. If you have just a few, it is hard to see any difference. With a big number of prefixes the CPU cost can become quite large. -* In this mode the server can perform the optimization of creating a single reply for all the clients subscribed to a given prefix, and send the same reply to all. This helps to lower the CPU usage. - -## The NOLOOP option - -By default client-side tracking will send invalidation messages to the -client that modified the key. Sometimes clients want this, since they -implement very basic logic that does not involve automatically caching -writes locally. However, more advanced clients may want to cache even the -writes they are doing in the local in-memory table. In such case receiving -an invalidation message immediately after the write is a problem, since it -will force the client to evict the value it just cached. - -In this case it is possible to use the `NOLOOP` option: it works both -in normal and broadcasting mode. Using this option, clients are able to -tell the server they don't want to receive invalidation messages for keys -that they modified. - -## Avoiding race conditions - -When implementing client-side caching redirecting the invalidation messages -to a different connection, you should be aware that there is a possible -race condition. See the following example interaction, where we'll call -the data connection "D" and the invalidation connection "I": - - [D] client -> server: GET foo - [I] server -> client: Invalidate foo (somebody else touched it) - [D] server -> client: "bar" (the reply of "GET foo") - -As you can see, because the reply to the GET was slower to reach the -client, we received the invalidation message before the actual data that -is already no longer valid. So we'll keep serving a stale version of the -foo key. To avoid this problem, it is a good idea to populate the cache -when we send the command with a placeholder: - - Client cache: set the local copy of "foo" to "caching-in-progress" - [D] client-> server: GET foo. - [I] server -> client: Invalidate foo (somebody else touched it) - Client cache: delete "foo" from the local cache. - [D] server -> client: "bar" (the reply of "GET foo") - Client cache: don't set "bar" since the entry for "foo" is missing. - -Such a race condition is not possible when using a single connection for both -data and invalidation messages, since the order of the messages is always known -in that case. - -## What to do when losing connection with the server - -Similarly, if we lost the connection with the socket we use in order to -get the invalidation messages, we may end with stale data. In order to avoid -this problem, we need to do the following things: - -1. Make sure that if the connection is lost, the local cache is flushed. -2. Both when using RESP2 with Pub/Sub, or RESP3, ping the invalidation channel periodically (you can send PING commands even when the connection is in Pub/Sub mode!). If the connection looks broken and we are not able to receive ping backs, after a maximum amount of time, close the connection and flush the cache. - -## What to cache - -Clients may want to run internal statistics about the number of times -a given cached key was actually served in a request, to understand in the -future what is good to cache. In general: - -* We don't want to cache many keys that change continuously. -* We don't want to cache many keys that are requested very rarely. -* We want to cache keys that are requested often and change at a reasonable rate. For an example of key not changing at a reasonable rate, think of a global counter that is continuously `INCR`emented. - -However simpler clients may just evict data using some random sampling just -remembering the last time a given cached value was served, trying to evict -keys that were not served recently. - -## Other hints for implementing client libraries - -* Handling TTLs: make sure you also request the key TTL and set the TTL in the local cache if you want to support caching keys with a TTL. -* Putting a max TTL on every key is a good idea, even if it has no TTL. This protects against bugs or connection issues that would make the client have old data in the local copy. -* Limiting the amount of memory used by clients is absolutely needed. There must be a way to evict old keys when new ones are added. - -## Limiting the amount of memory used by Valkey - -Be sure to configure a suitable value for the maximum number of keys remembered by Valkey or alternatively use the BCAST mode that consumes no memory at all on the Valkey side. Note that the memory consumed by Valkey when BCAST is not used, is proportional both to the number of keys tracked and the number of clients requesting such keys. - diff --git a/topics/clients.md b/topics/clients.md deleted file mode 100644 index f49165c3..00000000 --- a/topics/clients.md +++ /dev/null @@ -1,197 +0,0 @@ ---- -title: "Client handling" -description: > - How the Valkey server manages client connections ---- - -This document provides information about how Valkey handles clients at the network layer level: connections, timeouts, buffers, and other similar topics are covered here. - -## Accepting Client Connections - -Valkey accepts clients connections on the configured TCP port and on the Unix socket if enabled. When a new client connection is accepted the following operations are performed: - -* The client socket is put in the non-blocking state since Valkey uses multiplexing and non-blocking I/O. -* The `TCP_NODELAY` option is set in order to ensure that there are no delays to the connection. -* A *readable* file event is created so that Valkey is able to collect the client queries as soon as new data is available to read on the socket. - -After the client is initialized, Valkey checks if it is already at the limit -configured for the number of simultaneous clients (configured using the `maxclients` configuration directive, see the next section of this document for further information). - -When Valkey can't accept a new client connection because the maximum number of clients -has been reached, it tries to send an error to the client in order to -make it aware of this condition, closing the connection immediately. -The error message will reach the client even if the connection is -closed immediately by Valkey because the new socket output buffer is usually -big enough to contain the error, so the kernel will handle transmission -of the error. - -## What Order are Client Requests Served In? - -The order is determined by a combination of the client socket file descriptor -number and order in which the kernel reports events, so the order should be -considered as unspecified. - -However, Valkey does the following two things when serving clients: - -* It only performs a single `read()` system call every time there is something new to read from the client socket. This ensures that if we have multiple clients connected, and a few send queries at a high rate, other clients are not penalized and will not experience latency issues. -* However once new data is read from a client, all the queries contained in the current buffers are processed sequentially. This improves locality and does not need iterating a second time to see if there are clients that need some processing time. - -## Maximum Concurrent Connected Clients - -The limit for the maximum number of clients that can be handled simultaneously -is configurable using the `maxclients` directive in `valkey.conf`. The default -is 10,000 clients. - -However, Valkey checks with the kernel what the maximum number of file -descriptors that we are able to open is (the *soft limit* is checked). If the -limit is less than the maximum number of clients we want to handle, plus -32 (that is the number of file descriptors Valkey reserves for internal uses), -then the maximum number of clients is updated to match the number -of clients it is *really able to handle* under the current operating system -limit. - -When `maxclients` is set to a number greater than Valkey can support, a message is logged at startup: - -``` -$ ./valkey-server --maxclients 100000 -41422:M 03 Dec 2025 17:00:00.000 # You requested maxclients of 100000 requiring at least 100032 max file descriptors. -41422:M 03 Dec 2025 17:00:00.000 # Server can't set maximum open files to 100032 because of OS error: Operation not permitted. -41422:M 03 Dec 2025 17:00:00.000 # Current maximum open files is 10000. maxclients has been reduced to 9968 to compensate for low ulimit. If you need higher maxclients increase 'ulimit -n'. -``` - -When Valkey is configured in order to handle a specific number of clients it -is a good idea to make sure that the operating system limit for the maximum -number of file descriptors per process is also set accordingly. - -Under Linux these limits can be set both in the current session and as a -system-wide setting with the following commands: - -* `ulimit -Sn 100000 # This will only work if hard limit is big enough.` -* `sysctl -w fs.file-max=100000` - -## Output Buffer Limits - -Valkey needs to handle a variable-length output buffer for every client, since -a command can produce a large amount of data that needs to be transferred to the -client. - -However it is possible that a client sends more commands producing more output -to serve at a faster rate than that which Valkey can send the existing output to the -client. This is especially true with Pub/Sub clients in case a client is not -able to process new messages fast enough. - -Both conditions will cause the client output buffer to grow and consume -more and more memory. For this reason by default Sets limits to the -output buffer size for different kind of clients. When the limit is reached -the client connection is closed and the event logged in the Valkey log file. - -There are two kind of limits Valkey uses: - -* The **hard limit** is a fixed limit that when reached will make Valkey close the client connection as soon as possible. -* The **soft limit** instead is a limit that depends on the time, for instance a soft limit of 32 megabytes per 10 seconds means that if the client has an output buffer bigger than 32 megabytes for, continuously, 10 seconds, the connection gets closed. - -Different kind of clients have different default limits: - -* **Normal clients** have a default limit of 0, that means, no limit at all, because most normal clients use blocking implementations sending a single command and waiting for the reply to be completely read before sending the next command, so it is always not desirable to close the connection in case of a normal client. -* **Pub/Sub clients** have a default hard limit of 32 megabytes and a soft limit of 8 megabytes per 60 seconds. -* **Replicas** have a default hard limit of 256 megabytes and a soft limit of 64 megabyte per 60 seconds. - -It is possible to change the limit at runtime using the `CONFIG SET` command or in a permanent way using the Valkey configuration file `valkey.conf`. See the example `valkey.conf` in the Valkey distribution for more information about how to set the limit. - -## Query Buffer Hard Limit - -Every client is also subject to a query buffer limit. This is a hard limit that will close the connection when the client query buffer (that is the buffer we use to accumulate commands from the client) reaches 1 GB by default, and is actually only an extreme limit to avoid a server crash in case of client or server software bugs. -The limit can be changed with the `client-query-buffer-limit` configuration directive, also at runtime using `CONFIG SET`. -Starting with Valkey 8.0, when authentication is required, a client that has not yet authenticated is limited to 1 MB regardless of this setting. - -## Client Eviction - -Valkey is built to handle a very large number of client connections. -Client connections tend to consume memory, and when there are many of them, the aggregate memory consumption can be extremely high, leading to data eviction or out-of-memory errors. -These cases can be mitigated to an extent using [output buffer limits](#output-buffer-limits), but Valkey allows us a more robust configuration to limit the aggregate memory used by all clients' connections. - - -This mechanism is called **client eviction**, and it's essentially a safety mechanism that will disconnect clients once the aggregate memory usage of all clients is above a threshold. -The mechanism first attempts to disconnect clients that use the most memory. -It disconnects the minimal number of clients needed to return below the `maxmemory-clients` threshold. - -`maxmemory-clients` defines the maximum aggregate memory usage of all clients connected to Valkey. -The aggregation takes into account all the memory used by the client connections: the [query buffer](#query-buffer-hard-limit), the output buffer, and other intermediate buffers. - -Note that replica and primary connections aren't affected by the client eviction mechanism. Therefore, such connections are never evicted. - -`maxmemory-clients` can be set permanently in the configuration file (`valkey.conf`) or via the `CONFIG SET` command. -This setting can either be 0 (meaning no limit), a size in bytes (possibly with `mb`/`gb` suffix), -or a percentage of `maxmemory` by using the `%` suffix (e.g. setting it to `10%` would mean 10% of the `maxmemory` configuration). - -The default setting is 0, meaning client eviction is turned off by default. -However, for any large production deployment, it is highly recommended to configure some non-zero `maxmemory-clients` value. -A value `5%`, for example, can be a good place to start. - -It is possible to flag a specific client connection to be excluded from the client eviction mechanism. -This is useful for control path connections. -If, for example, you have an application that monitors the server via the `INFO` command and alerts you in case of a problem, you might want to make sure this connection isn't evicted. -You can do so using the following command (from the relevant client's connection): - -`CLIENT NO-EVICT` `on` - -And you can revert that with: - -`CLIENT NO-EVICT` `off` - -For more information and an example refer to the `maxmemory-clients` section in the default `valkey.conf` file. - -Client eviction is available from Redis OSS 7.0. - -## Client Timeouts - -By default recent versions of Valkey don't close the connection with the client -if the client is idle for many seconds: the connection will remain open forever. - -However if you don't like this behavior, you can configure a timeout, so that -if the client is idle for more than the specified number of seconds, the client connection will be closed. - -You can configure this limit via `valkey.conf` or simply using `CONFIG SET timeout `. - -Note that the timeout only applies to normal clients and it **does not apply to Pub/Sub clients**, since a Pub/Sub connection is a *push style* connection so a client that is idle is the norm. - -Even if by default connections are not subject to timeout, there are two conditions when it makes sense to set a timeout: - -* Mission critical applications where a bug in the client software may saturate the Valkey server with idle connections, causing service disruption. -* As a debugging mechanism in order to be able to connect with the server if a bug in the client software saturates the server with idle connections, making it impossible to interact with the server. - -Timeouts are not to be considered very precise: Valkey avoids setting timer events or running O(N) algorithms in order to check idle clients, so the check is performed incrementally from time to time. This means that it is possible that while the timeout is set to 10 seconds, the client connection will be closed, for instance, after 12 seconds if many clients are connected at the same time. - -## The CLIENT Command - -The Valkey `CLIENT` command allows you to inspect the state of every connected client, to kill a specific client, and to name connections. It is a very powerful debugging tool if you use Valkey at scale. - -`CLIENT LIST` is used in order to obtain a list of connected clients and their state: - -``` -127.0.0.1:6379> client list -addr=127.0.0.1:52555 fd=5 name= age=855 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=32768 obl=0 oll=0 omem=0 events=r cmd=client -addr=127.0.0.1:52787 fd=6 name= age=6 idle=5 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=0 obl=0 oll=0 omem=0 events=r cmd=ping -``` - -In the above example two clients are connected to the Valkey server. Let's look at what some of the data returned represents: - -* **addr**: The client address, that is, the client IP and the remote port number it used to connect with the Valkey server. -* **fd**: The client socket file descriptor number. -* **name**: The client name as set by `CLIENT SETNAME`. -* **age**: The number of seconds the connection existed for. -* **idle**: The number of seconds the connection is idle. -* **flags**: The kind of client (N means normal client, check the [full list of flags](../commands/client-list.md)). -* **omem**: The amount of memory used by the client for the output buffer. -* **cmd**: The last executed command. - -See the [`CLIENT LIST`](../commands/client-list.md) documentation for the full listing of fields and their purpose. - -Once you have the list of clients, you can close a client's connection using the `CLIENT KILL` command, specifying the client address as its argument. - -The commands `CLIENT SETNAME` and `CLIENT GETNAME` can be used to set and get the connection name. Starting with Redis OSS 4.0, the client name is shown in the -`SLOWLOG` output, to help identify clients that create latency issues. - -## TCP keepalive - -Valkey has TCP keepalive (`SO_KEEPALIVE` socket option) enabled by default and set to about 300 seconds. This option is useful in order to detect dead peers (clients that cannot be reached even if they look connected). Moreover, if there is network equipment between clients and servers that need to see some traffic in order to take the connection open, the option will prevent unexpected connection closed events. diff --git a/topics/cluster-spec.md b/topics/cluster-spec.md deleted file mode 100644 index 3bf8c593..00000000 --- a/topics/cluster-spec.md +++ /dev/null @@ -1,1354 +0,0 @@ ---- -title: Cluster specification -description: > - Detailed specification for Valkey cluster ---- - -Welcome to the **Valkey Cluster Specification**. Here you'll find information -about the algorithms and design rationales of Valkey Cluster. - -## Main properties and rationales of the design - -### Valkey Cluster goals - -Valkey Cluster is a distributed implementation of Valkey with the following goals in order of importance in the design: - -* High performance and linear scalability up to 2000 nodes. There are no proxies, asynchronous replication is used, and no merge operations are performed on values. -* Acceptable degree of write safety: the system tries (in a best-effort way) to retain all the writes originating from clients connected with the majority of the primary nodes. Usually there are small windows where acknowledged writes can be lost. Windows to lose acknowledged writes are larger when clients are in a minority partition. -* Availability: Valkey Cluster is able to survive partitions where the majority of the primary nodes are reachable and there is at least one reachable replica for every primary node that is no longer reachable. Moreover using *replicas migration*, primaries no longer replicated by any replica will receive one from a primary which is covered by multiple replicas. - -### Implemented subset - -Valkey Cluster implements all the single key commands available in the -non-distributed version of Valkey. Commands performing complex multi-key -operations like set unions and intersections are implemented for cases where -all of the keys involved in the operation hash to the same slot. - -Valkey Cluster implements a concept called **hash tags** that can be used -to force certain keys to be stored in the same hash slot. However, during -manual resharding, multi-key operations may become unavailable for some time -while single-key operations are always available. - -Starting with version 9.0, Valkey cluster supports multiple databases, similar to standalone mode but with some additional restrictions. -You can enable multi-database support using the `cluster-databases` setting (default value is `1`). - -## Client and Server roles in the Valkey cluster protocol - -In Valkey Cluster, nodes are responsible for holding the data, -and taking the state of the cluster, including mapping keys to the right nodes. -Cluster nodes are also able to auto-discover other nodes, detect non-working -nodes, and promote replica nodes to primary when needed in order -to continue to operate when a failure occurs. - -To perform their tasks all the cluster nodes are connected using a -TCP bus and a binary protocol, called the **Valkey Cluster Bus**. -Every node is connected to every other node in the cluster using the cluster -bus. Nodes use a gossip protocol to propagate information about the cluster -in order to discover new nodes, to send ping packets to make sure all the -other nodes are working properly, and to send cluster messages needed to -signal specific conditions. The cluster bus is also used in order to -propagate Pub/Sub messages across the cluster and to orchestrate manual -failovers when requested by users (manual failovers are failovers which -are not initiated by the Valkey Cluster failure detector, but by the -system administrator directly). - -Since cluster nodes are not able to proxy requests, clients may be redirected -to other nodes using redirection errors `-MOVED` and `-ASK`. -The client is in theory free to send requests to all the nodes in the cluster, -getting redirected if needed, so the client is not required to hold the -state of the cluster. However clients that are able to cache the map between -keys and nodes can improve the performance in a sensible way. - -### Write safety - -Valkey Cluster uses asynchronous replication between nodes, and **last failover wins** implicit merge function. This means that the last elected primary dataset eventually replaces all the other replicas. There is always a window of time when it is possible to lose writes during partitions. However these windows are very different in the case of a client that is connected to the majority of primaries, and a client that is connected to the minority of primaries. - -Valkey Cluster tries harder to retain writes that are performed by clients connected to the majority of primaries, compared to writes performed in the minority side. -The following are examples of scenarios that lead to loss of acknowledged -writes received in the majority partitions during failures: - -1. A write may reach a primary, but while the primary may be able to reply to the client, the write may not be propagated to replicas via the asynchronous replication used between primary and replica nodes. If the primary dies without the write reaching the replicas, the write is lost forever if the primary is unreachable for a long enough period that one of its replicas is promoted. This is usually hard to observe in the case of a total, sudden failure of a primary node since primaries try to reply to clients (with the acknowledge of the write) and replicas (propagating the write) at about the same time. However it is a real world failure mode. - -2. Another theoretically possible failure mode where writes are lost is the following: - -* A primary is unreachable because of a partition. -* It gets failed over by one of its replicas. -* After some time it may be reachable again. -* A client with an out-of-date routing table may write to the old primary before it is converted into a replica (of the new primary) by the cluster. - -The second failure mode is unlikely to happen because primary nodes are unable to communicate with the majority of the other primaries for enough time to be failed over will no longer accept writes, and when the partition is fixed writes are still refused for a small amount of time to allow other nodes to inform about configuration changes. This failure mode also requires that the client's routing table has not yet been updated. - -Writes targeting the minority side of a partition have a larger window in which to get lost. For example, Valkey Cluster loses a non-trivial number of writes on partitions where there is a minority of primaries and at least one or more clients, since all the writes sent to the primaries may potentially get lost if the primaries are failed over in the majority side. - -Specifically, for a primary to be failed over it must be unreachable by the majority of primaries for at least `NODE_TIMEOUT`, so if the partition is fixed before that time, no writes are lost. When the partition lasts for more than `NODE_TIMEOUT`, all the writes performed in the minority side up to that point may be lost. However the minority side of a Valkey Cluster will start refusing writes as soon as `NODE_TIMEOUT` time has elapsed without contact with the majority, so there is a maximum window after which the minority becomes no longer available. Hence, no writes are accepted or lost after that time. - -### Availability - -Valkey Cluster is not available in the minority side of the partition. In the majority side of the partition assuming that there are at least the majority of primaries and a replica for every unreachable primary, the cluster becomes available again after `NODE_TIMEOUT` time plus a few more seconds required for a replica to get elected and failover its primary (failovers are usually executed in a matter of 1 or 2 seconds). - -This means that Valkey Cluster is designed to survive failures of a few nodes in the cluster, but it is not a suitable solution for applications that require availability in the event of large net splits. - -In the example of a cluster composed of N primary nodes where every node has a single replica, the majority side of the cluster will remain available as long as a single node is partitioned away, and will remain available with a probability of `1-(1/(N*2-1))` when two nodes are partitioned away (after the first node fails we are left with `N*2-1` nodes in total, and the probability of the only primary without a replica to fail is `1/(N*2-1))`. - -For example, in a cluster with 5 nodes and a single replica per node, there is a `1/(5*2-1) = 11.11%` probability that after two nodes are partitioned away from the majority, the cluster will no longer be available. - -Thanks to a Valkey Cluster feature called **replicas migration** the Cluster -availability is improved in many real world scenarios by the fact that -replicas migrate to orphaned primaries (primaries no longer having replicas). -So at every successful failure event, the cluster may reconfigure the replicas -layout in order to better resist the next failure. - -### Performance - -In Valkey Cluster nodes don't proxy commands to the right node in charge for a given key, but instead they redirect clients to the right nodes serving a given portion of the key space. - -Eventually clients obtain an up-to-date representation of the cluster and which node serves which subset of keys, so during normal operations clients directly contact the right nodes in order to send a given command. - -Because of the use of asynchronous replication, nodes do not wait for other nodes' acknowledgment of writes (if not explicitly requested using the `WAIT` command). - -Also, because multi-key commands are only limited to *near* keys, data is never moved between nodes except when resharding. - -Normal operations are handled exactly as in the case of a single Valkey instance. This means that in a Valkey Cluster with N primary nodes you can expect the same performance as a single Valkey instance multiplied by N as the design scales linearly. At the same time the query is usually performed in a single round trip, since clients usually retain persistent connections with the nodes, so latency figures are also the same as the single standalone Valkey node case. - -Very high performance and scalability while preserving weak but -reasonable forms of data safety and availability is the main goal of -Valkey Cluster. - -### Why merge operations are avoided - -The Valkey Cluster design avoids conflicting versions of the same key-value pair in multiple nodes as in the case of the Valkey data model this is not always desirable. Values in Valkey are often very large; it is common to see lists or sorted sets with millions of elements. Also data types are semantically complex. Transferring and merging these kind of values can be a major bottleneck and/or may require the non-trivial involvement of application-side logic, additional memory to store meta-data, and so forth. - -There are no strict technological limits here. CRDTs or synchronously replicated -state machines can model complex data types similar to Valkey. However, the -actual run time behavior of such systems would not be similar to Valkey Cluster. -Valkey Cluster was designed in order to cover the exact use cases of the -non-clustered Valkey deployment. - -## Overview of Valkey Cluster main components - -### Key distribution model - -The cluster's key space is split into 16384 slots, effectively setting an upper limit -for the cluster size of 16384 primary nodes (however, the suggested max size of -nodes is on the order of ~ 1000 nodes). - -Each primary node in a cluster handles a subset of the 16384 hash slots. -The cluster is **stable** when there is no cluster reconfiguration in -progress (i.e. where hash slots are being moved from one node to another). -When the cluster is stable, a single hash slot will be served by a single node -(however the serving node can have one or more replicas that will replace it in the case of net splits or failures, -and that can be used in order to scale read operations where reading stale data is acceptable). - -The base algorithm used to map keys to hash slots is the following -(read the next paragraph for the hash tag exception to this rule): - - HASH_SLOT = CRC16(key) mod 16384 - -The CRC16 is specified as follows: - -* Name: XMODEM (also known as ZMODEM or CRC-16/ACORN) -* Width: 16 bit -* Poly: 1021 (That is actually x^16 + x^12 + x^5 + 1) -* Initialization: 0000 -* Reflect Input byte: False -* Reflect Output CRC: False -* Xor constant to output CRC: 0000 -* Output for "123456789": 31C3 - -14 out of 16 CRC16 output bits are used (this is why there is -a modulo 16384 operation in the formula above). - -In our tests CRC16 behaved remarkably well in distributing different kinds of -keys evenly across the 16384 slots. - -**Note**: A reference implementation of the CRC16 algorithm used is available in the Appendix A of this document. - -### Hash tags - -There is an exception for the computation of the hash slot that is used in order -to implement **hash tags**. Hash tags are a way to ensure that multiple keys -are allocated in the same hash slot. This is used in order to implement -multi-key operations in Valkey Cluster. - -To implement hash tags, the hash slot for a key is computed in a -slightly different way in certain conditions. -If the key contains a "{...}" pattern only the substring between -`{` and `}` is hashed in order to obtain the hash slot. However since it is -possible that there are multiple occurrences of `{` or `}` the algorithm is -well specified by the following rules: - -* IF the key contains a `{` character. -* AND IF there is a `}` character to the right of `{`. -* AND IF there are one or more characters between the first occurrence of `{` and the first occurrence of `}`. - -Then instead of hashing the key, only what is between the first occurrence of `{` and the following first occurrence of `}` is hashed. - -Examples: - -* The two keys `{user1000}.following` and `{user1000}.followers` will hash to the same hash slot since only the substring `user1000` will be hashed in order to compute the hash slot. -* For the key `foo{}{bar}` the whole key will be hashed as usually since the first occurrence of `{` is followed by `}` on the right without characters in the middle. -* For the key `foo{{bar}}zap` the substring `{bar` will be hashed, because it is the substring between the first occurrence of `{` and the first occurrence of `}` on its right. -* For the key `foo{bar}{zap}` the substring `bar` will be hashed, since the algorithm stops at the first valid or invalid (without bytes inside) match of `{` and `}`. -* What follows from the algorithm is that if the key starts with `{}`, it is guaranteed to be hashed as a whole. This is useful when using binary data as key names. - -#### Glob-style patterns - -Commands accepting a glob-style pattern, including `KEYS`, `SCAN` and `SORT`, are optimized for patterns that imply a single slot. -This means that if all keys that can match a pattern must belong to a specific slot, only this slot is searched for keys matching the pattern. -The pattern slot optimization is introduced in Valkey 8.0. - -The optimization kicks in when the pattern meets the following conditions: - -* the pattern contains a hashtag, -* there are no wildcards or escape characters before the hashtag, and -* the hashtag within curly braces doesn't contain any wildcards or escape characters. - -For example, `SCAN 0 MATCH {abc}*` can successfully recognize the hashtag and scans only the slot corresponding to `abc`. -However, the patterns `*{abc}`, `{a*c}`, or `{a\*bc}` cannot recognize the hashtag, so all slots need to be scanned. - -#### Hash slot example code - -Adding the hash tags exception, the following is an implementation of the `HASH_SLOT` function in Ruby and C language. - -Ruby example code: - - def HASH_SLOT(key) - s = key.index "{" - if s - e = key.index "}",s+1 - if e && e != s+1 - key = key[s+1..e-1] - end - end - crc16(key) % 16384 - end - -C example code: - - unsigned int HASH_SLOT(char *key, int keylen) { - int s, e; /* start-end indexes of { and } */ - - /* Search the first occurrence of '{'. */ - for (s = 0; s < keylen; s++) - if (key[s] == '{') break; - - /* No '{' ? Hash the whole key. This is the base case. */ - if (s == keylen) return crc16(key,keylen) & 16383; - - /* '{' found? Check if we have the corresponding '}'. */ - for (e = s+1; e < keylen; e++) - if (key[e] == '}') break; - - /* No '}' or nothing between {} ? Hash the whole key. */ - if (e == keylen || e == s+1) return crc16(key,keylen) & 16383; - - /* If we are here there is both a { and a } on its right. Hash - * what is in the middle between { and }. */ - return crc16(key+s+1,e-s-1) & 16383; - } - -### Cluster node attributes - -Every node has a unique name in the cluster. The node name is the -hex representation of a 160 bit random number, obtained the first time a -node is started (usually using /dev/urandom). -The node will save its ID in the node configuration file, and will use the -same ID forever, or at least as long as the node configuration file is not -deleted by the system administrator, or a *hard reset* is requested -via the `CLUSTER RESET` command. - -The node ID is used to identify every node across the whole cluster. -It is possible for a given node to change its IP address without any need -to also change the node ID. The cluster is also able to detect the change -in IP/port and reconfigure using the gossip protocol running over the cluster -bus. - -The node ID is not the only information associated with each node, but is -the only one that is always globally consistent. Every node has also the -following set of information associated. Some information is about the -cluster configuration detail of this specific node, and is eventually -consistent across the cluster. Some other information, like the last time -a node was pinged, is instead local to each node. - -Every node maintains the following information about other nodes that it is -aware of in the cluster: The node ID, IP and port of the node, a set of -flags, what is the primary of the node if it is flagged as `replica`, last time -the node was pinged and the last time the pong was received, the current -*configuration epoch* of the node (explained later in this specification), -the link state and finally the set of hash slots served. - -A detailed [explanation of all the node fields](../commands/cluster-nodes.md) is described in the `CLUSTER NODES` documentation. - -The `CLUSTER NODES` command can be sent to any node in the cluster and provides the state of the cluster and the information for each node according to the local view the queried node has of the cluster. - -The following is sample output of the `CLUSTER NODES` command sent to a primary -node in a small cluster of three nodes. - - $ valkey-cli cluster nodes - d1861060fe6a534d42d8a19aeb36600e18785e04 127.0.0.1:6379 myself - 0 1318428930 1 connected 0-1364 - 3886e65cc906bfd9b1f7e7bde468726a052d1dae 127.0.0.1:6380 master - 1318428930 1318428931 2 connected 1365-2729 - d289c575dcbc4bdd2931585fd4339089e461a27d 127.0.0.1:6381 master - 1318428931 1318428931 3 connected 2730-4095 - -In the above listing the different fields are in order: node id, address:port, flags, last ping sent, last pong received, configuration epoch, link state, slots. Details about the above fields will be covered as soon as we talk of specific parts of Valkey Cluster. - -### The cluster bus - -Every Valkey Cluster node has an additional TCP port for receiving -incoming connections from other Valkey Cluster nodes. This port will be derived by adding 10000 to the data port or it can be specified with the cluster-port config. - -Example 1: - -If a Valkey node is listening for client connections on port 6379, -and you do not add cluster-port parameter in valkey.conf, -the Cluster bus port 16379 will be opened. - -Example 2: - -If a Valkey node is listening for client connections on port 6379, -and you set cluster-port 20000 in valkey.conf, -the Cluster bus port 20000 will be opened. - -Node-to-node communication happens exclusively using the Cluster bus and -the Cluster bus protocol: a binary protocol composed of frames -of different types and sizes. The Cluster bus binary protocol is not -publicly documented since it is not intended for external software devices -to talk with Valkey Cluster nodes using this protocol. However you can -obtain more details about the Cluster bus protocol by reading the -`cluster.h` and `cluster.c` files in the Valkey Cluster source code. - -### Cluster topology - -Valkey Cluster is a full mesh where every node is connected with every other node using a TCP connection. - -In a cluster of N nodes, every node has N-1 outgoing TCP connections, and N-1 incoming connections. - -These TCP connections are kept alive all the time and are not created on demand. -When a node expects a pong reply in response to a ping in the cluster bus, before waiting long enough to mark the node as unreachable, it will try to -refresh the connection with the node by reconnecting from scratch. - -While Valkey Cluster nodes form a full mesh, **nodes use a gossip protocol and -a configuration update mechanism in order to avoid exchanging too many -messages between nodes during normal conditions**, so the number of messages -exchanged is not exponential. - -### Node handshake - -Nodes always accept connections on the cluster bus port, and even reply to -pings when received, even if the pinging node is not trusted. -However, all other packets will be discarded by the receiving node if the -sending node is not considered part of the cluster. - -A node will accept another node as part of the cluster only in two ways: - -* If a node presents itself with a `MEET` message (`CLUSTER MEET` command). A meet message is exactly -like a `PING` message, but forces the receiver to accept the node as part of -the cluster. Nodes will send `MEET` messages to other nodes **only if** the system administrator requests this via `CLUSTER MEET ip port`. - -* A node will also register another node as part of the cluster if a node that is already trusted will gossip about this other node. So if A knows B, and B knows C, eventually B will send gossip messages to A about C. When this happens, A will register C as part of the network, and will try to connect with C. - -This means that as long as we join nodes in any connected graph, they'll eventually form a fully connected graph automatically. This means that the cluster is able to auto-discover other nodes, but only if there is a trusted relationship that was forced by the system administrator. - -This mechanism makes the cluster more robust but prevents different Valkey clusters from accidentally mixing after change of IP addresses or other network related events. - -## Redirection and resharding - -### MOVED Redirection - -A Valkey client is free to send queries to every node in the cluster, including -replica nodes. The node will analyze the query, and if it is acceptable -(that is, only a single key is mentioned in the query, or the multiple keys -mentioned are all to the same hash slot) it will lookup what -node is responsible for the hash slot where the key or keys belong. - -If the hash slot is served by the node, the query is simply processed, otherwise -the node will check its internal hash slot to node map, and will reply -to the client with a MOVED error, like in the following example: - - GET x - -MOVED 3999 127.0.0.1:6381 - -The error includes the hash slot of the key (3999) and the endpoint:port of the instance that can serve the query. -The client needs to reissue the query to the specified node's endpoint address and port. -The endpoint can be either an IP address, a hostname, or it can be empty (e.g. `-MOVED 3999 :6380`). -An empty endpoint indicates that the server node has an unknown endpoint, and the client should send the next request to the same endpoint as the current request but with the provided port. - -The endpoint can be an IPv6 address, which can contain multiple colons. -Here, an IPv6 address is *not* enclosed in square brackets as it would be in other contexts such as URIs. -To properly split the string `endpoint:port` into `endpoint` and `port`, a cluster client needs to locate the *last* colon. - -Note that even if the client waits a long time before reissuing the query, -and in the meantime the cluster configuration changed, the destination node -will reply again with a MOVED error if the hash slot 3999 is now served by -another node. The same happens if the contacted node had no updated information. - -So while from the point of view of the cluster nodes are identified by -IDs we try to simplify our interface with the client just exposing a map -between hash slots and Valkey nodes identified by endpoint:port pairs. - -The client is not required to, but should try to memorize that hash slot -3999 is served by 127.0.0.1:6381. This way once a new command needs to -be issued it can compute the hash slot of the target key and have a -greater chance of choosing the right node. - -An alternative is to just refresh the whole client-side cluster layout -using the `CLUSTER SHARDS`, or the deprecated `CLUSTER SLOTS`, command -when a MOVED redirection is received. When a redirection is encountered, it -is likely multiple slots were reconfigured rather than just one, so updating -the client configuration as soon as possible is often the best strategy. - -Note that when the Cluster is stable (no ongoing changes in the configuration), -eventually all the clients will obtain a map of hash slots -> nodes, making -the cluster efficient, with clients directly addressing the right nodes -without redirections, proxies or other single point of failure entities. - -A client **must be also able to handle -ASK redirections** that are described -later in this document, otherwise it is not a complete Valkey Cluster client. - -### Live resharding - -#### Atomic slot migration - -Valkey 9.0 introduced a server-side mechanism for live resharding called -[atomic slot migration](atomic-slot-migration.md), which is the recommended method. - -When compared to legacy slot migration, atomic slot migration allows you to -perform live resharding faster, with higher reliability, and less client-side -impact. Atomic slot migration is started using the `CLUSTER MIGRATESLOTS` command. - -You can find more details about atomic slot migration in the following pages: - -* [Atomic slot migration overview](atomic-slot-migration.md) -* [`CLUSTER MIGRATESLOTS` command documentation](../commands/cluster-migrateslots.md) -* [`CLUSTER GETSLOTMIGRATIONS` command documentation](../commands/cluster-getslotmigrations.md) -* [`CLUSTER CANCELSLOTMIGRATIONS` command documentation](../commands/cluster-cancelslotmigrations.md) - -#### Legacy slot migration - -Valkey Cluster also supports a legacy, client-driven mechanism to add and remove nodes while the cluster -is running. Adding or removing a node is abstracted into the same -operation: moving a hash slot from one node to another. This means -that the same basic mechanism can be used in order to rebalance the cluster, add -or remove nodes, and so forth. - -* To add a new node to the cluster an empty node is added to the cluster and some set of hash slots are moved from existing nodes to the new node. -* To remove a node from the cluster the hash slots assigned to that node are moved to other existing nodes. -* To rebalance the cluster a given set of hash slots are moved between nodes. - -The core of the implementation is the ability to move hash slots around. -From a practical point of view a hash slot is just a set of keys, so -what Valkey Cluster really does during *resharding* is to move keys from -an instance to another instance. Moving a hash slot means moving all the keys -that happen to hash into this hash slot. - -To understand how this works we need to show the `CLUSTER` subcommands -that are used to manipulate the slots translation table in a Valkey Cluster node. - -The following subcommands are available (among others not useful in this case): - -* `CLUSTER ADDSLOTS` slot1 [slot2] ... [slotN] -* `CLUSTER DELSLOTS` slot1 [slot2] ... [slotN] -* `CLUSTER ADDSLOTSRANGE` start-slot1 end-slot1 [start-slot2 end-slot2] ... [start-slotN end-slotN] -* `CLUSTER DELSLOTSRANGE` start-slot1 end-slot1 [start-slot2 end-slot2] ... [start-slotN end-slotN] -* `CLUSTER SETSLOT` slot NODE node -* `CLUSTER SETSLOT` slot MIGRATING node -* `CLUSTER SETSLOT` slot IMPORTING node - -The first four commands, `ADDSLOTS`, `DELSLOTS`, `ADDSLOTSRANGE` and `DELSLOTSRANGE`, are simply used to assign -(or remove) slots to a Valkey node. Assigning a slot means to tell a given -primary node that it will be in charge of storing and serving content for -the specified hash slot. - -After the hash slots are assigned they will propagate across the cluster -using the gossip protocol, as specified later in the -*configuration propagation* section. - -The `ADDSLOTS` and `ADDSLOTSRANGE` commands are usually used when a new cluster is created -from scratch to assign each primary node a subset of all the 16384 hash -slots available. - -The `DELSLOTS` and `DELSLOTSRANGE` are mainly used for manual modification of a cluster configuration -or for debugging tasks: in practice it is rarely used. - -The `SETSLOT` subcommand is used to assign a slot to a specific node ID if -the `SETSLOT NODE` form is used. Otherwise the slot can be set in the -two special states `MIGRATING` and `IMPORTING`. Those two special states -are used in order to migrate a hash slot from one node to another. - -* When a slot is set as MIGRATING, the node will accept all queries that -are about this hash slot, but only if the key in question -exists, otherwise the query is forwarded using a `-ASK` redirection to the -node that is target of the migration. -* When a slot is set as IMPORTING, the node will accept all queries that -are about this hash slot, but only if the request is -preceded by an `ASKING` command. If the `ASKING` command was not given -by the client, the query is redirected to the real hash slot owner via -a `-MOVED` redirection error, as would happen normally. - -Let's make this clearer with an example of hash slot migration. -Assume that we have two Valkey primary nodes, called A and B. -We want to move hash slot 8 from A to B, so we issue commands like this: - -* We send B: CLUSTER SETSLOT 8 IMPORTING A -* We send A: CLUSTER SETSLOT 8 MIGRATING B - -All the other nodes will continue to point clients to node "A" every time -they are queried with a key that belongs to hash slot 8, so what happens -is that: - -* All queries about existing keys are processed by "A". -* All queries about non-existing keys in A are processed by "B", because "A" will redirect clients to "B". - -This way we no longer create new keys in "A". -In the meantime, `valkey-cli` used during reshardings -and Valkey Cluster configuration will migrate existing keys in -hash slot 8 from A to B. -This is performed using the following command: - - CLUSTER GETKEYSINSLOT slot count - -The above command will return `count` keys in the specified hash slot. -For keys returned, `valkey-cli` sends node "A" a `MIGRATE` command, that -will migrate the specified keys from A to B in an atomic way (both instances -are locked for the time (usually very small time) needed to migrate keys so -there are no race conditions). This is how `MIGRATE` works: - - MIGRATE target_host target_port "" target_database id timeout KEYS key1 key2 ... - -`MIGRATE` will connect to the target instance, send a serialized version of -the key, and once an OK code is received, the old key from its own dataset -will be deleted. From the point of view of an external client a key exists -either in A or B at any given time. - -In Valkey Cluster there is no need to specify a database other than 0, but -`MIGRATE` is a general command that can be used for other tasks not -involving Valkey Cluster. -`MIGRATE` is optimized to be as fast as possible even when moving complex -keys such as long lists, but in Valkey Cluster reconfiguring the -cluster where big keys are present is not considered a wise procedure if -there are latency constraints in the application using the database. - -When the migration process is finally finished, the `SETSLOT NODE ` command is sent to the two nodes involved in the migration in order to -set the slots to their normal state again. The same command is usually -sent to all other nodes to avoid waiting for the natural -propagation of the new configuration across the cluster. - -#### Replication of `CLUSTER SETSLOT` - -Starting from Valkey 8.0, the `CLUSTER SETSLOT` command is replicated if the replicas are running Valkey version 8.0+. -The primary node waits up to 2 seconds, by default, for all healthy replicas to acknowledge the replication. -If not all health replicas acknowledge the replication within this time frame, the primary aborts the command, -and the client receives a `NOREPLICAS Not enough good replicas to write` error. -Operators can retry the command or customize the timeout using the `TIMEOUT` parameter to further increase the -reliability of live resharding: - - CLUSTER SETSLOT slot [MIGRATING|IMPORTING|NODE] node-id [TIMEOUT timeout] - -The `timeout` is specified in seconds, where a value of 0 indicates an indefinite wait time. - -Replicating the slot information and ensuring acknowledgement from health replicas significantly reduces -the likelihood of losing replication states if the primary fails after executing the command. -For example, consider a scenario where the target primary node `B` is finalizing a slot migration. -Before the `SETSLOT` command is replicated to its replica node `B’`, `B` might send a cluster `PONG` -message to the source primary node `A`, promoting `A` to relinquish its ownership of the slot in question. -If `B` crashes right after this point, the replica node `B’`, which could be elected as the new primary, -would not be aware of the slot ownership transfer without the successful replication of `SETSLOT`. -This would leave the slot without an owner, leading to potential data loss and cluster topology inconsistency. - -#### Election in empty shards - -Starting from Valkey 8.0, Valkey clusters introduce the ability to elect a primary in empty shards. -This behavior ensures that even when a shard is in the process of receiving its first slot, -a primary can be elected. This prevents scenarios where there would be no primary available in the -empty shard to handle redirected requests from the official slot owner, -thereby maintaining availability during the live resharding. - -### ASK redirection - -In the previous section, we briefly talked about ASK redirection. Why can't -we simply use MOVED redirection? Because while MOVED means that -we think the hash slot is permanently served by a different node and the -next queries should be tried against the specified node. ASK means to -send only the next query to the specified node. - -This is needed because the next query about hash slot 8 can be about a -key that is still in A, so we always want the client to try A and -then B if needed. Since this happens only for one hash slot out of 16384 -available, the performance hit on the cluster is acceptable. - -We need to force that client behavior, so to make sure -that clients will only try node B after A was tried, node B will only -accept queries of a slot that is set as IMPORTING if the client sends the -ASKING command before sending the query. - -Basically the ASKING command sets a one-time flag on the client that forces -a node to serve a query about an IMPORTING slot. - -The full semantics of ASK redirection from the point of view of the client is as follows: - -* If ASK redirection is received, send only the query that was redirected to the specified node but continue sending subsequent queries to the old node. -* Start the redirected query with the ASKING command. -* Don't yet update local client tables to map hash slot 8 to B. - -Once hash slot 8 migration is completed, A will send a MOVED message and -the client may permanently map hash slot 8 to the new endpoint and port pair. -Note that if a buggy client performs the map earlier this is not -a problem since it will not send the ASKING command before issuing the query, -so B will redirect the client to A using a MOVED redirection error. - -Slots migration is explained in similar terms but with different wording -(for the sake of redundancy in the documentation) in the `CLUSTER SETSLOT` -command documentation. - -Starting from Valkey 8.0, when the primary in either the source or target shard fails during live resharding, -the primary in the other shard will automatically attempt to update its migrating/importing state to correctly pair -with the newly elected primary. If this update is successful, the ASK redirection will continue functioning without -requiring administrator intervention. In the event that slot migration fails, administrators can manually resume -the interrupted slot migration by running the command `valkey-cli --cluster fix `. - -Additionally, since Valkey 8.0, replicas are now able to return `ASK` redirects during slot migrations. -This capability was previously unavailable, as replicas were not aware of ongoing slot migrations in earlier versions. -See the [READONLY](../commands/readonly.md) command. - -### Client connections and redirection handling - -To be efficient, Valkey Cluster clients maintain a map of the current slot -configuration. However, this configuration is not *required* to be up to date. -When contacting the wrong node results in a redirection, the client -can update its internal slot map accordingly. - -Clients usually need to fetch a complete list of slots and mapped node -addresses in two different situations: - -* At startup, to populate the initial slots configuration -* When the client receives a `MOVED` redirection - -Note that a client may handle the `MOVED` redirection by updating just the -moved slot in its table; however this is usually not efficient because often -the configuration of multiple slots will be modified at once. For example, if a -replica is promoted to primary, all of the slots served by the old primary will -be remapped). It is much simpler to react to a `MOVED` redirection by -fetching the full map of slots to nodes from scratch. - -Client can issue a `CLUSTER SLOTS` command to retrieve an array of slot -ranges and the associated primary and replica nodes serving the specified ranges. - -The following is an example of output of `CLUSTER SLOTS`: - -``` -127.0.0.1:7000> cluster slots -1) 1) (integer) 5461 - 2) (integer) 10922 - 3) 1) "127.0.0.1" - 2) (integer) 7001 - 4) 1) "127.0.0.1" - 2) (integer) 7004 -2) 1) (integer) 0 - 2) (integer) 5460 - 3) 1) "127.0.0.1" - 2) (integer) 7000 - 4) 1) "127.0.0.1" - 2) (integer) 7003 -3) 1) (integer) 10923 - 2) (integer) 16383 - 3) 1) "127.0.0.1" - 2) (integer) 7002 - 4) 1) "127.0.0.1" - 2) (integer) 7005 -``` - -The first two sub-elements of every element of the returned array are the -start and end slots of the range. The additional elements represent address-port -pairs. The first address-port pair is the primary serving the slot, and the -additional address-port pairs are the replicas serving the same slot. Replicas -will be listed only when not in an error condition (i.e., when their FAIL flag is not set). - -The first element in the output above says that slots from 5461 to 10922 -(start and end included) are served by 127.0.0.1:7001, and it is possible -to scale read-only load contacting the replica at 127.0.0.1:7004. - -`CLUSTER SLOTS` is not guaranteed to return ranges that cover the full -16384 slots if the cluster is misconfigured, so clients should initialize the -slots configuration map filling the target nodes with NULL objects, and -report an error if the user tries to execute commands about keys -that belong to unassigned slots. - -Before returning an error to the caller when a slot is found to -be unassigned, the client should try to fetch the slots configuration -again to check if the cluster is now configured properly. - -### Multi-keys operations - -Using hash tags, clients are free to use multi-key operations. -For example the following operation is valid: - - MSET {user:1000}.name Angela {user:1000}.surname White - -Multi-key operations may become unavailable when a resharding of the -hash slot the keys belong to is in progress. - -More specifically, even during a resharding the multi-key operations targeting -keys that all exist and all still hash to the same slot (either the source or -destination node) are still available. - -Operations on keys that don't exist or are - during the resharding - split -between the source and destination nodes, will generate a `-TRYAGAIN` error. -The client can try the operation after some time, or report back the error. - -As soon as migration of the specified hash slot has terminated, all -multi-key operations are available again for that hash slot. - -### Scaling reads using replica nodes - -Normally replica nodes will redirect clients to the authoritative primary for -the hash slot involved in a given command, however clients can use replicas -in order to scale reads using the `READONLY` command. - -`READONLY` tells a Valkey Cluster replica node that the client is ok reading -possibly stale data and is not interested in running write queries. - -When the connection is in readonly mode, the cluster will send a redirection -to the client only if the operation involves keys not served -by the replica's primary node. This may happen because: - -1. The client sent a command about hash slots never served by the primary of this replica. -2. The cluster was reconfigured (for example resharded) and the replica is no longer able to serve commands for a given hash slot. - -When this happens the client should update its hash slot map as explained in -the previous sections. - -The readonly state of the connection can be cleared using the `READWRITE` command. - -Commands sent with no key arguments, such as `SCAN`, `DBSIZE` or `FLUSHDB`, -are not tied to a hash slot, so a replica never answers them with `-MOVED`. -Since Valkey 9.2, if the client uses [`CLIENT CAPA redirect`](../commands/client-capa.md) -and is not in readonly mode, the replica answers read and write commands of this kind -with `-REDIRECT primary-ip:port`, pointing to its own primary. - -## Fault Tolerance - -### Heartbeat and gossip messages - -Valkey Cluster nodes continuously exchange ping and pong packets. Those two kinds of packets have the same structure, and both carry important configuration information. The only actual difference is the message type field. We'll refer to the sum of ping and pong packets as *heartbeat packets*. - -Usually nodes send ping packets that will trigger the receivers to reply with pong packets. However this is not necessarily true. It is possible for nodes to just send pong packets to send information to other nodes about their configuration, without triggering a reply. This is useful, for example, in order to broadcast a new configuration as soon as possible. - -Usually a node will ping a few random nodes every second so that the total number of ping packets sent (and pong packets received) by each node is a constant amount regardless of the number of nodes in the cluster. - -However every node makes sure to ping every other node that hasn't sent a ping or received a pong for longer than half the `NODE_TIMEOUT` time. Before `NODE_TIMEOUT` has elapsed, nodes also try to reconnect the TCP link with another node to make sure nodes are not believed to be unreachable only because there is a problem in the current TCP connection. - -The number of messages globally exchanged can be sizable if `NODE_TIMEOUT` is set to a small figure and the number of nodes (N) is very large, since every node will try to ping every other node for which they don't have fresh information every half the `NODE_TIMEOUT` time. - -For example in a 100 node cluster with a node timeout set to 60 seconds, every node will try to send 99 pings every 30 seconds, with a total amount of pings of 3.3 per second. Multiplied by 100 nodes, this is 330 pings per second in the total cluster. - -There are ways to lower the number of messages, however there have been no -reported issues with the bandwidth currently used by Valkey Cluster failure -detection, so for now the obvious and direct design is used. Note that even -in the above example, the 330 packets per second exchanged are evenly -divided among 100 different nodes, so the traffic each node receives -is acceptable. - -### Heartbeat packet content - -Ping and pong packets contain a header that is common to all types of packets (for instance packets to request a failover vote), and a special gossip section that is specific to Ping and Pong packets. - -The common header has the following information: - -* Node ID, a 160 bit pseudorandom string that is assigned the first time a node is created and remains the same for all the life of a Valkey Cluster node. -* The `currentEpoch` and `configEpoch` fields of the sending node that are used to mount the distributed algorithms used by Valkey Cluster (this is explained in detail in the next sections). If the node is a replica the `configEpoch` is the last known `configEpoch` of its primary. -* The node flags, indicating if the node is a replica, a primary, and other single-bit node information. -* A bitmap of the hash slots served by the sending node, or if the node is a replica, a bitmap of the slots served by its primary. -* The sender TCP base port that is the port used by Valkey to accept client commands. -* The cluster port that is the port used by Valkey for node-to-node communication. -* The state of the cluster from the point of view of the sender (down or ok). -* The primary node ID of the sending node, if it is a replica. - -Ping and pong packets also contain a gossip section. This section offers to the receiver a view of what the sender node thinks about other nodes in the cluster. The gossip section only contains information about a few random nodes among the set of nodes known to the sender. The number of nodes mentioned in a gossip section is proportional to the cluster size. - -For every node added in the gossip section the following fields are reported: - -* Node ID. -* IP and port of the node. -* Node flags. - -Gossip sections allow receiving nodes to get information about the state of other nodes from the point of view of the sender. This is useful both for failure detection and to discover other nodes in the cluster. - -### Failure detection - -Valkey Cluster failure detection is used to recognize when a primary or replica node is no longer reachable by the majority of nodes and then respond by promoting a replica to the role of primary. When replica promotion is not possible the cluster is put in an error state to stop receiving queries from clients. - -As already mentioned, every node takes a list of flags associated with other known nodes. There are two flags that are used for failure detection that are called `PFAIL` and `FAIL`. `PFAIL` means *Possible failure*, and is a non-acknowledged failure type. `FAIL` means that a node is failing and that this condition was confirmed by a majority of primaries within a fixed amount of time. - -**PFAIL flag:** - -A node flags another node with the `PFAIL` flag when the node is not reachable for more than `NODE_TIMEOUT` time. Both primary and replica nodes can flag another node as `PFAIL`, regardless of its type. - -The concept of non-reachability for a Valkey Cluster node is that we have an **active ping** (a ping that we sent for which we have yet to get a reply) pending for longer than `NODE_TIMEOUT`. For this mechanism to work the `NODE_TIMEOUT` must be large compared to the network round trip time. In order to add reliability during normal operations, nodes will try to reconnect with other nodes in the cluster as soon as half of the `NODE_TIMEOUT` has elapsed without a reply to a ping. This mechanism ensures that connections are kept alive so broken connections usually won't result in false failure reports between nodes. - -**FAIL flag:** - -The `PFAIL` flag alone is just local information every node has about other nodes, but it is not sufficient to trigger a replica promotion. For a node to be considered down the `PFAIL` condition needs to be escalated to a `FAIL` condition. - -As outlined in the node heartbeats section of this document, every node sends gossip messages to every other node including the state of a few random known nodes. Every node eventually receives a set of node flags for every other node. This way every node has a mechanism to signal other nodes about failure conditions they have detected. - -A `PFAIL` condition is escalated to a `FAIL` condition when the following set of conditions are met: - -* Some node, that we'll call A, has another node B flagged as `PFAIL`. -* Node A collected, via gossip sections, information about the state of B from the point of view of the majority of primaries in the cluster. -* The majority of primaries signaled the `PFAIL` or `FAIL` condition within `NODE_TIMEOUT * FAIL_REPORT_VALIDITY_MULT` time. (The validity factor is set to 2 in the current implementation, so this is just two times the `NODE_TIMEOUT` time). - -If all the above conditions are true, Node A will: - -* Mark the node as `FAIL`. -* Send a `FAIL` message (as opposed to a `FAIL` condition within a heartbeat message) to all the reachable nodes. - -The `FAIL` message will force every receiving node to mark the node in `FAIL` state, whether or not it already flagged the node in `PFAIL` state. - -Note that *the FAIL flag is mostly one way*. That is, a node can go from `PFAIL` to `FAIL`, but a `FAIL` flag can only be cleared in the following situations: - -* The node is already reachable and is a replica. In this case the `FAIL` flag can be cleared as replicas are not failed over. -* The node is already reachable and is a primary not serving any slot. In this case the `FAIL` flag can be cleared as primaries without slots do not really participate in the cluster and are waiting to be configured in order to join the cluster. -* The node is already reachable and is a primary, but a long time (N times the `NODE_TIMEOUT`) has elapsed without any detectable replica promotion. It's better for it to rejoin the cluster and continue in this case. - -It is useful to note that while the `PFAIL` -> `FAIL` transition uses a form of agreement, the agreement used is weak: - -1. Nodes collect views of other nodes over some time period, so even if the majority of primary nodes need to "agree", actually this is just state that we collected from different nodes at different times and we are not sure, nor we require, that at a given moment the majority of primaries agreed. However we discard failure reports which are old, so the failure was signaled by the majority of primaries within a window of time. -2. While every node detecting the `FAIL` condition will force that condition on other nodes in the cluster using the `FAIL` message, there is no way to ensure the message will reach all the nodes. For instance a node may detect the `FAIL` condition and because of a partition will not be able to reach any other node. - -However the Valkey Cluster failure detection has a liveness requirement: eventually all the nodes should agree about the state of a given node. There are two cases that can originate from split brain conditions. Either some minority of nodes believe the node is in `FAIL` state, or a minority of nodes believe the node is not in `FAIL` state. In both the cases eventually the cluster will have a single view of the state of a given node: - -**Case 1**: If a majority of primaries have flagged a node as `FAIL`, because of failure detection and the *chain effect* it generates, every other node will eventually flag the primary as `FAIL`, since in the specified window of time enough failures will be reported. - -**Case 2**: When only a minority of primaries have flagged a node as `FAIL`, the replica promotion will not happen (as it uses a more formal algorithm that makes sure everybody knows about the promotion eventually) and every node will clear the `FAIL` state as per the `FAIL` state clearing rules above (i.e. no promotion after N times the `NODE_TIMEOUT` has elapsed). - -**The `FAIL` flag is only used as a trigger to run the safe part of the algorithm** for the replica promotion. In theory a replica may act independently and start a replica promotion when its primary is not reachable, and wait for the primaries to refuse to provide the acknowledgment if the primary is actually reachable by the majority. However the added complexity of the `PFAIL -> FAIL` state, the weak agreement, and the `FAIL` message forcing the propagation of the state in the shortest amount of time in the reachable part of the cluster, have practical advantages. Because of these mechanisms, usually all the nodes will stop accepting writes at about the same time if the cluster is in an error state. This is a desirable feature from the point of view of applications using Valkey Cluster. Also erroneous election attempts initiated by replicas that can't reach its primary due to local problems (the primary is otherwise reachable by the majority of other primary nodes) are avoided. - -## Configuration handling, propagation, and failovers - -### Cluster current epoch - -Valkey Cluster uses a concept similar to the Raft algorithm "term". In Valkey Cluster the term is called epoch instead, and it is used in order to give incremental versioning to events. When multiple nodes provide conflicting information, it becomes possible for another node to understand which state is the most up to date. - -The `currentEpoch` is a 64 bit unsigned number. - -At node creation every Valkey Cluster node, both replicas and primary nodes, set the `currentEpoch` to 0. - -Every time a packet is received from another node, if the epoch of the sender (part of the cluster bus messages header) is greater than the local node epoch, the `currentEpoch` is updated to the sender epoch. - -Because of these semantics, eventually all the nodes will agree to the greatest `currentEpoch` in the cluster. - -This information is used when the state of the cluster is changed and a node seeks agreement in order to perform some action. - -Currently this happens only during replica promotion, as described in the next section. Basically the epoch is a logical clock for the cluster and dictates that given information wins over one with a smaller epoch. - -### Configuration epoch - -Every primary always advertises its `configEpoch` in ping and pong packets along with a bitmap advertising the set of slots it serves. - -The `configEpoch` is set to zero in primaries when a new node is created. - -A new `configEpoch` is created during replica election. Replicas trying to replace -failing primaries increment their epoch and try to get authorization from -a majority of primaries. When a replica is authorized, a new unique `configEpoch` -is created and the replica turns into a primary using the new `configEpoch`. - -As explained in the next sections the `configEpoch` helps to resolve conflicts when different nodes claim divergent configurations (a condition that may happen because of network partitions and node failures). - -Replica nodes also advertise the `configEpoch` field in ping and pong packets, but in the case of replicas the field represents the `configEpoch` of its primary as of the last time they exchanged packets. This allows other instances to detect when a replica has an old configuration that needs to be updated (primary nodes will not grant votes to replicas with an old configuration). - -Every time the `configEpoch` changes for some known node, it is permanently stored in the nodes.conf file by all the nodes that receive this information. The same also happens for the `currentEpoch` value. These two variables are guaranteed to be saved and `fsync-ed` to disk when updated before a node continues its operations. - -The `configEpoch` values generated using a simple algorithm during failovers -are guaranteed to be new, incremental, and unique. - -### Replica election and promotion - -Replica election and promotion is handled by replica nodes, with the help of the primary nodes that vote for the replica to promote. -A replica election happens when a primary is in `FAIL` state from the point of view of at least one of its replicas that has the prerequisites in order to become a primary. - -In order for a replica to promote itself to primary, it needs to start an election and win it. All the replicas for a given primary can start an election if the primary is in `FAIL` state, however only one replica will win the election and promote itself to primary. - -A replica starts an election when the following conditions are met: - -* The replica's primary is in `FAIL` state. -* The primary was serving a non-zero number of slots. -* The replica replication link was disconnected from the primary for no longer than a given amount of time, in order to ensure the promoted replica's data is reasonably fresh. This time is user configurable. - -In order to be elected, the first step for a replica is to increment its `currentEpoch` counter, and request votes from primary instances. - -Votes are requested by the replica by broadcasting a `FAILOVER_AUTH_REQUEST` packet to every primary node of the cluster. Then it waits for a maximum time of two times the `NODE_TIMEOUT` for replies to arrive (but always for at least 2 seconds). - -Once a primary has voted for a given replica, replying positively with a `FAILOVER_AUTH_ACK`, it can no longer vote for another replica of the same primary for a period of `NODE_TIMEOUT * 2`. In this period it will not be able to reply to other authorization requests for the same primary. This is not needed to guarantee safety, but useful for preventing multiple replicas from getting elected (even if with a different `configEpoch`) at around the same time, which is usually not wanted. - -A replica discards any `AUTH_ACK` replies with an epoch that is less than the `currentEpoch` at the time the vote request was sent. This ensures it doesn't count votes intended for a previous election. - -Once the replica receives ACKs from the majority of primaries, it wins the election. -Otherwise if the majority is not reached within the period of two times `NODE_TIMEOUT` (but always at least 2 seconds), the election is aborted and a new one will be tried again after `NODE_TIMEOUT * 4` (and always at least 4 seconds). - -### Replica rank - -As soon as a primary is in `FAIL` state, a replica waits a short period of time before trying to get elected. That delay is computed as follows: - - DELAY = 500 milliseconds + random delay between 0 and 500 milliseconds + - REPLICA_RANK * 1000 milliseconds. - -The fixed delay ensures that we wait for the `FAIL` state to propagate across the cluster, otherwise the replica may try to get elected while the primaries are still unaware of the `FAIL` state, refusing to grant their vote. - -The random delay is used to desynchronize replicas so they're unlikely to start an election at the same time. - -The `REPLICA_RANK` is the rank of this replica regarding the amount of replication data it has processed from the primary. -Replicas exchange messages when the primary is failing in order to establish a (best effort) rank: -the replica with the most updated replication offset is at rank 0, the second most updated at rank 1, and so forth. -In this way the most updated replicas try to get elected before others. - -Rank order is not strictly enforced; if a replica of higher rank fails to be -elected, the others will try shortly. - -Once a replica wins the election, it obtains a new unique and incremental `configEpoch` which is higher than that of any other existing primary. It starts advertising itself as primary in ping and pong packets, providing the set of served slots with a `configEpoch` that will win over the past ones. - -In order to speedup the reconfiguration of other nodes, a pong packet is broadcast to all the nodes of the cluster. Currently unreachable nodes will eventually be reconfigured when they receive a ping or pong packet from another node or will receive an `UPDATE` packet from another node if the information it publishes via heartbeat packets are detected to be out of date. - -The other nodes will detect that there is a new primary serving the same slots served by the old primary but with a greater `configEpoch`, and will upgrade their configuration. Replicas of the old primary (or the failed over primary if it rejoins the cluster) will not just upgrade the configuration but will also reconfigure to replicate from the new primary. How nodes rejoining the cluster are configured is explained in the next sections. - -### Masters reply to replica vote request - -In the previous section, we discussed how replicas try to get elected. This section explains what happens from the point of view of a primary that is requested to vote for a given replica. - -Masters receive requests for votes in form of `FAILOVER_AUTH_REQUEST` requests from replicas. - -For a vote to be granted the following conditions need to be met: - -1. A primary only votes a single time for a given epoch, and refuses to vote for older epochs: every primary has a lastVoteEpoch field and will refuse to vote again as long as the `currentEpoch` in the auth request packet is not greater than the lastVoteEpoch. When a primary replies positively to a vote request, the lastVoteEpoch is updated accordingly, and safely stored on disk. -2. A primary votes for a replica only if the replica's primary is flagged as `FAIL`. -3. Auth requests with a `currentEpoch` that is less than the primary `currentEpoch` are ignored. Because of this the primary reply will always have the same `currentEpoch` as the auth request. If the same replica asks again to be voted, incrementing the `currentEpoch`, it is guaranteed that an old delayed reply from the primary can not be accepted for the new vote. - -Example of the issue caused by not using rule number 3: - -Primary `currentEpoch` is 5, lastVoteEpoch is 1 (this may happen after a few failed elections) - -* Replica `currentEpoch` is 3. -* Replica tries to be elected with epoch 4 (3+1), primary replies with an ok with `currentEpoch` 5, however the reply is delayed. -* Replica will try to be elected again, at a later time, with epoch 5 (4+1), the delayed reply reaches the replica with `currentEpoch` 5, and is accepted as valid. - -4. Primaries don't vote for a replica of the same primary before `NODE_TIMEOUT * 2` has elapsed if a replica of that primary was already voted for. This is not strictly required as it is not possible for two replicas to win the election in the same epoch. However, in practical terms it ensures that when a replica is elected it has plenty of time to inform the other replicas and avoid the possibility that another replica will win a new election, performing an unnecessary second failover. -5. Primaries make no effort to select the best replica in any way. If the replica's primary is in `FAIL` state and the primary did not vote in the current term, a positive vote is granted. The best replica is the most likely to start an election and win it before the other replicas, since it will usually be able to start the voting process earlier because of its *higher rank* as explained in the previous section. -6. When a primary refuses to vote for a given replica there is no negative response, the request is simply ignored. -7. Primaries don't vote for replicas sending a `configEpoch` that is less than any `configEpoch` in the primary table for the slots claimed by the replica. Remember that the replica sends the `configEpoch` of its primary, and the bitmap of the slots served by its primary. This means that the replica requesting the vote must have a configuration for the slots it wants to failover that is newer or equal the one of the primary granting the vote. - -### Practical example of configuration epoch usefulness during partitions - -This section illustrates how the epoch concept is used to make the replica promotion process more resistant to partitions. - -* A primary is no longer reachable indefinitely. The primary has three replicas A, B, C. -* Replica A wins the election and is promoted to primary. -* A network partition makes A not available for the majority of the cluster. -* Replica B wins the election and is promoted as primary. -* A partition makes B not available for the majority of the cluster. -* The previous partition is fixed, and A is available again. - -At this point B is down and A is available again with a role of primary (actually `UPDATE` messages would reconfigure it promptly, but here we assume all `UPDATE` messages were lost). At the same time, replica C will try to get elected in order to fail over B. This is what happens: - -1. C will try to get elected and will succeed, since for the majority of primaries its primary is actually down. It will obtain a new incremental `configEpoch`. -2. A will not be able to claim to be the primary for its hash slots, because the other nodes already have the same hash slots associated with a higher configuration epoch (the one of B) compared to the one published by A. -3. So, all the nodes will upgrade their table to assign the hash slots to C, and the cluster will continue its operations. - -As you'll see in the next sections, a stale node rejoining a cluster -will usually get notified as soon as possible about the configuration change -because as soon as it pings any other node, the receiver will detect it -has stale information and will send an `UPDATE` message. - -### Hash slots configuration propagation - -An important part of Valkey Cluster is the mechanism used to propagate the information about which cluster node is serving a given set of hash slots. This is vital to both the startup of a fresh cluster and the ability to upgrade the configuration after a replica was promoted to serve the slots of its failing primary. - -The same mechanism allows nodes partitioned away for an indefinite amount of -time to rejoin the cluster in a sensible way. - -There are two ways hash slot configurations are propagated: - -1. Heartbeat messages. The sender of a ping or pong packet always adds information about the set of hash slots it (or its primary, if it is a replica) serves. -2. `UPDATE` messages. Since in every heartbeat packet there is information about the sender `configEpoch` and set of hash slots served, if a receiver of a heartbeat packet finds the sender information is stale, it will send a packet with new information, forcing the stale node to update its info. - -The receiver of a heartbeat or `UPDATE` message uses certain simple rules in -order to update its table mapping hash slots to nodes. When a new Valkey Cluster node is created, its local hash slot table is simply initialized to `NULL` entries so that each hash slot is not bound or linked to any node. This looks similar to the following: - -``` -0 -> NULL -1 -> NULL -2 -> NULL -... -16383 -> NULL -``` - -The first rule followed by a node in order to update its hash slot table is the following: - -**Rule 1**: If a hash slot is unassigned (set to `NULL`), and a known node claims it, I'll modify my hash slot table and associate the claimed hash slots to it. - -So if we receive a heartbeat from node A claiming to serve hash slots 1 and 2 with a configuration epoch value of 3, the table will be modified to: - -``` -0 -> NULL -1 -> A [3] -2 -> A [3] -... -16383 -> NULL -``` - -When a new cluster is created, a system administrator needs to manually assign (using the `CLUSTER ADDSLOTS` command, via the valkey-cli command line tool, or by any other means) the slots served by each primary node only to the node itself, and the information will rapidly propagate across the cluster. - -However this rule is not enough. We know that hash slot mapping can change -during two events: - -1. A replica replaces its primary during a failover. -2. A slot is resharded from a node to a different one. - -For now let's focus on failovers. When a replica fails over its primary, it obtains -a configuration epoch which is guaranteed to be greater than the one of its -primary (and more generally greater than any other configuration epoch -generated previously). For example node B, which is a replica of A, may failover -A with configuration epoch of 4. It will start to send heartbeat packets -(the first time mass-broadcasting cluster-wide) and because of the following -second rule, receivers will update their hash slot tables: - -**Rule 2**: If a hash slot is already assigned, and a known node is advertising it using a `configEpoch` that is greater than the `configEpoch` of the primary currently associated with the slot, it'll rebind the hash slot to the new node. - -So after receiving messages from B that claim to serve hash slots 1 and 2 with configuration epoch of 4, the receivers will update their table in the following way: - -``` -0 -> NULL -1 -> B [4] -2 -> B [4] -... -16383 -> NULL -``` - -Liveness property: because of the second rule, eventually all nodes in the cluster will agree that the owner of a slot is the one with the greatest `configEpoch` among the nodes advertising it. - -This mechanism in Valkey Cluster is called **last failover wins**. - -The same happens during resharding. When a node importing a hash slot completes -the import operation, its configuration epoch is incremented to make sure the -change will be propagated throughout the cluster. - -### UPDATE messages, a closer look - -With the previous section in mind, it is easier to see how update messages -work. Node A may rejoin the cluster after some time. It will send heartbeat -packets where it claims it serves hash slots 1 and 2 with configuration epoch -of 3. All the receivers with updated information will instead see that -the same hash slots are associated with node B having a higher configuration -epoch. Because of this they'll send an `UPDATE` message to A with the new -configuration for the slots. A will update its configuration because of the -**rule 2** above. - -### How nodes rejoin the cluster - -The same basic mechanism is used when a node rejoins a cluster. -Continuing with the example above, node A will be notified -that hash slots 1 and 2 are now served by B. Assuming that these two were -the only hash slots served by A, the count of hash slots served by A will -drop to 0! So A will **reconfigure to be a replica of the new primary**. - -The actual rule followed is a bit more complex than this. In general it may -happen that A rejoins after a lot of time, in the meantime it may happen that -hash slots originally served by A are served by multiple nodes, for example -hash slot 1 may be served by B, and hash slot 2 by C. - -So the actual *Valkey Cluster node role switch rule* is: **A primary node will change its configuration to replicate (be a replica of) the node that stole its last hash slot**. - -During reconfiguration, eventually the number of served hash slots will drop to zero, and the node will reconfigure accordingly. Note that in the base case this just means that the old primary will be a replica of the replica that replaced it after a failover. However in the general form the rule covers all possible cases. - -Replicas do exactly the same: they reconfigure to replicate the node that -stole the last hash slot of its former primary. - -### Replica migration - -Valkey Cluster implements a concept called *replica migration* in order to -improve the availability of the system. The idea is that in a cluster with -a primary-replica setup, if the map between replicas and primaries is fixed -availability is limited over time if multiple independent failures of single -nodes happen. - -For example in a cluster where every primary has a single replica, the cluster -can continue operations as long as either the primary or the replica fail, but not -if both fail the same time. However there is a class of failures that are -the independent failures of single nodes caused by hardware or software issues -that can accumulate over time. For example: - -* Master A has a single replica A1. -* Master A fails. A1 is promoted as new primary. -* Three hours later A1 fails in an independent manner (unrelated to the failure of A). No other replica is available for promotion since node A is still down. The cluster cannot continue normal operations. - -If the map between primaries and replicas is fixed, the only way to make the cluster -more resistant to the above scenario is to add replicas to every primary, however -this is costly as it requires more instances of Valkey to be executed, more -memory, and so forth. - -An alternative is to create an asymmetry in the cluster, and let the cluster -layout automatically change over time. For example the cluster may have three -primaries A, B, C. A and B have a single replica each, A1 and B1. However, the primary -C is different and has two replicas: C1 and C2. - -Replica migration is the process of automatic reconfiguration of a replica -in order to *migrate* to a primary that has no longer coverage (no working -replicas). With replica migration the scenario mentioned above turns into the -following: - -* Master A fails. A1 is promoted. -* C2 migrates as replica of A1, that is otherwise not backed by any replica. -* Three hours later A1 fails as well. -* C2 is promoted as a new primary to replace A1. -* The cluster can continue the operations. - -### Replica migration algorithm - -The migration algorithm does not use any form of agreement since the replica -layout in a Valkey Cluster is not part of the cluster configuration that needs -to be consistent and/or versioned with config epochs. Instead it uses an -algorithm to avoid mass-migration of replicas when a primary is not backed. -The algorithm guarantees that eventually (once the cluster configuration is -stable) every primary will be backed by at least one replica. - -This is how the algorithm works. To start we need to define what is a -*good replica* in this context: a good replica is a replica not in `FAIL` state -from the point of view of a given node. - -The execution of the algorithm is triggered in every replica that detects that -there is at least a single primary without good replicas. However among all the -replicas detecting this condition, only a subset should act. This subset is -actually often a single replica unless different replicas have in a given moment -a slightly different view of the failure state of other nodes. - -The *acting replica* is the replica among the primaries with the maximum number -of attached replicas, that is not in FAIL state and has the smallest node ID. - -So for example if there are 10 primaries with 1 replica each, and 2 primaries with -5 replicas each, the replica that will try to migrate is - among the 2 primaries -having 5 replicas - the one with the lowest node ID. Given that no agreement -is used, it is possible that when the cluster configuration is not stable, -a race condition occurs where multiple replicas believe themselves to be -the non-failing replica with the lower node ID (it is unlikely for this to happen -in practice). If this happens, the result is multiple replicas migrating to the -same primary, which is harmless. If the race happens in a way that will leave -the ceding primary without replicas, as soon as the cluster is stable again -the algorithm will be re-executed again and will migrate a replica back to -the original primary. - -Eventually every primary will be backed by at least one replica. However, -the normal behavior is that a single replica migrates from a primary with -multiple replicas to an orphaned primary. - -The algorithm is controlled by a user-configurable parameter called -`cluster-migration-barrier`: the number of good replicas a primary -must be left with before a replica can migrate away. For example, if this -parameter is set to 2, a replica can try to migrate only if its primary remains -with two working replicas. - -### configEpoch conflicts resolution algorithm - -When new `configEpoch` values are created via replica promotion during -failovers, they are guaranteed to be unique. - -However there are two distinct events where new configEpoch values are -created in an unsafe way, just incrementing the local `currentEpoch` of -the local node and hoping there are no conflicts at the same time. -Both the events are system-administrator triggered: - -1. `CLUSTER FAILOVER` command with `TAKEOVER` option is able to manually promote a replica node into a primary *without the majority of primaries being available*. This is useful, for example, in multi data center setups. -2. Migration of slots for cluster rebalancing also generates new configuration epochs inside the local node without agreement for performance reasons. - -Specifically, during manual resharding, when a hash slot is migrated from -a node A to a node B, the resharding program will force B to upgrade -its configuration to an epoch which is the greatest found in the cluster, -plus 1 (unless the node is already the one with the greatest configuration -epoch), without requiring agreement from other nodes. -Usually a real world resharding involves moving several hundred hash slots -(especially in small clusters). Requiring an agreement to generate new -configuration epochs during resharding, for each hash slot moved, is -inefficient. Moreover it requires a fsync in each of the cluster nodes -every time in order to store the new configuration. Because of the way it is -performed instead, we only need a new config epoch when the first hash slot is moved, -making it much more efficient in production environments. - -However because of the two cases above, it is possible (though unlikely) to end -with multiple nodes having the same configuration epoch. A resharding operation -performed by the system administrator, and a failover happening at the same -time (plus a lot of bad luck) could cause `currentEpoch` collisions if -they are not propagated fast enough. - -Moreover, software bugs and filesystem corruptions can also contribute -to multiple nodes having the same configuration epoch. - -When primaries serving different hash slots have the same `configEpoch`, there -are no issues. It is more important that replicas failing over a primary have -unique configuration epochs. - -That said, manual interventions or resharding may change the cluster -configuration in different ways. The Valkey Cluster main liveness property -requires that slot configurations always converge, so under every circumstance -we really want all the primary nodes to have a different `configEpoch`. - -In order to enforce this, **a conflict resolution algorithm** is used in the -event that two nodes end up with the same `configEpoch`. - -* IF a primary node detects another primary node is advertising itself with -the same `configEpoch`. -* AND IF the node has a lexicographically smaller Node ID compared to the other node claiming the same `configEpoch`. -* THEN it increments its `currentEpoch` by 1, and uses it as the new `configEpoch`. - -If there are any set of nodes with the same `configEpoch`, all the nodes but the one with the greatest Node ID will move forward, guaranteeing that, eventually, every node will pick a unique configEpoch regardless of what happened. - -This mechanism also guarantees that after a fresh cluster is created, all -nodes start with a different `configEpoch` (even if this is not actually -used) since `valkey-cli` makes sure to use `CLUSTER SET-CONFIG-EPOCH` at startup. -However if for some reason a node is left misconfigured, it will update -its configuration to a different configuration epoch automatically. - -### Node resets - -Nodes can be software reset (without restarting them) in order to be reused -in a different role or in a different cluster. This is useful in normal -operations, in testing, and in cloud environments where a given node can -be reprovisioned to join a different set of nodes to enlarge or create a new -cluster. - -In Valkey Cluster nodes are reset using the `CLUSTER RESET` command. The -command is provided in two variants: - -* `CLUSTER RESET SOFT` -* `CLUSTER RESET HARD` - -The command must be sent directly to the node to reset. If no reset type is -provided, a soft reset is performed. - -The following is a list of operations performed by a reset: - -1. Soft and hard reset: If the node is a replica, it is turned into a primary, and its dataset is discarded. If the node is a primary and contains keys the reset operation is aborted. -2. Soft and hard reset: All the slots are released, and the manual failover state is reset. -3. Soft and hard reset: All the other nodes in the nodes table are removed, so the node no longer knows any other node. -4. Hard reset only: `currentEpoch`, `configEpoch`, and `lastVoteEpoch` are set to 0. -5. Hard reset only: the Node ID is changed to a new random ID. - -Master nodes with non-empty data sets can't be reset (since normally you want to reshard data to the other nodes). However, under special conditions when this is appropriate (e.g. when a cluster is totally destroyed with the intent of creating a new one), `FLUSHALL` must be executed before proceeding with the reset. - -### Removing nodes from a cluster - -It is possible to practically remove a node from an existing cluster by -resharding all its data to other nodes (if it is a primary node) and -shutting it down. However, the other nodes will still remember its node -ID and address, and will attempt to connect with it. - -For this reason, when a node is removed we want to also remove its entry -from all the other nodes tables. This is accomplished by using the -`CLUSTER FORGET ` command. - -The command does two things: - -1. It removes the node with the specified node ID from the nodes table. -2. It sets a 60 second ban which prevents a node with the same node ID from being re-added. - -The second operation is needed because Valkey Cluster uses gossip in order to auto-discover nodes, so removing the node X from node A, could result in node B gossiping about node X to A again. Because of the 60 second ban, the Valkey Cluster administration tools have 60 seconds in order to remove the node from all the nodes, preventing the re-addition of the node due to auto discovery. - -Further information is available in the `CLUSTER FORGET` documentation. - -## Publish/Subscribe - -In a Valkey Cluster, clients can subscribe to every node, and can also -publish to every other node. The cluster will make sure that published -messages are forwarded as needed. - -The clients can send SUBSCRIBE to any node and can also send PUBLISH to any node. -It will simply broadcast each published message to all other nodes. - -Redis OSS 7.0 and later features sharded pub/sub, in which shard channels are assigned to slots by the same algorithm used to assign keys to slots. -A shard message must be sent to a node that owns the slot the shard channel is hashed to. -The cluster makes sure the published shard messages are forwarded to all nodes in the shard, so clients can subscribe to a shard channel by connecting to either the primary responsible for the slot, or to any of its replicas. - -## Appendix - -### Appendix A: CRC16 reference implementation in ANSI C - - /* - * Copyright 2001-2010 Georges Menie (www.menie.org) - * Copyright 2010 Salvatore Sanfilippo (adapted to Redis coding style) - * All rights reserved. - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the University of California, Berkeley nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - /* CRC16 implementation according to CCITT standards. - * - * Note by @antirez: this is actually the XMODEM CRC 16 algorithm, using the - * following parameters: - * - * Name : "XMODEM", also known as "ZMODEM", "CRC-16/ACORN" - * Width : 16 bit - * Poly : 1021 (That is actually x^16 + x^12 + x^5 + 1) - * Initialization : 0000 - * Reflect Input byte : False - * Reflect Output CRC : False - * Xor constant to output CRC : 0000 - * Output for "123456789" : 31C3 - */ - - static const uint16_t crc16tab[256]= { - 0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7, - 0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef, - 0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,0x72f7,0x62d6, - 0x9339,0x8318,0xb37b,0xa35a,0xd3bd,0xc39c,0xf3ff,0xe3de, - 0x2462,0x3443,0x0420,0x1401,0x64e6,0x74c7,0x44a4,0x5485, - 0xa56a,0xb54b,0x8528,0x9509,0xe5ee,0xf5cf,0xc5ac,0xd58d, - 0x3653,0x2672,0x1611,0x0630,0x76d7,0x66f6,0x5695,0x46b4, - 0xb75b,0xa77a,0x9719,0x8738,0xf7df,0xe7fe,0xd79d,0xc7bc, - 0x48c4,0x58e5,0x6886,0x78a7,0x0840,0x1861,0x2802,0x3823, - 0xc9cc,0xd9ed,0xe98e,0xf9af,0x8948,0x9969,0xa90a,0xb92b, - 0x5af5,0x4ad4,0x7ab7,0x6a96,0x1a71,0x0a50,0x3a33,0x2a12, - 0xdbfd,0xcbdc,0xfbbf,0xeb9e,0x9b79,0x8b58,0xbb3b,0xab1a, - 0x6ca6,0x7c87,0x4ce4,0x5cc5,0x2c22,0x3c03,0x0c60,0x1c41, - 0xedae,0xfd8f,0xcdec,0xddcd,0xad2a,0xbd0b,0x8d68,0x9d49, - 0x7e97,0x6eb6,0x5ed5,0x4ef4,0x3e13,0x2e32,0x1e51,0x0e70, - 0xff9f,0xefbe,0xdfdd,0xcffc,0xbf1b,0xaf3a,0x9f59,0x8f78, - 0x9188,0x81a9,0xb1ca,0xa1eb,0xd10c,0xc12d,0xf14e,0xe16f, - 0x1080,0x00a1,0x30c2,0x20e3,0x5004,0x4025,0x7046,0x6067, - 0x83b9,0x9398,0xa3fb,0xb3da,0xc33d,0xd31c,0xe37f,0xf35e, - 0x02b1,0x1290,0x22f3,0x32d2,0x4235,0x5214,0x6277,0x7256, - 0xb5ea,0xa5cb,0x95a8,0x8589,0xf56e,0xe54f,0xd52c,0xc50d, - 0x34e2,0x24c3,0x14a0,0x0481,0x7466,0x6447,0x5424,0x4405, - 0xa7db,0xb7fa,0x8799,0x97b8,0xe75f,0xf77e,0xc71d,0xd73c, - 0x26d3,0x36f2,0x0691,0x16b0,0x6657,0x7676,0x4615,0x5634, - 0xd94c,0xc96d,0xf90e,0xe92f,0x99c8,0x89e9,0xb98a,0xa9ab, - 0x5844,0x4865,0x7806,0x6827,0x18c0,0x08e1,0x3882,0x28a3, - 0xcb7d,0xdb5c,0xeb3f,0xfb1e,0x8bf9,0x9bd8,0xabbb,0xbb9a, - 0x4a75,0x5a54,0x6a37,0x7a16,0x0af1,0x1ad0,0x2ab3,0x3a92, - 0xfd2e,0xed0f,0xdd6c,0xcd4d,0xbdaa,0xad8b,0x9de8,0x8dc9, - 0x7c26,0x6c07,0x5c64,0x4c45,0x3ca2,0x2c83,0x1ce0,0x0cc1, - 0xef1f,0xff3e,0xcf5d,0xdf7c,0xaf9b,0xbfba,0x8fd9,0x9ff8, - 0x6e17,0x7e36,0x4e55,0x5e74,0x2e93,0x3eb2,0x0ed1,0x1ef0 - }; - - uint16_t crc16(const char *buf, int len) { - int counter; - uint16_t crc = 0; - for (counter = 0; counter < len; counter++) - crc = (crc<<8) ^ crc16tab[((crc>>8) ^ *buf++)&0x00FF]; - return crc; - } diff --git a/topics/cluster-tutorial.md b/topics/cluster-tutorial.md deleted file mode 100644 index f770c791..00000000 --- a/topics/cluster-tutorial.md +++ /dev/null @@ -1,1066 +0,0 @@ ---- -title: Cluster tutorial -description: Horizontal scaling with Valkey Cluster ---- - -Valkey scales horizontally with a deployment topology called Valkey Cluster. -This topic will teach you how to set up, test, and operate Valkey Cluster in production. -You will learn about the availability and consistency characteristics of Valkey Cluster from the end user's point of view. -Valkey Cluster handles failover itself and doesn't use [Valkey Sentinel](sentinel.md), which is a separate way to get high availability for Valkey without sharding. - -If you plan to run a production Valkey Cluster deployment or want to understand better how Valkey Cluster works internally, consult the [Valkey Cluster specification](cluster-spec.md). - -## Valkey Cluster 101 - -Valkey Cluster provides a way to run a Valkey installation where data is automatically sharded across multiple Valkey nodes. -Valkey Cluster also provides some degree of availability during partitions—in practical terms, the ability to continue operations when some nodes fail or are unable to communicate. -However, the cluster will become unavailable in the event of larger failures (for example, when the majority of primaries are unavailable). - -So, with Valkey Cluster, you get the ability to: - -* Automatically split your dataset among multiple nodes. -* Continue operations when a subset of the nodes are experiencing failures or are unable to communicate with the rest of the cluster. - -#### Valkey Cluster TCP ports - -Every Valkey Cluster node requires two open TCP connections: a Valkey TCP port used to serve clients, e.g., 6379, and second port known as the _cluster bus port_. -By default, the cluster bus port is set by adding 10000 to the data port (e.g., 16379); however, you can override this in the `cluster-port` configuration. - -Cluster bus is a node-to-node communication channel that uses a binary protocol, which is more suited to exchanging information between nodes due to -little bandwidth and processing time. -Nodes use the cluster bus for failure detection, configuration updates, failover authorization, and so forth. -Clients should never try to communicate with the cluster bus port, but rather use the Valkey command port. -However, make sure you open both ports in your firewall, otherwise Valkey cluster nodes won't be able to communicate. - -For a Valkey Cluster to work properly you need, for each node: - -1. The client communication port (usually 6379) used to communicate with clients and be open to all the clients that need to reach the cluster, plus all the other cluster nodes that use the client port for key migrations. -2. The cluster bus port must be reachable from all the other cluster nodes. - -If you don't open both TCP ports, your cluster will not work as expected. - -> **Cluster Bus Security Warning:** The Valkey cluster bus protocol (running on client port + 10000) does not perform application-layer authentication of messages by default. It blindly trusts all incoming traffic on this port. To prevent unauthorized nodes from taking over the cluster (e.g., hijacking slots or executing denial-of-service payloads), you must secure the cluster bus using one of the following: -> -> * **Network-level isolation:** Strict firewall rules or Security Groups that only permit incoming traffic on the cluster bus port from the IP addresses of other legitimate cluster nodes. -> * **Mutual TLS (mTLS):** Enable TLS for the cluster bus (`tls-cluster yes`) and configure mutual certificate authentication so that only nodes with valid certificates can establish connections. - -#### Valkey Cluster with containers and NAT - -Containers and other environments using Network Address Translation rely on _port -mapping_: a program running inside a container may be reachable from the outside on a -different port than the one it believes it is using. This is useful for running -multiple containers using the same ports, at the same time, on the same host. - -Because a Valkey Cluster node publishes its own address to the other nodes, such a -remapping has to be made known to it. Configure each node to announce the address and -ports on which the others can actually reach it: - - cluster-announce-ip 10.1.1.5 - cluster-announce-port 6379 - cluster-announce-bus-port 6380 - -The announced information is published in the cluster bus messages, so the other -nodes can map the node to its reachable address. Announcing the bus port matters -because Valkey otherwise uses `cluster-port`, if configured, or the client port -plus 10000, which doesn't hold when the ports are remapped. - -A few related options cover more specific setups: - -* `cluster-announce-tls-port` announces the TLS port. If it is omitted while - `tls-cluster` is enabled, `cluster-announce-port` is taken to be the TLS port. -* `cluster-announce-client-port` and `cluster-announce-client-tls-port` announce the - ports that *clients* should use, for cases where clients reach the node on a - different port than the other nodes do, such as through a load balancer. -* `cluster-announce-client-ipv4` and `cluster-announce-client-ipv6` announce - client-facing addresses. When they are omitted, `cluster-announce-ip` is the - address exposed to clients. - -A node that doesn't announce anything falls back to auto-detecting its own address, -which is the right behavior when no remapping is involved. - -#### Valkey Cluster data sharding - -Valkey Cluster does not use consistent hashing, but a different form of sharding -where every key is conceptually part of what we call a **hash slot**. - -There are 16384 hash slots in Valkey Cluster, and to compute the hash -slot for a given key, we simply take the CRC16 of the key modulo -16384. - -Every node in a Valkey Cluster is responsible for a subset of the hash slots, -so, for example, you may have a cluster with 3 nodes, where: - -* Node A contains hash slots from 0 to 5500. -* Node B contains hash slots from 5501 to 11000. -* Node C contains hash slots from 11001 to 16383. - -This makes it easy to add and remove cluster nodes. For example, if -I want to add a new node D, I need to move some hash slots from nodes A, B, C -to D. Similarly, if I want to remove node A from the cluster, I can just -move the hash slots served by A to B and C. Once node A is empty, -I can remove it from the cluster completely. - -Moving hash slots from a node to another does not require stopping -any operations; therefore, adding and removing nodes, or changing the percentage of hash slots held by a node, requires no downtime. - -Valkey Cluster supports multiple key operations as long as all of the keys involved in a single command execution (or whole transaction, or Lua script -execution) belong to the same hash slot. The user can force multiple keys -to be part of the same hash slot by using a feature called *hash tags*. - -Hash tags are documented in the Valkey Cluster specification, but the gist is -that if there is a substring between {} brackets in a key, only what is -inside the string is hashed. For example, the keys `user:{123}:profile` and `user:{123}:account` are guaranteed to be in the same hash slot because they share the same hash tag. As a result, you can operate on these two keys in the same multi-key operation. - -#### Valkey Cluster primary-replica model - -To remain available when a subset of primary nodes are failing or are -not able to communicate with the majority of nodes, Valkey Cluster uses a -primary-replica model where every hash slot has from 1 (the primary itself) to N -replicas (N-1 additional replica nodes). - -In our example cluster with nodes A, B, C, if node B fails the cluster is not -able to continue, since we no longer have a way to serve hash slots in the -range 5501-11000. - -However, when the cluster is created (or at a later time), we add a replica -node to every primary, so that the final cluster is composed of A, B, C -that are primary nodes, and A1, B1, C1 that are replica nodes. -This way, the system can continue if node B fails. - -Node B1 replicates B, and B fails, the cluster will promote node B1 as the new -primary and will continue to operate correctly. - -However, note that if nodes B and B1 fail at the same time, Valkey Cluster will not be able to continue to operate. - -#### Valkey Cluster consistency guarantees - -Valkey Cluster does not guarantee **strong consistency**. In practical -terms this means that under certain conditions it is possible that Valkey -Cluster will lose writes that were acknowledged by the system to the client. - -The first reason why Valkey Cluster can lose writes is because it uses -asynchronous replication. This means that during writes the following -happens: - -* Your client writes to the primary B. -* The primary B replies OK to your client. -* The primary B propagates the write to its replicas B1, B2 and B3. - -As you can see, B does not wait for an acknowledgement from B1, B2, B3 before -replying to the client, since this would be a prohibitive latency penalty -for Valkey, so if your client writes something, B acknowledges the write, -but crashes before being able to send the write to its replicas, one of the -replicas (that did not receive the write) can be promoted to primary, losing -the write forever. - -This is very similar to what happens with most databases that are -configured to flush data to disk every second, so it is a scenario you -are already able to reason about because of past experiences with traditional -database systems not involving distributed systems. Similarly you can -improve consistency by forcing the database to flush data to disk before -replying to the client, but this usually results in prohibitively low -performance. That would be the equivalent of synchronous replication in -the case of Valkey Cluster. - -Basically, there is a trade-off to be made between performance and consistency. - -Valkey Cluster has support for synchronous writes when absolutely needed, -implemented via the `WAIT` command. This makes losing writes a lot less -likely. However, note that Valkey Cluster does not implement strong consistency -even when synchronous replication is used: it is always possible, under more -complex failure scenarios, that a replica that was not able to receive the write -will be elected as primary. - -There is another notable scenario where Valkey Cluster will lose writes, that -happens during a network partition where a client is isolated with a minority -of instances including at least a primary. - -Take as an example our 6 nodes cluster composed of A, B, C, A1, B1, C1, -with 3 primaries and 3 replicas. There is also a client, that we will call Z1. - -After a partition occurs, it is possible that in one side of the -partition we have A, C, A1, B1, C1, and in the other side we have B and Z1. - -Z1 is still able to write to B, which will accept its writes. If the -partition heals in a very short time, the cluster will continue normally. -However, if the partition lasts enough time for B1 to be promoted to primary -on the majority side of the partition, the writes that Z1 has sent to B -in the meantime will be lost. - -**Note:** -There is a **maximum window** to the amount of writes Z1 will be able -to send to B: if enough time has elapsed for the majority side of the -partition to elect a replica as primary, every primary node in the minority -side will have stopped accepting writes. - -This amount of time is a very important configuration directive of Valkey -Cluster, and is called the **node timeout**. - -After node timeout has elapsed, a primary node is considered to be failing, -and can be replaced by one of its replicas. -Similarly, after node timeout has elapsed without a primary node to be able -to sense the majority of the other primary nodes, it enters an error state -and stops accepting writes. - -## Valkey Cluster configuration parameters - -We are about to create an example cluster deployment. -Before we continue, let's introduce the configuration parameters that Valkey Cluster introduces -in the `valkey.conf` file. - -* **cluster-enabled ``**: If yes, enables Valkey Cluster support in a specific Valkey instance. Otherwise the instance starts as a standalone instance as usual. -* **cluster-config-file ``**: Note that despite the name of this option, this is not a user editable configuration file, but the file where a Valkey Cluster node automatically persists the cluster configuration (the state, basically) every time there is a change, in order to be able to re-read it at startup. The file lists things like the other nodes in the cluster, their state, persistent variables, and so forth. Often this file is rewritten and flushed on disk as a result of some message reception. -* **cluster-node-timeout ``**: The maximum amount of time a Valkey Cluster node can be unavailable, without it being considered as failing. If a primary node is not reachable for more than the specified amount of time, it will be failed over by its replicas. This parameter controls other important things in Valkey Cluster. Notably, every node that can't reach the majority of primary nodes for the specified amount of time, will stop accepting queries. -* **cluster-replica-validity-factor ``**: If set to zero, a replica will always consider itself valid, and will therefore always try to failover a primary, regardless of the amount of time the link between the primary and the replica remained disconnected. If the value is positive, a maximum disconnection time is calculated as the *node timeout* value multiplied by the factor provided with this option, and if the node is a replica, it will not try to start a failover if the primary link was disconnected for more than the specified amount of time. For example, if the node timeout is set to 5 seconds and the validity factor is set to 10, a replica disconnected from the primary for more than 50 seconds will not try to failover its primary. Note that any value different than zero may result in Valkey Cluster being unavailable after a primary failure if there is no replica that is able to failover it. In that case the cluster will return to being available only when the original primary rejoins the cluster. -* **cluster-migration-barrier ``**: Minimum number of replicas a primary will remain connected with, for another replica to migrate to a primary which is no longer covered by any replica. See the appropriate section about replica migration in this tutorial for more information. -* **cluster-require-full-coverage ``**: If this is set to yes, as it is by default, the cluster stops accepting writes if some percentage of the key space is not covered by any node. If the option is set to no, the cluster will still serve queries even if only requests about a subset of keys can be processed. -* **cluster-allow-reads-when-down ``**: If this is set to no, as it is by default, a node in a Valkey Cluster will stop serving all traffic when the cluster is marked as failed, either when a node can't reach a quorum of primaries or when full coverage is not met. This prevents reading potentially inconsistent data from a node that is unaware of changes in the cluster. This option can be set to yes to allow reads from a node during the fail state, which is useful for applications that want to prioritize read availability but still want to prevent inconsistent writes. It can also be used for when using Valkey Cluster with only one or two shards, as it allows the nodes to continue serving writes when a primary fails but automatic failover is impossible. - -## Create and use a Valkey Cluster - -To create and use a Valkey Cluster, follow these steps: - -* [Create a Valkey Cluster](#create-a-valkey-cluster) -* [Interact with the cluster](#interact-with-the-cluster) -* [Write an example app with redis-rb-cluster](#write-an-example-app-with-redis-rb-cluster) -* [Reshard the cluster](#reshard-the-cluster) -* [A more interesting example application](#a-more-interesting-example-application) -* [Test the failover](#test-the-failover) -* [Manual failover](#manual-failover) -* [Add a new node](#add-a-new-node) -* [Remove a node](#remove-a-node) -* [Replica migration](#replica-migration) -* [Upgrade nodes in a Valkey Cluster](#upgrade-nodes-in-a-valkey-cluster) -* [Migrate to Valkey Cluster](#migrate-to-valkey-cluster) - -But, first, familiarize yourself with the requirements for creating a cluster. - -#### Requirements to create a Valkey Cluster - -To create a cluster, the first thing you need is to have a few empty Valkey instances running in _cluster mode_. - -At minimum, set the following directives in the `valkey.conf` file: - -``` -port 7000 -cluster-enabled yes -cluster-config-file nodes.conf -cluster-node-timeout 5000 -appendonly yes -``` - -To enable cluster mode, set the `cluster-enabled` directive to `yes`. -Every instance also contains the path of a file where the -configuration for this node is stored, which by default is `nodes.conf`. -This file is never touched by humans; it is simply generated at startup -by the Valkey Cluster instances, and updated every time it is needed. - -Note that the **minimal cluster** that works as expected must contain -at least three primary nodes. For deployment, we strongly recommend -a six-node cluster, with three primaries and three replicas. - -You can test this locally by creating the following directories named -after the port number of the instance you'll run inside any given directory. - -For example: - -``` -mkdir cluster-test -cd cluster-test -mkdir 7000 7001 7002 7003 7004 7005 -``` - -Create a `valkey.conf` file inside each of the directories, from 7000 to 7005. -As a template for your configuration file just use the small example above, -but make sure to replace the port number `7000` with the right port number -according to the directory name. - - -You can start each instance as follows, each running in a separate terminal tab: - -``` -cd 7000 -valkey-server ./valkey.conf -``` -You'll see from the logs that every node assigns itself a new ID: - - [82462] 26 Nov 11:56:55.329 * No cluster configuration found, I'm 97a3a64667477371c4479320d683e4c8db5858b1 - -This ID will be used forever by this specific instance in order for the instance -to have a unique name in the context of the cluster. Every node -remembers every other node using this IDs, and not by IP or port. -IP addresses and ports may change, but the unique node identifier will never -change for all the life of the node. We call this identifier simply **Node ID**. - -#### Create a Valkey Cluster - -Now that we have a number of instances running, you need to create your cluster by writing some meaningful configuration to the nodes. - -You can configure and execute individual instances manually or use the create-cluster script. -Let's go over how you do it manually. - -To create the cluster, run: - - valkey-cli --cluster create 127.0.0.1:7000 127.0.0.1:7001 \ - 127.0.0.1:7002 127.0.0.1:7003 127.0.0.1:7004 127.0.0.1:7005 \ - --cluster-replicas 1 - -The command used here is **create**, since we want to create a new cluster. -The option `--cluster-replicas 1` means that we want a replica for every primary created. - -The other arguments are the list of addresses of the instances I want to use -to create the new cluster. - -`valkey-cli` will propose a configuration. Accept the proposed configuration by typing **yes**. -The cluster will be configured and *joined*, which means that instances will be -bootstrapped into talking with each other. Finally, if everything has gone well, you'll see a message like this: - - [OK] All 16384 slots covered - -This means that there is at least one primary instance serving each of the -16384 available slots. - -If you don't want to create a Valkey Cluster by configuring and executing -individual instances manually as explained above, there is a much simpler -system (but you'll not learn the same amount of operational details). - -Find the `utils/create-cluster` directory in the Valkey distribution. -There is a script called `create-cluster` inside (same name as the directory -it is contained into), it's a simple bash script. In order to start -a 6 nodes cluster with 3 primaries and 3 replicas just type the following -commands: - -1. `create-cluster start` -2. `create-cluster create` - -Reply to `yes` in step 2 when the `valkey-cli` utility wants you to accept -the cluster layout. - -You can now interact with the cluster, the first node will start at port 30001 -by default. When you are done, stop the cluster with: - -3. `create-cluster stop` - -Please read the `README` inside this directory for more information on how -to run the script. - -#### Interact with the cluster - -To connect to Valkey Cluster, you'll need a cluster-aware Valkey client. -See the documentation for your [client of choice](../clients/) to determine its cluster support. - -You can also test your Valkey Cluster using the `valkey-cli` command line utility: - -``` -$ valkey-cli -c -p 7000 -127.0.0.1:7000> set foo bar --> Redirected to slot [12182] located at 127.0.0.1:7002 -OK -127.0.0.1:7002> set hello world --> Redirected to slot [866] located at 127.0.0.1:7000 -OK -127.0.0.1:7000> get foo --> Redirected to slot [12182] located at 127.0.0.1:7002 -"bar" -127.0.0.1:7002> get hello --> Redirected to slot [866] located at 127.0.0.1:7000 -"world" -``` - -**Note:** -If you created the cluster using the script, your nodes may listen -on different ports, starting from 30001 by default. - -The `valkey-cli` cluster support is very basic, so it always uses the fact that -Valkey Cluster nodes are able to redirect a client to the right node. -A serious client is able to do better than that, and cache the map between -hash slots and nodes addresses, to directly use the right connection to the -right node. The map is refreshed only when something changed in the cluster -configuration, for example after a failover or after the system administrator -changed the cluster layout by adding or removing nodes. - -#### Write an example app with redis-rb-cluster - -Before going forward showing how to operate the Valkey Cluster, doing things -like a failover, or a resharding, we need to create some example application -or at least to be able to understand the semantics of a simple Valkey Cluster -client interaction. - -In this way we can run an example and at the same time try to make nodes -failing, or start a resharding, to see how Valkey Cluster behaves under real -world conditions. It is not very helpful to see what happens while nobody -is writing to the cluster. - -This section explains some basic usage of -[redis-rb-cluster](https://github.com/antirez/redis-rb-cluster) showing two -examples. -The first is the following, and is the -[`example.rb`](https://github.com/antirez/redis-rb-cluster/blob/master/example.rb) -file inside the redis-rb-cluster distribution: - -```ruby -require './cluster' - -if ARGV.length != 2 - startup_nodes = [ - {:host => "127.0.0.1", :port => 7000}, - {:host => "127.0.0.1", :port => 7001} - ] -else - startup_nodes = [ - {:host => ARGV[0], :port => ARGV[1].to_i} - ] -end - -rc = RedisCluster.new(startup_nodes,32,:timeout => 0.1) - -last = false - -while not last - begin - last = rc.get("__last__") - last = 0 if !last - rescue => e - puts "error #{e.to_s}" - sleep 1 - end -end - -((last.to_i+1)..1000000000).each{|x| - begin - rc.set("foo#{x}",x) - puts rc.get("foo#{x}") - rc.set("__last__",x) - rescue => e - puts "error #{e.to_s}" - end - sleep 0.1 -} -``` - -The application does a very simple thing, it sets keys in the form `foo` to `number`, one after the other. So if you run the program the result is the -following stream of commands: - -* SET foo0 0 -* SET foo1 1 -* SET foo2 2 -* And so forth... - -The program looks more complex than it should usually as it is designed to -show errors on the screen instead of exiting with an exception, so every -operation performed with the cluster is wrapped by `begin` `rescue` blocks. - -The **line 14** is the first interesting line in the program. It creates the -Valkey Cluster object, using as argument a list of *startup nodes*, the maximum -number of connections this object is allowed to take against different nodes, -and finally the timeout after a given operation is considered to be failed. - -The startup nodes don't need to be all the nodes of the cluster. The important -thing is that at least one node is reachable. Also note that redis-rb-cluster -updates this list of startup nodes as soon as it is able to connect with the -first node. You should expect such a behavior with any other serious client. - -Now that we have the Valkey Cluster object instance stored in the **rc** variable, -we are ready to use the object like if it was a normal Valkey object instance. - -This is exactly what happens in **line 18 to 26**: when we restart the example -we don't want to start again with `foo0`, so we store the counter inside -Valkey itself. The code above is designed to read this counter, or if the -counter does not exist, to assign it the value of zero. - -However note how it is a while loop, as we want to try again and again even -if the cluster is down and is returning errors. Normal applications don't need -to be so careful. - -**Lines between 28 and 37** start the main loop where the keys are set or -an error is displayed. - -Note the `sleep` call at the end of the loop. In your tests you can remove -the sleep if you want to write to the cluster as fast as possible (relatively -to the fact that this is a busy loop without real parallelism of course, so -you'll get the usually 10k ops/second in the best of the conditions). - -Normally writes are slowed down in order for the example application to be -easier to follow by humans. - -Starting the application produces the following output: - -``` -ruby ./example.rb -1 -2 -3 -4 -5 -6 -7 -8 -9 -^C (I stopped the program here) -``` - -This is not a very interesting program and we'll use a better one in a moment -but we can already see what happens during a resharding when the program -is running. - -#### Reshard the cluster - -Now we are ready to try a cluster resharding. To do this, please -keep the example.rb program running, so that you can see if there is some -impact on the program running. Also, you may want to comment the `sleep` -call to have some more serious write load during resharding. - -Resharding basically means to move hash slots from a set of nodes to another -set of nodes. -Like cluster creation, it is accomplished using the valkey-cli utility. - -To start a resharding, just type: - - valkey-cli --cluster reshard 127.0.0.1:7000 - -You only need to specify a single node, valkey-cli will find the other nodes -automatically. - -Currently valkey-cli is only able to reshard with the administrator support, -you can't just say move 5% of slots from this node to the other one (but -this is pretty trivial to implement). So it starts with questions. The first -is how much of a resharding do you want to do: - - How many slots do you want to move (from 1 to 16384)? - -We can try to reshard 1000 hash slots, that should already contain a non -trivial amount of keys if the example is still running without the sleep -call. - -Then valkey-cli needs to know what is the target of the resharding, that is, -the node that will receive the hash slots. -I'll use the first primary node, that is, 127.0.0.1:7000, but I need -to specify the Node ID of the instance. This was already printed in a -list by valkey-cli, but I can always find the ID of a node with the following -command if I need: - -``` -$ valkey-cli -p 7000 cluster nodes | grep myself -97a3a64667477371c4479320d683e4c8db5858b1 :0 myself,master - 0 0 0 connected 0-5460 -``` - -Ok so my target node is 97a3a64667477371c4479320d683e4c8db5858b1. - -Now you'll get asked from what nodes you want to take those keys. -I'll just type `all` in order to take a bit of hash slots from all the -other primary nodes. - -After the final confirmation you'll see a message for every slot that -valkey-cli is going to move from a node to another, and a dot will be printed -for every actual key moved from one side to the other. - -While the resharding is in progress you should be able to see your -example program running unaffected. You can stop and restart it multiple times -during the resharding if you want. - -At the end of the resharding, you can test the health of the cluster with -the following command: - - valkey-cli --cluster check 127.0.0.1:7000 - -All the slots will be covered as usual, but this time the primary at -127.0.0.1:7000 will have more hash slots, something around 6461. - -Resharding can be performed automatically without the need to manually -enter the parameters in an interactive way. This is possible using a command -line like the following: - - valkey-cli --cluster reshard : --cluster-from --cluster-to --cluster-slots --cluster-yes - -This allows you to build some automatism if you are likely to reshard often, -however currently there is no way for `valkey-cli` to automatically -rebalance the cluster checking the distribution of keys across the cluster -nodes and intelligently moving slots as needed. This feature will be added -in the future. - -The `--cluster-yes` option instructs the cluster manager to automatically answer -"yes" to the command's prompts, allowing it to run in a non-interactive mode. -Note that this option can also be activated by setting the -`REDISCLI_CLUSTER_YES` environment variable. - -#### A more interesting example application - -The example application we wrote early is not very good. -It writes to the cluster in a simple way without even checking if what was -written is the right thing. - -From our point of view the cluster receiving the writes could just always -write the key `foo` to `42` to every operation, and we would not notice at -all. - -So in the `redis-rb-cluster` repository, there is a more interesting application -that is called `consistency-test.rb`. It uses a set of counters, by default 1000, and sends `INCR` commands in order to increment the counters. - -However instead of just writing, the application does two additional things: - -* When a counter is updated using `INCR`, the application remembers the write. -* It also reads a random counter before every write, and check if the value is what we expected it to be, comparing it with the value it has in memory. - -What this means is that this application is a simple **consistency checker**, -and is able to tell you if the cluster lost some write, or if it accepted -a write that we did not receive acknowledgment for. In the first case we'll -see a counter having a value that is smaller than the one we remember, while -in the second case the value will be greater. - -Running the consistency-test application produces a line of output every -second: - -``` -$ ruby consistency-test.rb -925 R (0 err) | 925 W (0 err) | -5030 R (0 err) | 5030 W (0 err) | -9261 R (0 err) | 9261 W (0 err) | -13517 R (0 err) | 13517 W (0 err) | -17780 R (0 err) | 17780 W (0 err) | -22025 R (0 err) | 22025 W (0 err) | -25818 R (0 err) | 25818 W (0 err) | -``` - -The line shows the number of **R**eads and **W**rites performed, and the -number of errors (query not accepted because of errors since the system was -not available). - -If some inconsistency is found, new lines are added to the output. -This is what happens, for example, if I reset a counter manually while -the program is running: - -``` -$ valkey-cli -h 127.0.0.1 -p 7000 set key_217 0 -OK - -(in the other tab I see...) - -94774 R (0 err) | 94774 W (0 err) | -98821 R (0 err) | 98821 W (0 err) | -102886 R (0 err) | 102886 W (0 err) | 114 lost | -107046 R (0 err) | 107046 W (0 err) | 114 lost | -``` - -When I set the counter to 0 the real value was 114, so the program reports -114 lost writes (`INCR` commands that are not remembered by the cluster). - -This program is much more interesting as a test case, so we'll use it -to test the Valkey Cluster failover. - -#### Test the failover - -To trigger the failover, the simplest thing we can do (that is also -the semantically simplest failure that can occur in a distributed system) -is to crash a single process, in our case a single primary. - -**Note:** -During this test, you should take a tab open with the consistency test -application running. - -We can identify a primary and crash it with the following command: - -``` -$ valkey-cli -p 7000 cluster nodes | grep master -3e3a6cb0d9a9a87168e266b0a0b24026c0aae3f0 127.0.0.1:7001 master - 0 1385482984082 0 connected 5960-10921 -2938205e12de373867bf38f1ca29d31d0ddb3e46 127.0.0.1:7002 master - 0 1385482983582 0 connected 11423-16383 -97a3a64667477371c4479320d683e4c8db5858b1 :0 myself,master - 0 0 0 connected 0-5959 10922-11422 -``` - -Ok, so 7000, 7001, and 7002 are primaries. Let's crash node 7002 with the -**DEBUG SEGFAULT** command: - -``` -$ valkey-cli -p 7002 debug segfault -Error: Server closed the connection -``` - -Now we can look at the output of the consistency test to see what it reported. - -``` -18849 R (0 err) | 18849 W (0 err) | -23151 R (0 err) | 23151 W (0 err) | -27302 R (0 err) | 27302 W (0 err) | - -... many error warnings here ... - -29659 R (578 err) | 29660 W (577 err) | -33749 R (578 err) | 33750 W (577 err) | -37918 R (578 err) | 37919 W (577 err) | -42077 R (578 err) | 42078 W (577 err) | -``` - -As you can see during the failover the system was not able to accept 578 reads and 577 writes, however no inconsistency was created in the database. This may -sound unexpected as in the first part of this tutorial we stated that Valkey -Cluster can lose writes during the failover because it uses asynchronous -replication. What we did not say is that this is not very likely to happen -because Valkey sends the reply to the client, and the commands to replicate -to the replicas, about at the same time, so there is a very small window to -lose data. However the fact that it is hard to trigger does not mean that it -is impossible, so this does not change the consistency guarantees provided -by Valkey cluster. - -We can now check what is the cluster setup after the failover (note that -in the meantime I restarted the crashed instance so that it rejoins the -cluster as a replica): - -``` -$ valkey-cli -p 7000 cluster nodes -3fc783611028b1707fd65345e763befb36454d73 127.0.0.1:7004 slave 3e3a6cb0d9a9a87168e266b0a0b24026c0aae3f0 0 1385503418521 0 connected -a211e242fc6b22a9427fed61285e85892fa04e08 127.0.0.1:7003 slave 97a3a64667477371c4479320d683e4c8db5858b1 0 1385503419023 0 connected -97a3a64667477371c4479320d683e4c8db5858b1 :0 myself,master - 0 0 0 connected 0-5959 10922-11422 -3c3a0c74aae0b56170ccb03a76b60cfe7dc1912e 127.0.0.1:7005 master - 0 1385503419023 3 connected 11423-16383 -3e3a6cb0d9a9a87168e266b0a0b24026c0aae3f0 127.0.0.1:7001 master - 0 1385503417005 0 connected 5960-10921 -2938205e12de373867bf38f1ca29d31d0ddb3e46 127.0.0.1:7002 slave 3c3a0c74aae0b56170ccb03a76b60cfe7dc1912e 0 1385503418016 3 connected -``` - -Now the primaries are running on ports 7000, 7001 and 7005. What was previously -a primary, that is the Valkey instance running on port 7002, is now a replica of -7005. - -The output of the `CLUSTER NODES` command may look intimidating, but it is actually pretty simple, and is composed of the following tokens: - -* Node ID -* ip:port -* flags: master, replica, myself, fail, ... -* if it is a replica, the Node ID of the master -* Time of the last pending PING still waiting for a reply. -* Time of the last PONG received. -* Configuration epoch for this node (see the Cluster specification). -* Status of the link to this node. -* Slots served... - -#### Manual failover - -Sometimes it is useful to force a failover without actually causing any problem -on a primary. For example, to upgrade the Valkey process of one of the -primary nodes it is a good idea to failover it to turn it into a replica -with minimal impact on availability. - -Manual failovers are supported by Valkey Cluster using the `CLUSTER FAILOVER` -command, that must be executed in one of the replicas of the primary you want -to failover. - -Manual failovers are special and are safer compared to failovers resulting from -actual primary failures. They occur in a way that avoids data loss in the -process, by switching clients from the original primary to the new primary only -when the system is sure that the new primary processed all the replication stream -from the old one. - -This is what you see in the replica log when you perform a manual failover: - - # Manual failover user request accepted. - # Received replication offset for paused primary manual failover: 347540 - # All primary replication stream processed, manual failover can start. - # Start of election delayed for 0 milliseconds (rank #0, offset 347540). - # Starting a failover election for epoch 7545. - # Failover election won: I'm the new primary. - -Clients sending write commands to the primary are blocked during the failover. -When the primary sends its replication offset to the replica, the replica -waits to reach the offset on its side. When the replication offset is reached, -the failover starts, and the old primary is informed about the configuration -switch. When the switch is complete, the clients are unblocked on the old -primary and they are redirected to the new primary. - -**Note:** -To promote a replica to primary, it must first be known as a replica by a majority of the primaries in the cluster. - Otherwise, it cannot win the failover election. - If the replica has just been added to the cluster (see [Add a new node as a replica](#add-a-new-node-as-a-replica)), you may need to wait a while before sending the `CLUSTER FAILOVER` command, to make sure the primaries in cluster are aware of the new replica. - -#### Add a new node - -Adding a new node is basically the process of adding an empty node and then -moving some data into it, in case it is a new primary, or telling it to -setup as a replica of a known node, in case it is a replica. - -We'll show both, starting with the addition of a new primary instance. - -In both cases the first step to perform is **adding an empty node**. - -This is as simple as to start a new node in port 7006 (we already used -from 7000 to 7005 for our existing 6 nodes) with the same configuration -used for the other nodes, except for the port number, so what you should -do in order to conform with the setup we used for the previous nodes: - -* Create a new tab in your terminal application. -* Enter the `cluster-test` directory. -* Create a directory named `7006`. -* Create a valkey.conf file inside, similar to the one used for the other nodes but using 7006 as port number. -* Finally start the server with `../valkey-server ./valkey.conf` - -At this point the server should be running. - -Now we can use **valkey-cli** as usual in order to add the node to -the existing cluster. - - valkey-cli --cluster add-node 127.0.0.1:7006 127.0.0.1:7000 - -As you can see I used the **add-node** command specifying the address of the -new node as first argument, and the address of a random existing node in the -cluster as second argument. - -In practical terms valkey-cli here did very little to help us, it just -sent a `CLUSTER MEET` message to the node, something that is also possible -to accomplish manually. However valkey-cli also checks the state of the -cluster before to operate, so it is a good idea to perform cluster operations -always via valkey-cli even when you know how the internals work. - -Now we can connect to the new node to see if it really joined the cluster: - -``` -valkey 127.0.0.1:7006> cluster nodes -3e3a6cb0d9a9a87168e266b0a0b24026c0aae3f0 127.0.0.1:7001 master - 0 1385543178575 0 connected 5960-10921 -3fc783611028b1707fd65345e763befb36454d73 127.0.0.1:7004 slave 3e3a6cb0d9a9a87168e266b0a0b24026c0aae3f0 0 1385543179583 0 connected -f093c80dde814da99c5cf72a7dd01590792b783b :0 myself,master - 0 0 0 connected -2938205e12de373867bf38f1ca29d31d0ddb3e46 127.0.0.1:7002 slave 3c3a0c74aae0b56170ccb03a76b60cfe7dc1912e 0 1385543178072 3 connected -a211e242fc6b22a9427fed61285e85892fa04e08 127.0.0.1:7003 slave 97a3a64667477371c4479320d683e4c8db5858b1 0 1385543178575 0 connected -97a3a64667477371c4479320d683e4c8db5858b1 127.0.0.1:7000 master - 0 1385543179080 0 connected 0-5959 10922-11422 -3c3a0c74aae0b56170ccb03a76b60cfe7dc1912e 127.0.0.1:7005 master - 0 1385543177568 3 connected 11423-16383 -``` - -Note that since this node is already connected to the cluster it is already -able to redirect client queries correctly and is generally speaking part of -the cluster. However it has two peculiarities compared to the other primaries: - -* It holds no data as it has no assigned hash slots. -* Because it is a primary without assigned slots, it does not participate in the election process when a replica wants to become a primary. - -Now it is possible to assign hash slots to this node using the resharding -feature of `valkey-cli`. -It is basically useless to show this as we already -did in a previous section, there is no difference, it is just a resharding -having as a target the empty node. - -##### Add a new node as a replica - -Adding a new replica can be performed in two ways. The obvious one is to -use valkey-cli again, but with the --cluster-replica option, like this: - - valkey-cli --cluster add-node 127.0.0.1:7006 127.0.0.1:7000 --cluster-replica - -Note that the command line here is exactly like the one we used to add -a new primary, so we are not specifying to which primary we want to add -the replica. In this case, what happens is that valkey-cli will add the new -node as replica of a random primary among the primaries with fewer replicas. - -However you can specify exactly what primary you want to target with your -new replica with the following command line: - - valkey-cli --cluster add-node 127.0.0.1:7006 127.0.0.1:7000 --cluster-replica --cluster-master-id 3c3a0c74aae0b56170ccb03a76b60cfe7dc1912e - -This way we assign the new replica to a specific primary. - -A more manual way to add a replica to a specific primary is to add the new -node as an empty primary, and then turn it into a replica using the -`CLUSTER REPLICATE` command. This also works if the node was added as a replica -but you want to move it as a replica of a different primary. - -For example in order to add a replica for the node 127.0.0.1:7005 that is -currently serving hash slots in the range 11423-16383, that has a Node ID -3c3a0c74aae0b56170ccb03a76b60cfe7dc1912e, all I need to do is to connect -with the new node (already added as empty primary) and send the command: - - valkey 127.0.0.1:7006> cluster replicate 3c3a0c74aae0b56170ccb03a76b60cfe7dc1912e - -That's it. Now we have a new replica for this set of hash slots, and all -the other nodes in the cluster already know (after a few seconds needed to -update their config). We can verify with the following command: - -``` -$ valkey-cli -p 7000 cluster nodes | grep slave | grep 3c3a0c74aae0b56170ccb03a76b60cfe7dc1912e -f093c80dde814da99c5cf72a7dd01590792b783b 127.0.0.1:7006 replica 3c3a0c74aae0b56170ccb03a76b60cfe7dc1912e 0 1385543617702 3 connected -2938205e12de373867bf38f1ca29d31d0ddb3e46 127.0.0.1:7002 replica 3c3a0c74aae0b56170ccb03a76b60cfe7dc1912e 0 1385543617198 3 connected -``` - -The node 3c3a0c... now has two replicas, running on ports 7002 (the existing one) and 7006 (the new one). - -#### Remove a node - -To remove a replica node just use the `del-node` command of valkey-cli: - - valkey-cli --cluster del-node 127.0.0.1:7000 `` - -The first argument is just a random node in the cluster, the second argument -is the ID of the node you want to remove. - -You can remove a primary node in the same way as well, **however in order to -remove a primary node it must be empty**. If the primary is not empty you need -to reshard data away from it to all the other primary nodes before. - -An alternative to remove a primary node is to perform a manual failover of it -over one of its replicas and remove the node after it turned into a replica of the -new primary. Obviously this does not help when you want to reduce the actual -number of primaries in your cluster, in that case, a resharding is needed. - -There is a special scenario where you want to remove a failed node. -You should not use the `del-node` command because it tries to connect to all nodes and you will encounter a "connection refused" error. -Instead, you can use the `call` command: - - valkey-cli --cluster call 127.0.0.1:7000 cluster forget `` - -This command will execute `CLUSTER FORGET` command on every node. - -#### Replica migration - -In Valkey Cluster, you can reconfigure a replica to replicate with a -different primary at any time just using this command: - - CLUSTER REPLICATE - -However there is a special scenario where you want replicas to move from one -primary to another one automatically, without the help of the system administrator. -The automatic reconfiguration of replicas is called *replicas migration* and is -able to improve the reliability of a Valkey Cluster. - -**Note:** -You can read the details of replicas migration in the [Valkey Cluster Specification](cluster-spec.md), here we'll only provide some information about the -general idea and what you should do in order to benefit from it. - -The reason why you may want to let your cluster replicas to move from one primary -to another under certain condition, is that usually the Valkey Cluster is as -resistant to failures as the number of replicas attached to a given primary. - -For example a cluster where every primary has a single replica can't continue -operations if the primary and its replica fail at the same time, simply because -there is no other instance to have a copy of the hash slots the primary was -serving. However while net-splits are likely to isolate a number of nodes -at the same time, many other kind of failures, like hardware or software failures -local to a single node, are a very notable class of failures that are unlikely -to happen at the same time, so it is possible that in your cluster where -every primary has a replica, the replica is killed at 4am, and the primary is killed -at 6am. This still will result in a cluster that can no longer operate. - -To improve reliability of the system we have the option to add additional -replicas to every primary, but this is expensive. Replica migration allows to -add more replicas to just a few primaries. So you have 10 primaries with 1 replica -each, for a total of 20 instances. However you add, for example, 3 instances -more as replicas of some of your primaries, so certain primaries will have more -than a single replica. - -With replicas migration what happens is that if a primary is left without -replicas, a replica from a primary that has multiple replicas will migrate to -the *orphaned* primary. So after your replica goes down at 4am as in the example -we made above, another replica will take its place, and when the primary -will fail as well at 5am, there is still a replica that can be elected so that -the cluster can continue to operate. - -So what you should know about replicas migration in short? - -* The cluster will try to migrate a replica from the primary that has the greatest number of replicas in a given moment. -* To benefit from replica migration you have just to add a few more replicas to a single primary in your cluster, it does not matter what primary. -* There is a configuration parameter that controls the replica migration feature that is called `cluster-migration-barrier`: you can read more about it in the example `valkey.conf` file provided with Valkey Cluster. - -#### Upgrade nodes in a Valkey Cluster - -Upgrading replica nodes is easy since you just need to stop the node and restart -it with an updated version of Valkey. If there are clients scaling reads using -replica nodes, they should be able to reconnect to a different replica if a given -one is not available. - -Upgrading primaries is a bit more complex. The suggested procedure is to trigger -a manual failover to turn the old primary into a replica and then upgrading it. - -A complete rolling upgrade of all nodes in a cluster can be performed by -repeating the following procedure for each shard (a primary and its replicas): - -1. Add one or more upgraded nodes as new replicas to the primary. This step is - optional but it ensures that the number of replicas is not compromised during - the rolling upgrade. To add a new node, use [`CLUSTER - MEET`](../commands/cluster-meet.md) and [`CLUSTER - REPLICATE`](../commands/cluster-replicate.md) or use `valkey-cli` as - described under [Add a new node as a replica](#add-a-new-node-as-a-replica). - - An alternative is to upgrade one replica at a time and have fewer replicas - online during the upgrade. - -2. Upgrade the old replicas you want to keep by restarting them with the updated - version of Valkey. If you're replacing all the old nodes with new nodes, you - can skip this step. - -3. Select one of the upgraded replicas to be the new primary. Wait until this - replica has caught up the replication offset with the primary. You can use - [`INFO REPLICATION`](../commands/info.md) and check for the line - `master_link_status:up` to be present. This indicates that the initial sync - with the primary is complete. - - After the initial full sync, the replica might still lag behind in - replication. Send `INFO REPLICATION` to the primary and the replica and - compare the field `master_repl_offset` returned by both nodes. If the offsets - match, it means that all writes have been replicated. However, if the primary - receives a constant stream of writes, it's possible that the offsets will - never be equal. In this step, you can accept a small difference. It's usually - enough to wait for some seconds to minimize the difference. - -4. Check that the new replica is known by all nodes in the cluster, or at least - by the primaries in the cluster. You can send [`CLUSTER - NODES`](../commands/cluster-nodes.md) to each of the nodes in the cluster and - check that they all are aware of the new node. Wait for some time and repeat - the check if necessary. - -5. Trigger a manual failover by sending [`CLUSTER - FAILOVER`](../commands/cluster-failover.md) to the replica node selected to - become the new primary. See the [Manual failover](#manual-failover) section - in this document for more information. - -6. Wait for the failover to complete. To check, you can use - [`ROLE`](../commands/role.md), [`INFO REPLICATION`](../commands/info.md) - (which indicates `role:master` after successful failover) or [`CLUSTER - NODES`](../commands/cluster-nodes.md) to verify that the state of the cluster - has changed shortly after the command was sent. - -7. Take the old primary (now a replica) out of service, or upgrade it and add it - again as a replica. Remove additional replicas kept for redundancy during the - upgrade, if any. - -Repeat this sequence for each shard (each primary and its replicas) until all -nodes in the cluster have been upgraded. - -#### Migrate to Valkey Cluster - -Users willing to migrate to Valkey Cluster may have just a single primary, or -may already using a preexisting sharding setup, where keys -are split among N nodes, using some in-house algorithm or a sharding algorithm -implemented by their client library or Valkey proxy. - -In both cases it is possible to migrate to Valkey Cluster easily, however -what is the most important detail is if multiple-keys operations are used -by the application, and how. There are three different cases: - -1. Multiple keys operations, or transactions, or Lua scripts involving multiple keys, are not used. Keys are accessed independently (even if accessed via transactions or Lua scripts grouping multiple commands, about the same key, together). -2. Multiple keys operations, or transactions, or Lua scripts involving multiple keys are used but only with keys having the same **hash tag**, which means that the keys used together all have a `{...}` sub-string that happens to be identical. For example the following multiple keys operation is defined in the context of the same hash tag: `SUNION {user:1000}.foo {user:1000}.bar`. -3. Multiple keys operations, or transactions, or Lua scripts involving multiple keys are used with key names not having an explicit, or the same, hash tag. - -The third case is not handled by Valkey Cluster: the application requires to -be modified in order to not use multi keys operations or only use them in -the context of the same hash tag. - -Case 1 and 2 are covered, so we'll focus on those two cases, that are handled -in the same way, so no distinction will be made in the documentation. - -Assuming you have your preexisting data set split into N primaries, where -N=1 if you have no preexisting sharding, the following steps are needed -in order to migrate your data set to Valkey Cluster: - -1. Stop your clients. No automatic live-migration to Valkey Cluster is currently possible. You may be able to do it orchestrating a live migration in the context of your application / environment. -2. Generate an append only file for all of your N primaries using the `BGREWRITEAOF` command, and waiting for the AOF file to be completely generated. -3. Save your AOF files from aof-1 to aof-N somewhere. At this point you can stop your old instances if you wish (this is useful since in non-virtualized deployments you often need to reuse the same computers). -4. Create a Valkey Cluster composed of N primaries and zero replicas. You'll add replicas later. Make sure all your nodes are using the append only file for persistence. -5. Stop all the cluster nodes, substitute their append only file with your pre-existing append only files, aof-1 for the first node, aof-2 for the second node, up to aof-N. -6. Restart your Valkey Cluster nodes with the new AOF files. They'll complain that there are keys that should not be there according to their configuration. -7. Use `valkey-cli --cluster fix` command in order to fix the cluster so that keys will be migrated according to the hash slots each node is authoritative or not. -8. Use `valkey-cli --cluster check` at the end to make sure your cluster is ok. -9. Restart your clients modified to use a Valkey Cluster aware client library. - -There is an alternative way to import data from external instances to a Valkey -Cluster, which is to use the `valkey-cli --cluster import` command. - -The command moves all the keys of a running instance (deleting the keys from -the source instance) to the specified pre-existing Valkey Cluster. - -**Note:** -If not for backward compatibility, the Valkey project no longer uses the words "master" and "slave". Unfortunately in this command these words are part of the protocol, so we'll be able to remove such occurrences only when this API will be naturally deprecated. - -## Learn more - -* [Valkey Cluster specification](cluster-spec.md) - diff --git a/topics/command-arguments.md b/topics/command-arguments.md deleted file mode 100644 index db49909e..00000000 --- a/topics/command-arguments.md +++ /dev/null @@ -1,181 +0,0 @@ ---- -title: "Command arguments" -description: How Valkey commands expose their documentation programmatically ---- - -The `COMMAND DOCS` command returns documentation-focused information about available Valkey commands. -The map reply that the command returns includes the _arguments_ key. -This key stores an array that describes the command's arguments. - -Every element in the _arguments_ array is a map with the following fields: - -* **name:** the argument's name, always present. - The name of an argument is given for identification purposes alone. - It isn't displayed during the command's syntax rendering. - The same name can appear more than once in the entire argument tree, but it is unique compared to other sibling arguments' names. - This allows obtaining a unique identifier for each argument (the concatenation of all names in the path from the root to any argument). -* **display_text:** the argument's display string, present in arguments that have a displayable representation (all arguments that aren't oneof/block). - This is the string used in the command's syntax rendering. -* **type:** the argument's type, always present. - An argument must have one of the following types: - - **string:** a string argument. - - **integer:** an integer argument. - - **double:** a double-precision argument. - - **key:** a string that represents the name of a key. - - **pattern:** a string that represents a glob-like pattern. - - **unix-time:** an integer that represents a Unix timestamp. - - **pure-token:** an argument is a token, meaning a reserved keyword, which may or may not be provided. - Not to be confused with free-text user input. - - **oneof**: the argument is a container for nested arguments. - This type enables choice among several nested arguments (see the `XADD` example below). - - **block:** the argument is a container for nested arguments. - This type enables grouping arguments and applying a property (such as _optional_) to all (see the `XADD` example below). -* **key_spec_index:** this value is available for every argument of the _key_ type. - It is a 0-based index of the specification in the command's [key specifications][tr] that corresponds to the argument. -* **token**: a constant literal that precedes the argument (user input) itself. -* **summary:** a short description of the argument. -* **since:** the debut Redis OSS version of the argument (or for module commands, the module version). -* **deprecated_since:** the Redis OSS version that deprecated the command (or for module commands, the module version). -* **flags:** an array of argument flags. - Possible flags are: - - **optional**: denotes that the argument is optional (for example, the _GET_ clause of the `SET` command). - - **multiple**: denotes that the argument may be repeated (such as the _key_ argument of `DEL`). - - **multiple-token:** denotes the possible repetition of the argument with its preceding token (see `SORT`'s `GET pattern` clause). -* **value:** the argument's value. - For arguments types other than _oneof_ and _block_, this is a string that describes the value in the command's syntax. - For the _oneof_ and _block_ types, this is an array of nested arguments, each being a map as described in this section. - -[tr]: key-specs.md - -## Example - -The trimming clause of `XADD`, i.e., `[MAXLEN|MINID [=|~] threshold [LIMIT count]]`, is represented at the top-level as _block_-typed argument. - -It consists of four nested arguments: - -1. **trimming strategy:** this nested argument has an _oneof_ type with two nested arguments. - Each of the nested arguments, _MAXLEN_ and _MINID_, is typed as _pure-token_. -2. **trimming operator:** this nested argument is an optional _oneof_ type with two nested arguments. - Each of the nested arguments, _=_ and _~_, is a _pure-token_. -3. **threshold:** this nested argument is a _string_. -4. **count:** this nested argument is an optional _integer_ with a _token_ (_LIMIT_). - -Here's `XADD`'s arguments array: - -``` -1) 1) "name" - 2) "key" - 3) "type" - 4) "key" - 5) "value" - 6) "key" -2) 1) "name" - 2) "nomkstream" - 3) "type" - 4) "pure-token" - 5) "token" - 6) "NOMKSTREAM" - 7) "since" - 8) "6.2" - 9) "flags" - 10) 1) optional -3) 1) "name" - 2) "trim" - 3) "type" - 4) "block" - 5) "flags" - 6) 1) optional - 7) "value" - 8) 1) 1) "name" - 2) "strategy" - 3) "type" - 4) "oneof" - 5) "value" - 6) 1) 1) "name" - 2) "maxlen" - 3) "type" - 4) "pure-token" - 5) "token" - 6) "MAXLEN" - 2) 1) "name" - 2) "minid" - 3) "type" - 4) "pure-token" - 5) "token" - 6) "MINID" - 7) "since" - 8) "6.2" - 2) 1) "name" - 2) "operator" - 3) "type" - 4) "oneof" - 5) "flags" - 6) 1) optional - 7) "value" - 8) 1) 1) "name" - 2) "equal" - 3) "type" - 4) "pure-token" - 5) "token" - 6) "=" - 2) 1) "name" - 2) "approximately" - 3) "type" - 4) "pure-token" - 5) "token" - 6) "~" - 3) 1) "name" - 2) "threshold" - 3) "type" - 4) "string" - 5) "value" - 6) "threshold" - 4) 1) "name" - 2) "count" - 3) "type" - 4) "integer" - 5) "token" - 6) "LIMIT" - 7) "since" - 8) "6.2" - 9) "flags" - 10) 1) optional - 11) "value" - 12) "count" -4) 1) "name" - 2) "id_or_auto" - 3) "type" - 4) "oneof" - 5) "value" - 6) 1) 1) "name" - 2) "auto_id" - 3) "type" - 4) "pure-token" - 5) "token" - 6) "*" - 2) 1) "name" - 2) "id" - 3) "type" - 4) "string" - 5) "value" - 6) "id" -5) 1) "name" - 2) "field_value" - 3) "type" - 4) "block" - 5) "flags" - 6) 1) multiple - 7) "value" - 8) 1) 1) "name" - 2) "field" - 3) "type" - 4) "string" - 5) "value" - 6) "field" - 2) 1) "name" - 2) "value" - 3) "type" - 4) "string" - 5) "value" - 6) "value" -``` diff --git a/topics/command-tips.md b/topics/command-tips.md deleted file mode 100644 index b20f7f85..00000000 --- a/topics/command-tips.md +++ /dev/null @@ -1,111 +0,0 @@ ---- -title: "Command tips" -description: Get additional information about a command ---- - -This page documents a small part of the reply of the [`COMMAND`](../commands/command.md). -In the reply of the COMMAND command, each command is represented by an array. -The 8th element in this array is the command tips. -It's an array of strings. - -These provide Valkey clients with additional information about the command. -The information can instruct Valkey Cluster clients as to how the command should be executed and its output processed in a clustered deployment. - -Unlike the command's flags (see the 3rd element of [`COMMAND`](../commands/command.md)'s reply), which are strictly internal to the server's operation, tips don't serve any purpose other than being reported to clients. - - -## `nondeterministic_output` - -This tip indicates that the command's output isn't deterministic. -That means that calls to the command may yield different results with the same arguments and data. -That difference could be the result of the command's random nature (e.g., `RANDOMKEY` and `SPOP`); the call's timing (e.g., `TTL`); or generic differences that relate to the server's state (e.g., `INFO` and `CLIENT LIST`). - -**Note:** -Prior to Redis OSS 7.0, this tip was the `random` command flag. - -## `nondeterministic_output_order` - -The existence of this tip indicates that the command's output is deterministic, but its ordering is random (e.g., `HGETALL` and `SMEMBERS`). - -**Note:** -Prior to Redis OSS 7.0, this tip was the `sort_for_script` flag. - -## `request_policy:`*value* - -This tip can help clients determine the shards to send the command in clustering mode. -The default behavior a client should implement for commands without the `request_policy` tip is as follows: - -1. The command doesn't accept key name arguments: the client can execute the command on an arbitrary shard. -1. For commands that accept one or more key name arguments: the client should route the command to a single shard, as determined by the hash slot of the input keys. - -In cases where the client should adopt a behavior different than the default, the `request_policy` tip can be one of: - -- **all_nodes:** the client should execute the command on all nodes - primaries and replicas alike. - An example is the `CONFIG SET` command. - This tip is in-use by commands that don't accept key name arguments. - The command operates atomically per shard. -* **all_shards:** the client should execute the command on all primary shards (e.g., the `DBSIZE` command). - This tip is in-use by commands that don't accept key name arguments. - The command operates atomically per shard. -- **multi_shard:** the client should execute the command on several shards. - The client should split the inputs according to the hash slots of its input key name arguments. - For example, the command `DEL {foo} {foo}1 bar` should be split to `DEL {foo} {foo}1` and `DEL bar`. - If the keys are hashed to more than a single slot, the command must be split even if all the slots are managed by the same shard. - Examples for such commands include `MSET`, `MGET` and `DEL`. - However, note that `SUNIONSTORE` isn't considered as _multi_shard_ because all of its keys must belong to the same hash slot. -- **special:** indicates a non-trivial form of the client's request policy, such as the `SCAN` command. - -## `response_policy:`*value* - -This tip can help clients determine the aggregate they need to compute from the replies of multiple shards in a cluster. -The default behavior for commands without a `request_policy` tip only applies to replies with of nested types (i.e., an array, a set, or a map). -The client's implementation for the default behavior should be as follows: - -1. The command doesn't accept key name arguments: the client can aggregate all replies within a single nested data structure. -For example, the array replies we get from calling `KEYS` against all shards. -These should be packed in a single in no particular order. -1. For commands that accept one or more key name arguments: the client needs to retain the same order of replies as the input key names. -For example, `MGET`'s aggregated reply. - -The `response_policy` tip is set for commands that reply with scalar data types, or when it's expected that clients implement a non-default aggregate. -This tip can be one of: - -* **one_succeeded:** the clients should return success if at least one shard didn't reply with an error. - The client should reply with the first non-error reply it obtains. - If all shards return an error, the client can reply with any one of these. - For example, consider a `SCRIPT KILL` command that's sent to all shards. - Although the script should be loaded in all of the cluster's shards, the `SCRIPT KILL` will typically run only on one at a given time. -* **all_succeeded:** the client should return successfully only if there are no error replies. - Even a single error reply should disqualify the aggregate and be returned. - Otherwise, the client should return one of the non-error replies. - As an example, consider the `CONFIG SET`, `SCRIPT FLUSH` and `SCRIPT LOAD` commands. -* **agg_logical_and:** the client should return the result of a logical _AND_ operation on all replies (only applies to integer replies, usually from commands that return either _0_ or _1_). - Consider the `SCRIPT EXISTS` command as an example. - It returns an array of _0_'s and _1_'s that denote the existence of its given SHA1 sums in the script cache. - The aggregated response should be _1_ only when all shards had reported that a given script SHA1 sum is in their respective cache. -* **agg_logical_or:** the client should return the result of a logical _AND_ operation on all replies (only applies to integer replies, usually from commands that return either _0_ or _1_). -* **agg_min:** the client should return the minimal value from the replies (only applies to numerical replies). - The aggregate reply from a cluster-wide `WAIT` command, for example, should be the minimal value (number of synchronized replicas) from all shards. -* **agg_max:** the client should return the maximal value from the replies (only applies to numerical replies). -* **agg_sum:** the client should return the sum of replies (only applies to numerical replies). - Example: `DBSIZE`. -* **special:** this type of tip indicates a non-trivial form of reply policy. - `INFO` is an excellent example of that. - -## Example - -``` -127.0.0.1:6379> command info ping -1) 1) "ping" - 2) (integer) -1 - 3) 1) fast - 4) (integer) 0 - 5) (integer) 0 - 6) (integer) 0 - 7) 1) @fast - 2) @connection - 8) 1) "request_policy:all_shards" - 2) "response_policy:all_succeeded" - 9) (empty array) - 10) (empty array) -``` diff --git a/topics/data-types.md b/topics/data-types.md deleted file mode 100644 index 8c706fce..00000000 --- a/topics/data-types.md +++ /dev/null @@ -1,122 +0,0 @@ ---- -title: "Data types" -description: Overview of data types supported by Valkey ---- - -Valkey is a data structure server. -At its core, Valkey provides a collection of native data types that help you solve a wide variety of problems, from [caching](client-side-caching.md) to [queuing](lists.md) to [event processing](streams-intro.md). -Below is a short description of each data type, with links to broader overviews and command references. - -If you'd like to try a comprehensive tutorial for each data structure, see their overview pages below. - -## Strings - -[Strings](strings.md) are the most basic Valkey data type, representing a sequence of bytes. -For more information, see: - -* [Overview of Strings](strings.md) -* [String command reference](../commands/#string) - -## Lists - -[Lists](lists.md) are lists of strings sorted by insertion order. -For more information, see: - -* [Overview of Lists](lists.md) -* [List command reference](../commands/#list) - -## Sets - -[Sets](sets.md) are unordered collections of unique strings that act like the sets from your favorite programming language (for example, [Java HashSets](https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html), [Python sets](https://docs.python.org/3.10/library/stdtypes.html#set-types-set-frozenset), and so on). -With a Set, you can add, remove, and test for existence in O(1) time (in other words, regardless of the number of set elements). -For more information, see: - -* [Overview of Sets](sets.md) -* [Set command reference](../commands/#set) - -## Hashes - -[Hashes](hashes.md) are record types modeled as collections of field-value pairs. -As such, Hashes resemble [Python dictionaries](https://docs.python.org/3/tutorial/datastructures.html#dictionaries), [Java HashMaps](https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html), and [Ruby hashes](https://ruby-doc.org/core-3.1.2/Hash.html). -For more information, see: - -* [Overview of Hashes](hashes.md) -* [Hashes command reference](../commands/#hash) - -## Sorted sets - -[Sorted Sets](sorted-sets.md) are collections of unique strings that maintain order by each string's associated score. -For more information, see: - -* [Overview of Sorted Sets](sorted-sets.md) -* [Sorted Set command reference](../commands/#sorted-set) - -## Streams - -A [Stream](streams-intro.md) is a data structure that acts like an append-only log. -Streams help record events in the order they occur and then syndicate them for processing. -For more information, see: - -* [Overview of Streams](streams-intro.md) -* [Streams command reference](../commands/#stream) - -## Geospatial indexes - -[Geospatial indexes](geospatial.md) are useful for finding locations within a given geographic radius or bounding box. -For more information, see: - -* [Overview of Geospatial indexes](geospatial.md) -* [Geospatial indexes command reference](../commands/#geo) - -## Bitmaps - -[Bitmaps](bitmaps.md) let you perform bitwise operations on strings. -For more information, see: - -* [Overview of Bitmaps](bitmaps.md) -* [Bitmap command reference](../commands/#bitmap) - -## Bitfields - -[Bitfields](bitfields.md) efficiently encode multiple counters in a string value. -Bitfields provide atomic get, set, and increment operations and support different overflow policies. -For more information, see: - -* [Overview of Bitfields](bitfields.md) -* The `BITFIELD` command. - -## HyperLogLog - -The [HyperLogLog](hyperloglogs.md) data structures provide probabilistic estimates of the cardinality (i.e., number of elements) of large sets. For more information, see: - -* [Overview of HyperLogLog](hyperloglogs.md) -* [HyperLogLog command reference](../commands/#hyperloglog) - -## Bloom Filter - -[Bloom filters](bloomfilters.md) are a space efficient probabilistic data structure that allows adding elements and checking if item/s are definitely not present, or if there is a possibility they exist (with the configured false positive rate). - -The Bloom filter data type / command support is provided by the `valkey-bloom` module. -For more information, see: - -* [Overview of Bloom Filters](bloomfilters.md) -* [Bloom filter command reference](../commands/#bloom) -* [Valkey-bloom module on GitHub](https://github.com/valkey-io/valkey-bloom/) - -## Large Object - -[Large objects](large-object.md) are large binary values, such as machine learning KV cache blocks, tensors, and embeddings, stored in DRAM or in tiered DRAM and NVMe storage, with optional RDMA transfer to and from client memory. - -The large object data type / command support is provided by the `valkey-large-object` module, which is at version 0.x. -For more information, see: - -* [Overview of Large Objects](large-object.md) -* [Large object command reference](../commands/#large-object) -* [Valkey-large-object module on GitHub](https://github.com/valkey-io/valkey-large-object/) - -## Extensions - -To extend the features provided by the included data types, use one of these options: - -1. Write your own custom [server-side functions in Lua](programmability.md). -2. Write your own Valkey module using [Modules Introduction](modules-intro.md) and [Modules API](modules-api-ref.md). diff --git a/topics/debugging.md b/topics/debugging.md deleted file mode 100644 index fb057510..00000000 --- a/topics/debugging.md +++ /dev/null @@ -1,196 +0,0 @@ ---- -title: "Debugging" -description: > - A guide to debugging Valkey server processes ---- - -Valkey is developed with an emphasis on stability. We do our best with -every release to make sure you'll experience a stable product with no -crashes. However, if you ever need to debug the Valkey process itself, read on. - -When Valkey crashes, it produces a detailed report of what happened. However, -sometimes looking at the crash report is not enough, nor is it possible for -the Valkey core team to reproduce the issue independently. In this scenario, we -need help from the user who can reproduce the issue. - -This guide shows how to use GDB to provide the information the -Valkey developers will need to track the bug more easily. - -## What is GDB? - -GDB is the Gnu Debugger: a program that is able to inspect the internal state -of another program. Usually tracking and fixing a bug is an exercise in -gathering more information about the state of the program at the moment the -bug happens, so GDB is an extremely useful tool. - -GDB can be used in two ways: - -* It can attach to a running program and inspect the state of it at runtime. -* It can inspect the state of a program that already terminated using what is called a *core file*, that is, the image of the memory at the time the program was running. - -From the point of view of investigating Valkey bugs we need to use both of these -GDB modes. The user able to reproduce the bug attaches GDB to their running Valkey -instance, and when the crash happens, they create the `core` file that in turn -the developer will use to inspect the Valkey internals at the time of the crash. - -This way the developer can perform all the inspections in his or her computer -without the help of the user, and the user is free to restart Valkey in their -production environment. - -## Compiling Valkey without optimizations - -By default, Valkey is compiled with the `-O3` optimization flag, which enables -a high level of compiler optimizations that aim to maximize runtime performance. -Valkey is also compiled with the `-fno-omit-frame-pointer` flag by default, ensuring that -the frame pointer is preserved across function calls. This combination allows for -precise stack walking and call stack tracing, which is essential for debugging. - -It is better to attach GDB to Valkey compiled without optimizations using the -`make noopt` command (instead of just using the plain `make` command). However, -if you have an already running Valkey in production there is no need to recompile -and restart it if this is going to create problems on your side. GDB still works -against executables compiled with optimizations. - -You should not be overly concerned at the loss of performance from compiling Valkey -without optimizations. It is unlikely that this will cause problems in your -environment as Valkey is not very CPU-bound. - -## Attaching GDB to a running process - -If you have an already running Valkey server, you can attach GDB to it, so that -if Valkey crashes it will be possible to both inspect the internals and generate -a `core dump` file. - -After you attach GDB to the Valkey process it will continue running as usual without -any loss of performance, so this is not a dangerous procedure. - -In order to attach GDB the first thing you need is the *process ID* of the running -Valkey instance (the *pid* of the process). You can easily obtain it using -`valkey-cli`: - - $ valkey-cli info | grep process_id - process_id:58414 - -In the above example the process ID is **58414**. - -Login into your Valkey server. - -(Optional but recommended) Start **screen** or **tmux** or any other program that will make sure that your GDB session will not be closed if your ssh connection times out. You can learn more about screen in [this article](https://www.linuxjournal.com/article/6340). - -Attach GDB to the running Valkey server by typing: - - $ gdb - -For example: - - $ gdb /usr/local/bin/valkey-server 58414 - -GDB will start and will attach to the running server printing something like the following: - - Reading symbols for shared libraries + done - 0x00007fff8d4797e6 in epoll_wait () - (gdb) - -At this point GDB is attached but **your Valkey instance is blocked by GDB**. In -order to let the Valkey instance continue the execution just type **continue** at -the GDB prompt, and press enter. - - (gdb) continue - Continuing. - -Done! Now your Valkey instance has GDB attached. Now you can wait for the next crash. :) - -Now it's time to detach your screen/tmux session, if you are running GDB using it, by -pressing **Ctrl-a a** key combination. - -## After the crash - -Valkey has a command to simulate a segmentation fault (in other words a bad crash) using -the `DEBUG SEGFAULT` command (don't use it against a real production instance of course! -So I'll use this command to crash my instance to show what happens in the GDB side: - - (gdb) continue - Continuing. - - Program received signal EXC_BAD_ACCESS, Could not access memory. - Reason: KERN_INVALID_ADDRESS at address: 0xffffffffffffffff - debugCommand (c=0x7ffc32005000) at debug.c:220 - 220 *((char*)-1) = 'x'; - -As you can see GDB detected that Valkey crashed, and was even able to show me -the file name and line number causing the crash. This is already much better -than the Valkey crash report back trace (containing just function names and -binary offsets). - -## Obtaining the stack trace - -The first thing to do is to obtain a full stack trace with GDB. This is as -simple as using the **bt** command: - - (gdb) bt - #0 debugCommand (c=0x7ffc32005000) at debug.c:220 - #1 0x000000010d246d63 in call (c=0x7ffc32005000) at valkey.c:1163 - #2 0x000000010d247290 in processCommand (c=0x7ffc32005000) at valkey.c:1305 - #3 0x000000010d251660 in processInputBuffer (c=0x7ffc32005000) at networking.c:959 - #4 0x000000010d251872 in readQueryFromClient (el=0x0, fd=5, privdata=0x7fff76f1c0b0, mask=220924512) at networking.c:1021 - #5 0x000000010d243523 in aeProcessEvents (eventLoop=0x7fff6ce408d0, flags=220829559) at ae.c:352 - #6 0x000000010d24373b in aeMain (eventLoop=0x10d429ef0) at ae.c:397 - #7 0x000000010d2494ff in main (argc=1, argv=0x10d2b2900) at valkey.c:2046 - -This shows the backtrace, but we also want to dump the processor registers using the **info registers** command: - - (gdb) info registers - rax 0x0 0 - rbx 0x7ffc32005000 140721147367424 - rcx 0x10d2b0a60 4515891808 - rdx 0x7fff76f1c0b0 140735188943024 - rsi 0x10d299777 4515796855 - rdi 0x0 0 - rbp 0x7fff6ce40730 0x7fff6ce40730 - rsp 0x7fff6ce40650 0x7fff6ce40650 - r8 0x4f26b3f7 1327936503 - r9 0x7fff6ce40718 140735020271384 - r10 0x81 129 - r11 0x10d430398 4517462936 - r12 0x4b7c04f8babc0 1327936503000000 - r13 0x10d3350a0 4516434080 - r14 0x10d42d9f0 4517452272 - r15 0x10d430398 4517462936 - rip 0x10d26cfd4 0x10d26cfd4 - eflags 0x10246 66118 - cs 0x2b 43 - ss 0x0 0 - ds 0x0 0 - es 0x0 0 - fs 0x0 0 - gs 0x0 0 - -Please **make sure to include** both of these outputs in your bug report. - -## Obtaining the core file - -The next step is to generate the core dump, that is the image of the memory of the running Valkey process. This is done using the `gcore` command: - - (gdb) gcore - Saved corefile core.58414 - -Now you have the core dump to send to the Valkey developer, but **it is important -to understand** that this happens to contain all the data that was inside the -Valkey instance at the time of the crash; Valkey developers will make sure not to -share the content with anyone else, and will delete the file as soon as it is no -longer used for debugging purposes, but you are warned that by sending the core -file you are sending your data. - -## What to send to developers - -Finally you can send everything to the Valkey core team: - -* The Valkey executable you are using. -* The stack trace produced by the **bt** command, and the registers dump. -* The core file you generated with gdb. -* Information about the operating system and GCC version, and Valkey version you are using. - -## Thank you - -Your help is extremely important! Many issues can only be tracked this way. So -thanks! diff --git a/topics/distlock.md b/topics/distlock.md deleted file mode 100644 index 2e93448b..00000000 --- a/topics/distlock.md +++ /dev/null @@ -1,237 +0,0 @@ ---- -title: "Distributed Locks" -description: > - A distributed lock pattern with Valkey ---- -Distributed locks are a very useful primitive in many environments where -different processes must operate with shared resources in a mutually -exclusive way. - -There are a number of libraries and blog posts describing how to implement -a DLM (Distributed Lock Manager) with Valkey, but every library uses a different -approach, and many use a simple approach with lower guarantees compared to -what can be achieved with slightly more complex designs. - -This page describes a more canonical algorithm to implement -distributed locks with Valkey. We propose an algorithm, called **Redlock**, -which implements a DLM which we believe to be safer than the vanilla single -instance approach. We hope that the community will analyze it, provide -feedback, and use it as a starting point for the implementations or more -complex or alternative designs. - -## Implementations - -Before describing the algorithm, here are a few links to implementations -already available that can be used for reference. - -* [Redlock-rb](https://github.com/antirez/redlock-rb) (Ruby implementation). There is also a [fork of Redlock-rb](https://github.com/leandromoreira/redlock-rb) that adds a gem for easy distribution. -* [Redlock-py](https://github.com/SPSCommerce/redlock-py) (Python implementation). -* [Pottery](https://github.com/brainix/pottery#redlock) (Python implementation). -* [Aioredlock](https://github.com/joanvila/aioredlock) (Asyncio Python implementation). -* [RedisMutex](https://github.com/malkusch/lock#redismutex) (PHP implementation with both [Redis extension](https://github.com/phpredis/phpredis) and [Predis library](https://github.com/predis/predis) clients support). -* [Redlock-php](https://github.com/ronnylt/redlock-php) (PHP implementation). -* [cheprasov/php-redis-lock](https://github.com/cheprasov/php-redis-lock) (PHP library for locks). -* [rtckit/react-redlock](https://github.com/rtckit/reactphp-redlock) (Async PHP implementation). -* [Redsync](https://github.com/go-redsync/redsync) (Go implementation). -* [Redisson](https://github.com/mrniko/redisson) (Java implementation). -* [Redis::DistLock](https://github.com/sbertrang/redis-distlock) (Perl implementation). -* [Redlock-cpp](https://github.com/jacket-code/redlock-cpp) (C++ implementation). -* [Redis-plus-plus](https://github.com/sewenew/redis-plus-plus/#redlock) (C++ implementation). -* [Redlock-cs](https://github.com/kidfashion/redlock-cs) (C#/.NET implementation). -* [RedLock.net](https://github.com/samcook/RedLock.net) (C#/.NET implementation). Includes async and lock extension support. -* [ScarletLock](https://github.com/aidapsibr/scarletlock) (C# .NET implementation with configurable datastore). -* [Redlock4Net](https://github.com/LiZhenNet/Redlock4Net) (C# .NET implementation). -* [node-redlock](https://github.com/mike-marcacci/node-redlock) (NodeJS implementation). Includes support for lock extension. -* [redlock-universal](https://github.com/alexpota/redlock-universal) (NodeJS implementation). Supports node-redis, ioredis, and Valkey GLIDE. Features auto-extension and batch acquisition. -* [Deno DLM](https://github.com/oslabs-beta/Deno-Redlock) (Deno implementation) -* [Rslock](https://github.com/hexcowboy/rslock) (Rust implementation). Includes async and lock extension support. - -## Safety and Liveness Guarantees - -We are going to model our design with just three properties that, from our point of view, are the minimum guarantees needed to use distributed locks in an effective way. - -1. Safety property: Mutual exclusion. At any given moment, only one client can hold a lock. -2. Liveness property A: Deadlock free. Eventually it is always possible to acquire a lock, even if the client that locked a resource crashes or gets partitioned. -3. Liveness property B: Fault tolerance. As long as the majority of Valkey nodes are up, clients are able to acquire and release locks. - -## Why Failover-based Implementations Are Not Enough - -To understand what we want to improve, let’s analyze the current state of affairs with most Valkey-based distributed lock libraries. - -The simplest way to use Valkey to lock a resource is to create a key in an instance. The key is usually created with a limited time to live, using the Valkey expires feature, so that eventually it will get released (property 2 in our list). When the client needs to release the resource, it deletes the key. - -Superficially this works well, but there is a problem: this is a single point of failure in our architecture. What happens if the Valkey primary goes down? - -Well, let’s add a replica! And use it if the primary is unavailable. This is unfortunately not viable. By doing so we can’t implement our safety property of mutual exclusion, because Valkey replication is asynchronous. - -There is a race condition with this model: - -1. Client A acquires the lock in the primary. -2. The primary crashes before the write to the key is transmitted to the replica. -3. The replica gets promoted to primary. -4. Client B acquires the lock to the same resource A already holds a lock for. **SAFETY VIOLATION!** - -Sometimes it is perfectly fine that, under special circumstances, for example during a failure, multiple clients can hold the lock at the same time. -If this is the case, you can use your replication based solution. Otherwise we suggest to implement the solution described in this document. - -## Correct Implementation with a Single Instance - -Before trying to overcome the limitation of the single instance setup described above, let’s check how to do it correctly in this simple case, since this is actually a viable solution in applications where a race condition from time to time is acceptable, and because locking into a single instance is the foundation we’ll use for the distributed algorithm described here. - -To acquire the lock, the way to go is the following: - - SET resource_name my_random_value NX PX 30000 - -The command will set the key only if it does not already exist (`NX` option), with an expire of 30000 milliseconds (`PX` option). -The key is set to a value “my\_random\_value”. This value must be unique across all clients and all lock requests. - -Basically the random value is used in order to release the lock in a safe way, with a script that tells Valkey: remove the key only if it exists and the value stored at the key is exactly the one I expect to be. - -In Valkey 9.0.0 and later, this can be done atomically using the built-in DELIFEQ command: - - DELIFEQ resource_name my_random_value - -In earlier versions of Valkey, the same behavior can be achieved using a Lua script: - - if server.call("get",KEYS[1]) == ARGV[1] then - return server.call("del",KEYS[1]) - else - return 0 - end - -This is important in order to avoid removing a lock that was created by another client. For example a client may acquire the lock, get blocked performing some operation for longer than the lock validity time (the time at which the key will expire), and later remove the lock, that was already acquired by some other client. -Using just `DEL` is not safe as a client may remove another client's lock. With the above script instead every lock is “signed” with a random string, so the lock will be removed only if it is still the one that was set by the client trying to remove it. - -What should this random string be? We assume it’s 20 bytes from `/dev/urandom`, but you can find cheaper ways to make it unique enough for your tasks. -For example a safe pick is to seed RC4 with `/dev/urandom`, and generate a pseudo random stream from that. -A simpler solution is to use a UNIX timestamp with microsecond precision, concatenating the timestamp with a client ID. It is not as safe, but probably sufficient for most environments. - -The "lock validity time" is the time we use as the key's time to live. It is both the auto release time, and the time the client has in order to perform the operation required before another client may be able to acquire the lock again, without technically violating the mutual exclusion guarantee, which is only limited to a given window of time from the moment the lock is acquired. - -So now we have a good way to acquire and release the lock. With this system, reasoning about a non-distributed system composed of a single, always available, instance, is safe. Let’s extend the concept to a distributed system where we don’t have such guarantees. - -## The Redlock Algorithm - -In the distributed version of the algorithm we assume we have N Valkey primaries. Those nodes are totally independent, so we don’t use replication or any other implicit coordination system. We already described how to acquire and release the lock safely in a single instance. We take for granted that the algorithm will use this method to acquire and release the lock in a single instance. In our examples we set N=5, which is a reasonable value, so we need to run 5 Valkey primaries on different computers or virtual machines in order to ensure that they’ll fail in a mostly independent way. - -In order to acquire the lock, the client performs the following operations: - -1. It gets the current time in milliseconds. -2. It tries to acquire the lock in all the N instances sequentially, using the same key name and random value in all the instances. During step 2, when setting the lock in each instance, the client uses a timeout which is small compared to the total lock auto-release time in order to acquire it. For example if the auto-release time is 10 seconds, the timeout could be in the ~ 5-50 milliseconds range. This prevents the client from remaining blocked for a long time trying to talk with a Valkey node which is down: if an instance is not available, we should try to talk with the next instance ASAP. -3. The client computes how much time elapsed in order to acquire the lock, by subtracting from the current time the timestamp obtained in step 1. If and only if the client was able to acquire the lock in the majority of the instances (at least 3), and the total time elapsed to acquire the lock is less than lock validity time, the lock is considered to be acquired. -4. If the lock was acquired, its validity time is considered to be the initial validity time minus the time elapsed, as computed in step 3. -5. If the client failed to acquire the lock for some reason (either it was not able to lock N/2+1 instances or the validity time is negative), it will try to unlock all the instances (even the instances it believed it was not able to lock). - -### Is the Algorithm Asynchronous? - -The algorithm relies on the assumption that while there is no synchronized clock across the processes, the local time in every process updates at approximately at the same rate, with a small margin of error compared to the auto-release time of the lock. This assumption closely resembles a real-world computer: every computer has a local clock and we can usually rely on different computers to have a clock drift which is small. - -At this point we need to better specify our mutual exclusion rule: it is guaranteed only as long as the client holding the lock terminates its work within the lock validity time (as obtained in step 3), minus some time (just a few milliseconds in order to compensate for clock drift between processes). - -This paper contains more information about similar systems requiring a bound *clock drift*: [Leases: an efficient fault-tolerant mechanism for distributed file cache consistency](https://dl.acm.org/citation.cfm?id=74870). - -### Retry on Failure - -When a client is unable to acquire the lock, it should try again after a random delay in order to try to desynchronize multiple clients trying to acquire the lock for the same resource at the same time (this may result in a split brain condition where nobody wins). Also the faster a client tries to acquire the lock in the majority of Valkey instances, the smaller the window for a split brain condition (and the need for a retry), so ideally the client should try to send the `SET` commands to the N instances at the same time using multiplexing. - -It is worth stressing how important it is for clients that fail to acquire the majority of locks, to release the (partially) acquired locks ASAP, so that there is no need to wait for key expiry in order for the lock to be acquired again (however if a network partition happens and the client is no longer able to communicate with the Valkey instances, there is an availability penalty to pay as it waits for key expiration). - -### Releasing the Lock - -Releasing the lock is simple, and can be performed whether or not the client believes it was able to successfully lock a given instance. - -### Safety Arguments - -Is the algorithm safe? Let's examine what happens in different scenarios. - -To start let’s assume that a client is able to acquire the lock in the majority of instances. All the instances will contain a key with the same time to live. However, the key was set at different times, so the keys will also expire at different times. But if the first key was set at worst at time T1 (the time we sample before contacting the first server) and the last key was set at worst at time T2 (the time we obtained the reply from the last server), we are sure that the first key to expire in the set will exist for at least `MIN_VALIDITY=TTL-(T2-T1)-CLOCK_DRIFT`. All the other keys will expire later, so we are sure that the keys will be simultaneously set for at least this time. - -During the time that the majority of keys are set, another client will not be able to acquire the lock, since N/2+1 SET NX operations can’t succeed if N/2+1 keys already exist. So if a lock was acquired, it is not possible to re-acquire it at the same time (violating the mutual exclusion property). - -However we want to also make sure that multiple clients trying to acquire the lock at the same time can’t simultaneously succeed. - -If a client locked the majority of instances using a time near, or greater, than the lock maximum validity time (the TTL we use for SET basically), it will consider the lock invalid and will unlock the instances, so we only need to consider the case where a client was able to lock the majority of instances in a time which is less than the validity time. In this case for the argument already expressed above, for `MIN_VALIDITY` no client should be able to re-acquire the lock. So multiple clients will be able to lock N/2+1 instances at the same time (with "time" being the end of Step 2) only when the time to lock the majority was greater than the TTL time, making the lock invalid. - -### Liveness Arguments - -The system liveness is based on three main features: - -1. The auto release of the lock (since keys expire): eventually keys are available again to be locked. -2. The fact that clients, usually, will cooperate removing the locks when the lock was not acquired, or when the lock was acquired and the work terminated, making it likely that we don’t have to wait for keys to expire to re-acquire the lock. -3. The fact that when a client needs to retry a lock, it waits a time which is comparably greater than the time needed to acquire the majority of locks, in order to probabilistically make split brain conditions during resource contention unlikely. - -However, we pay an availability penalty equal to `TTL` time on network partitions, so if there are continuous partitions, we can pay this penalty indefinitely. -This happens every time a client acquires a lock and gets partitioned away before being able to remove the lock. - -Basically if there are infinite continuous network partitions, the system may become not available for an infinite amount of time. - -### Performance, Crash Recovery and fsync - -Many users using Valkey as a lock server need high performance in terms of both latency to acquire and release a lock, and number of acquire / release operations that it is possible to perform per second. In order to meet this requirement, the strategy to talk with the N Valkey servers to reduce latency is definitely multiplexing (putting the socket in non-blocking mode, send all the commands, and read all the commands later, assuming that the RTT between the client and each instance is similar). - -However there is another consideration around persistence if we want to target a crash-recovery system model. - -Basically to see the problem here, let’s assume we configure Valkey without persistence at all. A client acquires the lock in 3 of 5 instances. One of the instances where the client was able to acquire the lock is restarted, at this point there are again 3 instances that we can lock for the same resource, and another client can lock it again, violating the safety property of exclusivity of lock. - -If we enable AOF persistence, things will improve quite a bit. For example we can upgrade a server by sending it a `SHUTDOWN` command and restarting it. Because Valkey expires are semantically implemented so that time still elapses when the server is off, all our requirements are fine. -However everything is fine as long as it is a clean shutdown. What about a power outage? If Valkey is configured, as by default, to fsync on disk every second, it is possible that after a restart our key is missing. In theory, if we want to guarantee the lock safety in the face of any kind of instance restart, we need to enable `fsync=always` in the persistence settings. This will affect performance due to the additional sync overhead. - -However things are better than they look like at a first glance. Basically, -the algorithm safety is retained as long as when an instance restarts after a -crash, it no longer participates to any **currently active** lock. This means that the -set of currently active locks when the instance restarts were all obtained -by locking instances other than the one which is rejoining the system. - -To guarantee this we just need to make an instance, after a crash, unavailable -for at least a bit more than the max `TTL` we use. This is the time needed -for all the keys about the locks that existed when the instance crashed to -become invalid and be automatically released. - -Using *delayed restarts* it is basically possible to achieve safety even -without any kind of Valkey persistence available, however note that this may -translate into an availability penalty. For example if a majority of instances -crash, the system will become globally unavailable for `TTL` (here globally means -that no resource at all will be lockable during this time). - -### Making the algorithm more reliable: Extending the lock - -If the work performed by clients consists of small steps, it is possible to -use smaller lock validity times by default, and extend the algorithm implementing -a lock extension mechanism. Basically the client, if in the middle of the -computation while the lock validity is approaching a low value, may extend the -lock by sending a Lua script to all the instances that extends the TTL of the key -if the key exists and its value is still the random value the client assigned -when the lock was acquired. - -The client should only consider the lock re-acquired if it was able to extend -the lock into the majority of instances, and within the validity time -(basically the algorithm to use is very similar to the one used when acquiring -the lock). - -However this does not technically change the algorithm, so the maximum number -of lock reacquisition attempts should be limited, otherwise one of the liveness -properties is violated. - -### Disclaimer about consistency - -Please consider thoroughly reviewing the [Analysis of Redlock](#analysis-of-redlock) section at the end of this page. -Martin Kleppman's article and antirez's answer to it are very relevant. -If you are concerned about consistency and correctness, you should pay attention to the following topics: - -1. You should implement fencing tokens. - This is especially important for processes that can take significant time and applies to any distributed locking system. - Extending locks' lifetime is also an option, but don´t assume that a lock is retained as long as the process that had acquired it is alive. -2. Valkey is not using monotonic clock for TTL expiration mechanism. - That means that a wall-clock shift may result in a lock being acquired by more than one process. - Even though the problem can be mitigated by preventing admins from manually setting the server's time and setting up NTP properly, there's still a chance of this issue occurring in real life and compromising consistency. - -## Want to help? - -If you are into distributed systems, it would be great to have your opinion / analysis. Also reference implementations in other languages could be great. - -Thanks in advance! - -## Analysis of Redlock ---- - -1. Martin Kleppmann [analyzed Redlock here](https://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html). A counterpoint to this analysis can be [found here](https://web.archive.org/web/20241209045142/http://antirez.com/news/101). diff --git a/topics/eval-intro.md b/topics/eval-intro.md deleted file mode 100644 index 253f3fe5..00000000 --- a/topics/eval-intro.md +++ /dev/null @@ -1,293 +0,0 @@ ---- -title: "Scripting with Lua" -description: > - Executing Lua in Valkey ---- - -Valkey lets users upload and execute Lua scripts on the server. -Scripts can employ programmatic control structures and use most of the [commands](../commands/) while executing to access the database. -Because scripts execute in the server, reading and writing data from scripts is very efficient. - -Valkey guarantees the script's atomic execution. -While executing the script, all server activities are blocked during its entire runtime. -These semantics mean that all of the script's effects either have yet to happen or had already happened. - -Scripting offers several properties that can be valuable in many cases. -These include: - -* Providing locality by executing logic where data lives. Data locality reduces overall latency and saves networking resources. -* Blocking semantics that ensure the script's atomic execution. -* Enabling the composition of simple capabilities that are either missing from Valkey or are too niche to be a part of it. - -Lua lets you run part of your application logic inside Valkey. -Such scripts can perform conditional updates across multiple keys, possibly combining several different data types atomically. - -Scripts are executed in Valkey by an embedded execution engine. -Presently, Valkey supports a single scripting engine, the [Lua 5.1](https://www.lua.org/) interpreter. -Please refer to the [Valkey Lua API Reference](lua-api.md) page for complete documentation. - -Although the server executes them, Eval scripts are regarded as a part of the client-side application, which is why they're not named, versioned, or persisted. -So all scripts may need to be reloaded by the application at any time if missing (after a server restart, fail-over to a replica, etc.). -As of version 7.0, [Valkey Functions](functions-intro.md) offer an alternative approach to programmability which allow the server itself to be extended with additional programmed logic. - -## Getting started - -We'll start scripting with Valkey by using the `EVAL` command. - -Here's our first example: - -``` -> EVAL "return 'Hello, scripting!'" 0 -"Hello, scripting!" -``` - -In this example, `EVAL` takes two arguments. -The first argument is a string that consists of the script's Lua source code. -The script doesn't need to include any definitions of Lua function. -It is just a Lua program that will run in the Valkey engine's context. - -The second argument is the number of arguments that follow the script's body, starting from the third argument, representing Valkey key names. -In this example, we used the value _0_ because we didn't provide the script with any arguments, whether the names of keys or not. - -## Script parameterization - -It is possible, although highly ill-advised, to have the application dynamically generate script source code per its needs. -For example, the application could send these two entirely different, but at the same time perfectly identical scripts: - -``` -127.0.0.1:6379> EVAL "return 'Hello'" 0 -"Hello" -127.0.0.1:6379> EVAL "return 'Scripting!'" 0 -"Scripting!" -``` - -Although this mode of operation isn't blocked by Valkey, it is an anti-pattern due to script cache considerations (more on the topic below). -Instead of having your application generate subtle variations of the same scripts, you can parametrize them and pass any arguments needed for to execute them. - -The following example demonstrates how to achieve the same effects as above, but via parameterization: - -``` -127.0.0.1:6379> EVAL "return ARGV[1]" 0 Hello -"Hello" -127.0.0.1:6379> EVAL "return ARGV[1]" 0 Parameterization! -"Parameterization!" -``` - -At this point, it is essential to understand the distinction Valkey makes between input arguments that are names of keys and those that aren't. - -While key names in Valkey are just strings, unlike any other string values, these represent keys in the database. -The name of a key is a fundamental concept in Valkey and is the basis for operating the Valkey Cluster. - -**Important:** -to ensure the correct execution of scripts, both in standalone and clustered deployments, all names of keys that a script accesses must be explicitly provided as input key arguments. -The script **should only** access keys whose names are given as input arguments. -Scripts **should never** access keys with programmatically-generated names or based on the contents of data structures stored in the database. - -Any input to the function that isn't the name of a key is a regular input argument. - -In the example above, both _Hello_ and _Parameterization!_ regular input arguments for the script. -Because the script doesn't touch any keys, we use the numerical argument _0_ to specify there are no key name arguments. -The execution context makes arguments available to the script through [_KEYS_](lua-api.md#the-keys-global-variable) and [_ARGV_](lua-api.md#the-argv-global-variable) global runtime variables. -The _KEYS_ table is pre-populated with all key name arguments provided to the script before its execution, whereas the _ARGV_ table serves a similar purpose but for regular arguments. - -The following attempts to demonstrate the distribution of input arguments between the scripts _KEYS_ and _ARGV_ runtime global variables: - -``` -127.0.0.1:6379> EVAL "return { KEYS[1], KEYS[2], ARGV[1], ARGV[2], ARGV[3] }" 2 key1 key2 arg1 arg2 arg3 -1) "key1" -2) "key2" -3) "arg1" -4) "arg2" -5) "arg3" -``` - -**Note:** -as can been seen above, Lua's table arrays are returned as [RESP2 array replies](protocol.md#arrays), so it is likely that your client's library will convert it to the native array data type in your programming language. -Please refer to the rules that govern [data type conversion](lua-api.md#data-type-conversion) for more pertinent information. - -## Interacting with Valkey from a script - -It is possible to call Valkey commands from a Lua script either via [`server.call()`](lua-api.md#server.call) or [`server.pcall()`](lua-api.md#server.pcall). - -The two are nearly identical. -Both execute a Valkey command along with its provided arguments, if these represent a well-formed command. -However, the difference between the two functions lies in the manner in which runtime errors (such as syntax errors, for example) are handled. -Errors raised from calling `server.call()` function are returned directly to the client that had executed it. -Conversely, errors encountered when calling the `server.pcall()` function are returned to the script's execution context instead for possible handling. - -For example, consider the following: - -``` -> EVAL "return server.call('SET', KEYS[1], ARGV[1])" 1 foo bar -OK -``` - -The above script accepts one key name and one value as its input arguments. -When executed, the script calls the `SET` command to set the input key, _foo_, with the string value "bar". - -## Script cache - -Until this point, we've used the `EVAL` command to run our script. - -Whenever we call `EVAL`, we also include the script's source code with the request. -Repeatedly calling `EVAL` to execute the same set of parameterized scripts, wastes both network bandwidth and also has some overheads in Valkey. -Naturally, saving on network and compute resources is key, so, instead, Valkey provides a caching mechanism for scripts. - -Every script you execute with `EVAL` is stored in a dedicated cache that the server keeps. -The cache's contents are organized by the scripts' SHA1 digest sums, so the SHA1 digest sum of a script uniquely identifies it in the cache. -You can verify this behavior by running `EVAL` and calling `INFO` afterward. -You'll notice that the _used_memory_scripts_eval_ and _number_of_cached_scripts_ metrics grow with every new script that's executed. - -As mentioned above, dynamically-generated scripts are an anti-pattern. -Generating scripts during the application's runtime may, and probably will, exhaust the host's memory resources for caching them. -Instead, scripts should be as generic as possible and provide customized execution via their arguments. - -A script is loaded to the server's cache by calling the `SCRIPT LOAD` command and providing its source code. -The server doesn't execute the script, but instead just compiles and loads it to the server's cache. -Once loaded, you can execute the cached script with the SHA1 digest returned from the server. - -Here's an example of loading and then executing a cached script: - -``` -127.0.0.1:6379> SCRIPT LOAD "return 'Immabe a cached script'" -"c664a3bf70bd1d45c4284ffebb65a6f2299bfc9f" -127.0.0.1:6379> EVALSHA c664a3bf70bd1d45c4284ffebb65a6f2299bfc9f 0 -"Immabe a cached script" -``` - -### Cache volatility - -The Valkey script cache is **always volatile**. -It isn't considered as a part of the database and is **not persisted**. -The cache may be cleared when the server restarts, during fail-over when a replica assumes the primary role, or explicitly by `SCRIPT FLUSH`. -That means that cached scripts are ephemeral, and the cache's contents can be lost at any time. - -Applications that use scripts should always call `EVALSHA` to execute them. -The server returns an error if the script's SHA1 digest is not in the cache. -For example: - -``` -127.0.0.1:6379> EVALSHA ffffffffffffffffffffffffffffffffffffffff 0 -(error) NOSCRIPT No matching script -``` - -In this case, the application should first load it with `SCRIPT LOAD` and then call `EVALSHA` once more to run the cached script by its SHA1 sum. -Most of [Valkey' clients](../clients/) already provide utility APIs for doing that automatically. -Please consult your client's documentation regarding the specific details. - -### `EVALSHA` in the context of pipelining - -Special care should be given executing `EVALSHA` in the context of a [pipelined request](pipelining.md). -The commands in a pipelined request run in the order they are sent, but other clients' commands may be interleaved for execution between these. -Because of that, the `NOSCRIPT` error can return from a pipelined request but can't be handled. - -Therefore, a client library's implementation should revert to using plain `EVAL` of parameterized in the context of a pipeline. - -### Script cache semantics - -During normal operation, an application's scripts are meant to stay indefinitely in the cache (that is, until the server is restarted or the cache being flushed). -The underlying reasoning is that the script cache contents of a well-written application are unlikely to grow continuously. -Even large applications that use hundreds of cached scripts shouldn't be an issue in terms of cache memory usage. - -There are two exceptions to this rule, which exist to protect the server from unbounded memory usage: - -* Starting from Valkey 8.0, scripts cached by `EVAL` are kept in an LRU cache of at most 500 scripts. - When the limit is reached, the least recently used `EVAL` script is evicted to make room for a new one. - Starting from Valkey 9.2, the memory used by these scripts can also be capped with the `maxmemory-scripts` configuration. - When the limit is reached, the least recently used `EVAL` scripts are evicted until the memory usage is back under the limit. - The two limits are independent, and both are enforced. -* Scripts loaded with `SCRIPT LOAD` are never evicted and aren't counted against the 500 scripts limit or `maxmemory-scripts`. - Starting from Valkey 9.2, `SCRIPT LOAD` is denied with an out of memory error when the server is over the `maxmemory` limit and can't free memory by eviction. - -An evicted script can be loaded again, as described in the [cache volatility](#cache-volatility) section. - -The only way to flush the script cache is by explicitly calling the `SCRIPT FLUSH` command. -Running the command will _completely flush_ the scripts cache, removing all the scripts executed so far. -Typically, this is only needed when the instance is going to be instantiated for another customer or application in a cloud environment. - -Also, as already mentioned, restarting a Valkey instance flushes the non-persistent script cache. -However, from the point of view of the Valkey client, there are only two ways to make sure that a Valkey instance was not restarted between two different commands: - -* The connection we have with the server is persistent and was never closed so far. -* The client explicitly checks the `run_id` field in the `INFO` command to ensure the server was not restarted and is still the same process. - -Practically speaking, it is much simpler for the client to assume that in the context of a given connection, cached scripts are guaranteed to be there unless the administrator explicitly invoked the `SCRIPT FLUSH` command. -The fact that the user can count on Valkey to retain cached scripts is semantically helpful in the context of pipelining. - -## The `SCRIPT` command - -The Valkey `SCRIPT` provides several ways for controlling the scripting subsystem. -These are: - -* `SCRIPT FLUSH`: this command is the only way to force Valkey to flush the scripts cache. - It is most useful in environments where the same Valkey instance is reassigned to different uses. - It is also helpful for testing client libraries' implementations of the scripting feature. - -* `SCRIPT EXISTS`: given one or more SHA1 digests as arguments, this command returns an array of _1_'s and _0_'s. - _1_ means the specific SHA1 is recognized as a script already present in the scripting cache. _0_'s meaning is that a script with this SHA1 wasn't loaded before (or at least never since the latest call to `SCRIPT FLUSH`). - -* `SCRIPT LOAD script`: this command registers the specified script in the Valkey script cache. - It is a useful command in all the contexts where we want to ensure that `EVALSHA` doesn't not fail (for instance, in a pipeline or when called from a [`MULTI`/`EXEC` transaction](transactions.md)), without the need to execute the script. - -* `SCRIPT SHOW`: this command shows the original source code for a script that is stored in the script cache. - It is useful to help users easily obtain scripts using signature. - -* `SCRIPT KILL`: this command is the only way to interrupt a long-running script (a.k.a slow script), short of shutting down the server. - A script is deemed as slow once its execution's duration exceeds the configured [maximum execution time](programmability.md#maximum-execution-time) threshold. - The `SCRIPT KILL` command can be used only with scripts that did not modify the dataset during their execution (since stopping a read-only script does not violate the scripting engine's guaranteed atomicity). - -* `SCRIPT DEBUG`: controls use of the built-in [Valkey Lua scripts debugger](ldb.md). - -## Script replication - -In a primary-replica setup (see [replication](replication.md)), write commands performed by a script on the primary are also sent to replicas to maintain consistency. -When the script execution finishes, the sequence of commands that the script generated are wrapped into a [`MULTI`/`EXEC` transaction](transactions.md) and are sent to the replicas and written to the AOF file, if an AOF file is used. (See [Persistence](persistence.md).) -This is called *effects replication*. - -In the past, it was also possible to use *verbatim replication* which means that a script was replicated as a whole, but this was removed in 7.0. - -The [`server.replicate_commands()`](lua-api.md#server.replicate_commands) function is deprecated and has no effect, but it exists to avoid breaking existing scripts. - -## Debugging Eval scripts - -Valkey has a built-in Lua debugger. -The Valkey Lua debugger is a remote debugger consisting of a server, which is Valkey itself, and a client, which is by default [`valkey-cli`](cli.md). - -The Lua debugger is described in the [Lua scripts debugging](ldb.md) section of the Valkey documentation. - -## Execution under low memory conditions - -When memory usage in Valkey exceeds the `maxmemory` limit, the first write command encountered in the script that uses additional memory will cause the script to abort (unless [`server.pcall`](lua-api.md#server.pcall) was used). - -However, an exception to the above is when the script's first write command does not use additional memory, as is the case with (for example, `DEL` and `LREM`). -In this case, Valkey will allow all commands in the script to run to ensure atomicity. -If subsequent writes in the script consume additional memory, Valkey' memory usage can exceed the threshold set by the `maxmemory` configuration directive. - -Another scenario in which a script can cause memory usage to cross the `maxmemory` threshold is when the execution begins when Valkey is slightly below `maxmemory`, so the script's first write command is allowed. -As the script executes, subsequent write commands consume more memory leading to the server using more RAM than the configured `maxmemory` directive. - -In those scenarios, you should consider setting the `maxmemory-policy` configuration directive to any values other than `noeviction`. -In addition, Lua scripts should be as fast as possible so that eviction can kick in between executions. - -Note that you can change this behaviour by using [flags](#eval-flags) - -## Eval flags - -Normally, when you run an Eval script, the server does not know how it accesses the database. -By default, Valkey assumes that all scripts read and write data. -However, starting with Redis OSS 7.0, there's a way to declare flags when creating a script in order to tell Valkey how it should behave. - -The way to do that is by using a Shebang statement on the first line of the script like so: - -``` -#!lua flags=no-writes,allow-stale -local x = server.call('get','x') -return x -``` - -Note that as soon as Valkey sees the `#!` comment, it'll treat the script as if it declares flags, even if no flags are defined, -it still has a different set of defaults compared to a script without a `#!` line. - -Another difference is that scripts without `#!` can run commands that access keys belonging to different cluster hash slots, but ones with `#!` inherit the default flags, so they cannot. - -Please refer to [Script flags](lua-api.md#script_flags) to learn about the various scripts and the defaults. diff --git a/topics/faq.md b/topics/faq.md deleted file mode 100644 index a8bad50f..00000000 --- a/topics/faq.md +++ /dev/null @@ -1,133 +0,0 @@ ---- -title: "FAQ" -description: > - Commonly asked questions when getting started with Valkey ---- -## How is Valkey different from other key-value stores? - -* Valkey has a different evolution path in the key-value DBs where values can contain more complex data types, with atomic operations defined on those data types. Valkey data types are closely related to fundamental data structures and are exposed to the programmer as such, without additional abstraction layers. -* Valkey is an in-memory but persistent on disk database, so it represents a different trade off where very high write and read speed is achieved with the limitation of data sets that can't be larger than memory. Another advantage of -in-memory databases is that the memory representation of complex data structures -is much simpler to manipulate compared to the same data structures on disk, so -Valkey can do a lot with little internal complexity. At the same time the -two on-disk storage formats (RDB and AOF) don't need to be suitable for random -access, so they are compact and always generated in an append-only fashion -(Even the AOF log rotation is an append-only operation, since the new version -is generated from the copy of data in memory). However this design also involves -different challenges compared to traditional on-disk stores. Being the main data -representation on memory, Valkey operations must be carefully handled to make sure -there is always an updated version of the data set on disk. - -## What's the Valkey memory footprint? - -To give you a few examples: - -* An empty instance uses ~ 3MB of memory. -* 1 Million small Keys -> String Value pairs use ~ 85MB of memory. -* 1 Million Keys -> Hash value, representing an object with 5 fields, use ~ 160 MB of memory. - -Testing your use case is trivial. Use the `valkey-benchmark` utility to generate random data sets then check the space used with the `INFO memory` command. - -## Why does Valkey keep its entire dataset in memory? - -In the past, developers experimented with Virtual Memory and other systems in order to allow larger than RAM datasets, but after all we are very happy if we can do one thing well: data served from memory, disk used for storage. So for now there are no plans to create an on disk backend for Valkey. Most of what -Valkey is, after all, a direct result of its current design. - -If your real problem is not the total RAM needed, but the fact that you need -to split your data set into multiple Valkey instances, please read the -[partitioning page](cluster-tutorial.md) in this documentation for more info. - -## Can you use Valkey with a disk-based database? - -Yes, a common design pattern involves taking very write-heavy small data -in Valkey (and data you need the Valkey data structures to model your problem -in an efficient way), and big *blobs* of data into an SQL or eventually -consistent on-disk database. Similarly sometimes Valkey is used in order to -take in memory another copy of a subset of the same data stored in the on-disk -database. This may look similar to caching, but actually is a more advanced model -since normally the Valkey dataset is updated together with the on-disk DB dataset, -and not refreshed on cache misses. - -## How can I reduce Valkey' overall memory usage? - -A good practice is to consider memory consumption when mapping your logical data model to the physical data model within Valkey. These considerations include using specific data types, key patterns, and normalization. - -Beyond data modeling, there is more info in the [Memory Optimization page](memory-optimization.md). - -## What happens if Valkey runs out of memory? - -Valkey has built-in protections allowing the users to set a max limit on memory -usage, using the `maxmemory` option in the configuration file to put a limit -to the memory Valkey can use. If this limit is reached, Valkey will start to reply -with an error to write commands (but will continue to accept read-only -commands). - -You can also configure Valkey to evict keys when the max memory limit -is reached. See the [eviction policy docs](lru-cache.md) for more information on this. - -## Background saving fails with a fork() error on Linux? - -Short answer: `echo 1 > /proc/sys/vm/overcommit_memory` :) - -And now the long one: - -The Valkey background saving schema relies on the copy-on-write semantic of the `fork` system call in -modern operating systems: Valkey forks (creates a child process) that is an -exact copy of the parent. The child process dumps the DB on disk and finally -exits. In theory the child should use as much memory as the parent being a -copy, but actually thanks to the copy-on-write semantic implemented by most -modern operating systems the parent and child process will _share_ the common -memory pages. A page will be duplicated only when it changes in the child or in -the parent. Since in theory all the pages may change while the child process is -saving, Linux can't tell in advance how much memory the child will take, so if -the `overcommit_memory` setting is set to zero the fork will fail unless there is -as much free RAM as required to really duplicate all the parent memory pages. -If you have a Valkey dataset of 3 GB and just 2 GB of free -memory it will fail. - -Setting `overcommit_memory` to 1 tells Linux to relax and perform the fork in a -more optimistic allocation fashion, and this is indeed what you want for Valkey. - -You can refer to the [proc(5)][proc5] man page for explanations of the -available values. - -[proc5]: https://man7.org/linux/man-pages/man5/proc.5.html - -## Are Valkey on-disk snapshots atomic? - -Yes, the Valkey background saving process is always forked when the server is -outside of the execution of a command, so every command reported to be atomic -in RAM is also atomic from the point of view of the disk snapshot. - -## How can Valkey use multiple CPUs or cores? - -Enable I/O threading to offload client communication to threads. -In Valkey 8, the I/O threading implementation has been rewritten and greatly improved. -Reading commands from clients and writing replies back uses considerable CPU time. -By offloading this work to separate threads, the main thread can focus on executing commands. - -You can also start multiple instances of Valkey in the same box and combine them into a [cluster](cluster-tutorial.md). - -## What is the maximum number of keys a single Valkey instance can hold? What is the maximum number of elements in a Hash, List, Set, and Sorted Set? - -Valkey can handle up to 232 keys, and was tested in practice to -handle at least 250 million keys per instance. - -Every hash, list, set, and sorted set, can hold 232 elements. - -In other words your limit is likely the available memory in your system. - -## Why does my replica have a different number of keys than its primary instance? - -If you use keys with limited time to live (Valkey expires) this is normal behavior. This is what happens: - -* The primary generates an RDB file on the first synchronization with the replica. -* The RDB file will not include keys already expired in the primary but which are still in memory. -* These keys are still in the memory of the Valkey primary, even if logically expired. They'll be considered non-existent, and their memory will be reclaimed later, either incrementally or explicitly on access. While these keys are not logically part of the dataset, they are accounted for in the `INFO` output and in the `DBSIZE` command. -* When the replica reads the RDB file generated by the primary, this set of keys will not be loaded. - -Because of this, it's common for users with many expired keys to see fewer keys in the replicas. However, logically, the primary and replica will have the same content. - -## Why did Linux Foundation start the Valkey project? - -Read about [the history of Valkey](history.md). diff --git a/topics/forkless.md b/topics/forkless.md deleted file mode 100644 index 6959d268..00000000 --- a/topics/forkless.md +++ /dev/null @@ -1,127 +0,0 @@ ---- -title: Forkless operations -description: Overview of forkless operations ---- - -Valkey uses the `fork()` system call for several background operations, including saving the dataset to disk and fully synchronizing replicas. -Fork-based operations have been part of Valkey since its earliest days and are a simple, proven approach. -They also come with tradeoffs that can matter for some workloads. -One of them is memory usage: the forked child process shares memory with Valkey through copy-on-write, so memory usage can grow while the child is running. -In extreme cases, where writes are spread across much of the dataset during that time, memory usage can grow by up to 2x. - -Valkey 9.2 introduces **forkless save** and **forkless full sync**, which perform these two operations without calling `fork()`. -Valkey takes the snapshot inside the running process, which keeps memory usage steadier and more predictable while the operation runs. -In this case, the tradeoff is that writes can briefly wait and latency can be slightly higher during the operation, as discussed later in [Impact on clients](#impact-on-clients). - -It is important to note that forkless is not yet a full replacement for `fork()`. -In some situations, Valkey falls back to a fork-based save or full sync even when it is configured to prefer forkless operations. -When using forkless, it is highly encouraged to plan the configuration in a way that avoids these fallbacks, and to take into account that other operations, such as AOF rewrite and atomic slot migration, still use `fork()`. -This page describes how to plan for forkless operations. - -## Enabling forkless operations - -Forkless operations are disabled by default. -Two configuration parameters control them: - -- `forkless-infrastructure-enabled`: enables support for forkless operations. - It is `no` by default and can only be set at startup. - When enabled, Valkey stores an additional 4 bytes with each key. - This setting does not change how saves or full syncs are performed on its own. -- `forkless-policy`: selects how background saves and full syncs are performed. - The default, `require-fork`, always uses `fork()`. - `prefer-forkless` uses forkless operations when possible and falls back to `fork()` otherwise, as described in [When Valkey uses fork instead](#when-valkey-uses-fork-instead). - It can be changed at runtime with `CONFIG SET`, and can only be set to `prefer-forkless` when `forkless-infrastructure-enabled` is `yes`. - -### When Valkey uses fork instead - -As the name suggests, `prefer-forkless` does not guarantee that every save and full sync is forkless. -Before each operation, Valkey checks whether a forkless operation is possible, and uses `fork()` when it is not. -Each fallback is logged to the server log, and counted in the `debug` section of `INFO`. - -Valkey uses `fork()` for saves when: - -- **A loaded module does not support forkless operations.** - Every loaded module must declare support, as described in [For module developers](#for-module-developers). - Counted in `forkless_fallbacks_module`. -- **The node is receiving slots through atomic slot migration.** - This applies to the target node of a [`CLUSTER MIGRATESLOTS`](atomic-slot-migration.md) operation, for example while resharding. - Saves and full syncs on that node use `fork()` until the migration finishes. - `CLUSTER GETSLOTMIGRATIONS` shows which migrations are in progress. - Counted in `forkless_fallbacks_slot_import`. - -For full syncs, the conditions above apply, and Valkey additionally uses `fork()` when: - -- **The replica does not support forkless full sync.** - This is the case when any of the following is true: - - The replica runs a Valkey version older than 9.2. - - The replica uses `repl-diskless-load swapdb`, and the primary uses diskless sync (`repl-diskless-sync yes`, the default). - - The replica loads a module that does not support forkless operations, and the primary uses diskless sync. - - Counted in `forkless_fallbacks_missing_inband_repl`. -- **Replication compression is enabled.** - When `repl-compression` is enabled on both the primary and the replica, the full sync uses `fork()`. - Counted in `forkless_fallbacks_compression`. -- **A client requests an RDB file that contains only functions**, for example with `valkey-cli --functions-rdb`. - Counted in `forkless_fallbacks_exclude_data`. - -### Events that cancel forkless operations - -Some events that do not affect a fork-based save or full sync cancel a forkless one: - -- **`FLUSHDB`** cancels a forkless save to disk, including the save performed for a disk-based full sync (`repl-diskless-sync no`). - During a diskless full sync, `FLUSHDB` cancels the sync only when the flushed database holds more than half of all keys. - Otherwise, the flush is sent to the replica as part of the sync. -- **The start of a slot import** cancels a forkless full sync on the target node of an atomic slot migration. - The replica's next full sync uses `fork()`, as described above. - -When a full sync is cancelled, the replica reconnects and starts a new full sync. -When a save is cancelled, automatic saves configured with `save` are retried later, and a save started with `BGSAVE` must be started again. - -## Monitoring forkless operations - -The `persistence` section of `INFO` shows which method Valkey uses: - -- `rdb_current_bgsave_type`: the method of the save or full sync in progress, `fork` or `forkless`, or `none` when no save is running. -- `rdb_last_bgsave_type`: the method of the last completed save to disk. -- `forkless_estimated_seconds_remaining`: an estimate of the time left in the forkless save or full sync in progress, or `-1` when none is running. - -The server log records the method of each full sync, and the reason for each fallback. -For debugging, the `debug` section of `INFO` also includes the `forkless_fallbacks_*` counters described in [When Valkey uses fork instead](#when-valkey-uses-fork-instead). - -## Impact on clients - -A forkless operation runs while Valkey keeps serving clients, so it can affect commands that write to the dataset: - -- **Writes can briefly wait.** - A write to a key during a forkless operation has a small risk of waiting briefly. - The larger the key, the higher the risk and the longer the wait. - String values of up to 512 bytes are generally not affected. - Read commands do not wait, except for the few that modify data internally, such as `PFCOUNT`. -- **Latency can be slightly higher.** - Command latency can be slightly higher while a forkless operation runs, compared to a comparable fork-based operation. - -Workloads with very large keys that receive frequent writes are the most affected. -Splitting very large collections into smaller keys reduces both the chance that a write waits and how long it waits. - -## For module developers - -A module declares that it supports forkless operations by setting the `VALKEYMODULE_OPTIONS_HANDLE_FORKLESS` option with `ValkeyModule_SetModuleOptions`. -Forkless operations are used only when every loaded module sets this option. -A module that does not set it keeps working as before, and Valkey uses `fork()` for saves and full syncs while that module is loaded, even when `forkless-policy` is set to `prefer-forkless`. - -By setting the option, a module agrees to the following: - -- **RDB save callbacks must be thread-safe.** - A module that registers a data type declares that its RDB save callbacks can run on a background thread, at the same time as commands run on the main thread. - The value being saved does not change during the callback, but any other module state that the callback reads must be protected with synchronization. -- **Auxiliary save callbacks must be small.** - An `aux_save` or `aux_save2` callback must run only in the `VALKEYMODULE_AUX_BEFORE_RDB` section and save only a limited amount of data, because it runs on the main thread and blocks it during a forkless operation. -- **Opening a key for write can return `NULL`.** - While a forkless operation is running, `ValkeyModule_OpenKey` with `VALKEYMODULE_WRITE` can return `NULL` for keys that the module command did not declare. - For the keys that a module command declares, the risk is the same as for other writes, as described in [Impact on clients](#impact-on-clients): the command can briefly wait. - For undeclared keys, including keys opened outside of a command, such as from a timer, there is a chance that `NULL` is returned. - From the module's point of view, when `NULL` is returned can seem random, because it depends on internal server state that changes rapidly and cannot generally be monitored. - Therefore, modules should be designed so that every such write can handle a `NULL` return. - -A module cannot be loaded while a forkless save or full sync is running. -`MODULE LOAD` returns an error, and the module can be loaded after the operation finishes. diff --git a/topics/functions-intro.md b/topics/functions-intro.md deleted file mode 100644 index 1d503de8..00000000 --- a/topics/functions-intro.md +++ /dev/null @@ -1,434 +0,0 @@ ---- -title: "Functions" -description: > - Scripting with functions stored on the server ---- - -Valkey Functions is an API for managing code to be executed on the server. -This feature is as a complement to [EVAL scripts](eval-intro.md). - -## What's wrong with EVAL? - -There's nothing wrong with `EVAL`, but there are some differences between EVAL scripts and Functions. -With the [`EVAL`](../commands/eval.md) command, scripts are sent to the server for immediate execution. -The core use cases for `EVAL` scripts is executing part of your application logic inside Valkey, efficiently and atomically. -Such script can perform conditional updates across multiple keys, possibly combining several different data types. - -Using `EVAL` requires that the application sends the entire script for execution every time. -Because this results in network and script compilation overheads, Valkey provides an optimization in the form of the [`EVALSHA`](../commands/evalsha.md) command. -By first calling [`SCRIPT LOAD`](../commands/script-load.md) to obtain the script's SHA1, the application can invoke it repeatedly afterward with its digest alone. - -Valkey only caches the loaded scripts. -That means that the script cache can become lost at any time, such as after calling `SCRIPT FLUSH`, after restarting the server, or when failing over to a replica. -The application is responsible for reloading scripts during runtime if any are missing. -The underlying assumption is that scripts are a part of the application and not maintained by the Valkey server. - -This approach suits many light-weight scripting use cases, but introduces several difficulties once an application becomes complex and relies more heavily on scripting, namely: - -1. All client application instances must maintain a copy of all scripts. That means having some mechanism that applies script updates to all of the application's instances. -1. Calling cached scripts within the context of a [transaction](transactions.md) increases the probability of the transaction failing because of a missing script. Being more likely to fail makes using cached scripts as building blocks of workflows less attractive. -1. SHA1 digests are not readable for humans, making debugging the system hard (e.g. in a [`MONITOR`](../commands/monitor.md) session). -1. When used naively, `EVAL` promotes an anti-pattern in which the client application renders verbatim scripts instead of responsibly using the [`KEYS` and `ARGV` Lua APIs](lua-api.md#runtime-globals). -1. Because they are ephemeral, a script can't call another script. This makes sharing and reusing code between scripts nearly impossible, short of client-side preprocessing. - -To address these needs while avoiding breaking changes to already-established and well-liked ephemeral scripts, functions were introduced in version 7.0. - -## What are Valkey Functions? - -Functions provide the same core functionality as scripts but are first-class artifacts of the database. -Valkey manages functions as an integral part of the database and ensures their availability via data persistence and replication. -Because functions are part of the database and therefore declared before use, applications aren't required to load them during runtime nor risk aborted transactions. -An application that uses functions depends only on their APIs rather than on the embedded script logic in the database. - -Whereas ephemeral scripts are considered a part of the application's domain, functions extend the database server itself with user-provided logic. -They can be loaded at startup and be used repeatedly by various applications and clients. -Functions are also persisted to the AOF file and replicated from primary to replicas, so they are as durable as the data itself. -When Valkey is used as an ephemeral cache, additional mechanisms (described below) are required to make functions more durable. - -Functions also simplify development by enabling code sharing. -Every function has a user-defined name and belongs to a library, and a library can consist of multiple functions. -The library's contents are immutable, and selective updates of its functions aren't allowed. -Instead, libraries are updated as a whole with all of their functions together in one operation. -This allows calling functions from other functions within the same library, or sharing code between functions by using a common code in library-internal methods, that can also take language native arguments. - -Like all other operations in Valkey, the execution of a function is atomic. -A function's execution blocks all server activities during its entire time, similarly to the semantics of [transactions](transactions.md). -These semantics mean that all of the script's effects either have yet to happen or had already happened. -The blocking semantics of an executed function apply to all connected clients at all times. -Because running a function blocks the Valkey server, functions are meant to finish executing quickly, so you should avoid using long-running functions. - -Functions are written in [Lua 5.1](lua-api.md). -Valkey functions can use all of Lua's available capabilities to ephemeral scripts, -with the only exception being the [Valkey Lua scripts debugger](ldb.md). - -## Loading libraries and functions - -Let's explore Valkey Functions via some tangible examples and Lua snippets. - -At this point, if you're unfamiliar with Lua in general and specifically in Valkey, you may benefit from reviewing some of the examples in [Introduction to Eval Scripts](eval-intro.md) and [Lua API](lua-api.md) pages for a better grasp of the language. - -Every Valkey function belongs to a library. -Loading a library to the database is done with the [`FUNCTION LOAD`](../commands/function-load.md) command. -The library source code must start with a Shebang line that provides metadata about the library, like the language (always "lua") and the library name. -The Shebang format is: - -``` -#!lua name= -``` - -Let's try loading an empty library: - -``` -127.0.0.1:6379> FUNCTION LOAD "#!lua name=mylib\n" -(error) ERR No functions registered -``` - -The error is expected, as there are no functions in the loaded library. Every library needs to include at least one registered function to load successfully. -A registered function is named and acts as an entry point to the library. -When the target execution engine handles the `FUNCTION LOAD` command, it registers the library's functions. - -The Lua engine compiles and evaluates the library source code when loaded, and expects functions to be registered by calling the `server.register_function()` API. - -The following snippet demonstrates a simple library registering a single function named _knockknock_, returning a string reply: - -```lua -#!lua name=mylib -server.register_function( - 'knockknock', - function() return 'Who\'s there?' end -) -``` - -In the example above, we provide two arguments about the function to Lua's `server.register_function()` API: its registered name and a callback. - -We can load our library and use `FCALL` to call the registered function: - -``` -127.0.0.1:6379> FUNCTION LOAD "#!lua name=mylib\nserver.register_function('knockknock', function() return 'Who\\'s there?' end)" -mylib -127.0.0.1:6379> FCALL knockknock 0 -"Who's there?" -``` - -Notice that the `FUNCTION LOAD` command returns the name of the loaded library, this name can later be used `FUNCTION LIST` and `FUNCTION DELETE`. - -We've provided [`FCALL`](../commands/fcall.md) with two arguments: the function's registered name and the numeric value `0`. This numeric value indicates the number of key names that follow it (the same way `EVAL` and `EVALSHA` works). - -We'll explain immediately how key names and additional arguments are available to the function. As this simple example doesn't involve keys, we simply use 0 for now. - -## Input keys and regular arguments - -Before we move to the following example, it is vital to understand the distinction Valkey makes between arguments that are names of keys and those that aren't. - -While key names in Valkey are just strings, unlike any other string values, these represent keys in the database. -The name of a key is a fundamental concept in Valkey and is the basis for operating the Valkey Cluster. - -**Important:** -To ensure the correct execution of Valkey Functions, both in standalone and clustered deployments, all names of keys that a function accesses must be explicitly provided as input key arguments. - -Any input to the function that isn't the name of a key is a regular input argument. - -Now, let's pretend that our application stores some of its data in Hashes. -We want an [`HSET`](../commands/hset.md)-like way to set and update fields in said Hashes and store the last modification time in a new field named `_last_modified_`. -We can implement a function to do all that. - -Our function will call [`TIME`](../commands/time.md) to get the server's clock reading and update the target Hash with the new fields' values and the modification's timestamp. -The function we'll implement accepts the following input arguments: the Hash's key name and the field-value pairs to update. - -The Lua API for Valkey Functions makes these inputs accessible as the first and second arguments to the function's callback. -The callback's first argument is a Lua table populated with all key names inputs to the function. -Similarly, the callback's second argument consists of all regular arguments. - -The following is a possible implementation for our function and its library registration: - -```lua -#!lua name=mylib - -local function my_hset(keys, args) - local hash = keys[1] - local time = server.call('TIME')[1] - return server.call('HSET', hash, '_last_modified_', time, unpack(args)) -end - -server.register_function('my_hset', my_hset) -``` - -If we create a new file named _mylib.lua_ that consists of the library's definition, we can load it like so (without stripping the source code of helpful whitespaces): - -```bash -$ cat mylib.lua | valkey-cli -x FUNCTION LOAD REPLACE -``` - -We've added the `REPLACE` modifier to the call to `FUNCTION LOAD` to tell Valkey that we want to overwrite the existing library definition. -Otherwise, we would have gotten an error from Valkey complaining that the library already exists. - -Now that the library's updated code is loaded to Valkey, we can proceed and call our function: - -``` -127.0.0.1:6379> FCALL my_hset 1 myhash myfield "some value" another_field "another value" -(integer) 3 -127.0.0.1:6379> HGETALL myhash -1) "_last_modified_" -2) "1640772721" -3) "myfield" -4) "some value" -5) "another_field" -6) "another value" -``` - -In this case, we had invoked `FCALL` with _1_ as the number of key name arguments. -That means that the function's first input argument is a name of a key (and is therefore included in the callback's `keys` table). -After that first argument, all following input arguments are considered regular arguments and constitute the `args` table passed to the callback as its second argument. - -## Expanding the library - -We can add more functions to our library to benefit our application. -The additional metadata field we've added to the Hash shouldn't be included in responses when accessing the Hash's data. -On the other hand, we do want to provide the means to obtain the modification timestamp for a given Hash key. - -We'll add two new functions to our library to accomplish these objectives: - -1. The `my_hgetall` Valkey Function will return all fields and their respective values from a given Hash key name, excluding the metadata (i.e., the `_last_modified_` field). -1. The `my_hlastmodified` Valkey Function will return the modification timestamp for a given Hash key name. - -The library's source code could look something like the following: - -```lua -#!lua name=mylib - -local function my_hset(keys, args) - local hash = keys[1] - local time = server.call('TIME')[1] - return server.call('HSET', hash, '_last_modified_', time, unpack(args)) -end - -local function my_hgetall(keys, args) - server.setresp(3) - local hash = keys[1] - local res = server.call('HGETALL', hash) - res['map']['_last_modified_'] = nil - return res -end - -local function my_hlastmodified(keys, args) - local hash = keys[1] - return server.call('HGET', hash, '_last_modified_') -end - -server.register_function('my_hset', my_hset) -server.register_function('my_hgetall', my_hgetall) -server.register_function('my_hlastmodified', my_hlastmodified) -``` - -While all of the above should be straightforward, note that the `my_hgetall` also calls [`server.setresp(3)`](lua-api.md#server.setresp). -That means that the function expects [RESP3](protocol.md) replies after calling `server.call()`, which, unlike the default RESP2 protocol, returns the replies as maps (associative arrays). -Doing so allows the function to delete (or set to `nil` as is the case with Lua tables) specific fields from the reply, and in our case, the `_last_modified_` field. - -Assuming you've saved the library's implementation in the _mylib.lua_ file, you can replace it with: - -```bash -$ cat mylib.lua | valkey-cli -x FUNCTION LOAD REPLACE -``` - -Once loaded, you can call the library's functions with `FCALL`: - -``` -127.0.0.1:6379> FCALL my_hgetall 1 myhash -1) "myfield" -2) "some value" -3) "another_field" -4) "another value" -127.0.0.1:6379> FCALL my_hlastmodified 1 myhash -"1640772721" -``` - -You can also get the library's details with the `FUNCTION LIST` command: - -``` -127.0.0.1:6379> FUNCTION LIST -1) 1) "library_name" - 2) "mylib" - 3) "engine" - 4) "LUA" - 5) "functions" - 6) 1) 1) "name" - 2) "my_hset" - 3) "description" - 4) (nil) - 5) "flags" - 6) (empty array) - 2) 1) "name" - 2) "my_hgetall" - 3) "description" - 4) (nil) - 5) "flags" - 6) (empty array) - 3) 1) "name" - 2) "my_hlastmodified" - 3) "description" - 4) (nil) - 5) "flags" - 6) (empty array) -``` - -You can see that it is easy to update our library with new capabilities. - -## Reusing code in the library - -On top of bundling functions together into database-managed software artifacts, libraries also facilitate code sharing. -We can add to our library an error handling helper function called from other functions. -The helper function `check_keys()` verifies that the input _keys_ table has a single key. -Upon success it returns `nil`, otherwise it returns an [error reply](lua-api.md#server.error_reply). - -The updated library's source code would be: - -```lua -#!lua name=mylib - -local function check_keys(keys) - local error = nil - local nkeys = table.getn(keys) - if nkeys == 0 then - error = 'Hash key name not provided' - elseif nkeys > 1 then - error = 'Only one key name is allowed' - end - - if error ~= nil then - server.log(server.LOG_WARNING, error); - return server.error_reply(error) - end - return nil -end - -local function my_hset(keys, args) - local error = check_keys(keys) - if error ~= nil then - return error - end - - local hash = keys[1] - local time = server.call('TIME')[1] - return server.call('HSET', hash, '_last_modified_', time, unpack(args)) -end - -local function my_hgetall(keys, args) - local error = check_keys(keys) - if error ~= nil then - return error - end - - server.setresp(3) - local hash = keys[1] - local res = server.call('HGETALL', hash) - res['map']['_last_modified_'] = nil - return res -end - -local function my_hlastmodified(keys, args) - local error = check_keys(keys) - if error ~= nil then - return error - end - - local hash = keys[1] - return server.call('HGET', keys[1], '_last_modified_') -end - -server.register_function('my_hset', my_hset) -server.register_function('my_hgetall', my_hgetall) -server.register_function('my_hlastmodified', my_hlastmodified) -``` - -After you've replaced the library in Valkey with the above, you can immediately try out the new error handling mechanism: - -``` -127.0.0.1:6379> FCALL my_hset 0 myhash nope nope -(error) Hash key name not provided -127.0.0.1:6379> FCALL my_hgetall 2 myhash anotherone -(error) Only one key name is allowed -``` - -And your Valkey log file should have lines in it that are similar to: - -``` -... -20075:M 1 Jan 2022 16:53:57.688 # Hash key name not provided -20075:M 1 Jan 2022 16:54:01.309 # Only one key name is allowed -``` - -## Functions in cluster - -As noted above, Valkey automatically handles propagation of loaded functions to replicas. -In a [cluster](cluster-tutorial.md), it is necessary to load functions to all primaries. - -As one of the goals of functions is to live separately from the client application, this should not be part of the Valkey client library responsibilities. Instead, `valkey-cli --cluster-only-primaries --cluster call host:port FUNCTION LOAD ...` can be used to execute the load command on all primary nodes. - -Also, note that `valkey-cli --cluster add-node` automatically takes care to propagate the loaded functions from one of the existing nodes to the new node. - -## Functions and ephemeral Valkey instances - -In some cases there may be a need to start a fresh Valkey server with a set of functions pre-loaded. Common reasons for that could be: - -* Starting Valkey in a new environment -* Re-starting an ephemeral (cache-only) Valkey, that uses functions - -In such cases, we need to make sure that the pre-loaded functions are available before Valkey accepts inbound user connections and commands. - -To do that, it is possible to use `valkey-cli --functions-rdb` to extract the functions from an existing server. This generates an RDB file that can be loaded by Valkey at startup. - -## Function flags - -Valkey needs to have some information about how a function is going to behave when executed, in order to properly enforce resource usage policies and maintain data consistency. - -For example, Valkey needs to know that a certain function is read-only before permitting it to execute using `FCALL_RO` on a read-only replica. - -By default, Valkey assumes that all functions may perform arbitrary read or write operations. Function Flags make it possible to declare more specific function behavior at the time of registration. Let's see how this works. - -In our previous example, we defined two functions that only read data. We can try executing them using `FCALL_RO` against a read-only replica. - -``` -127.0.0.1:6379> FCALL_RO my_hgetall 1 myhash -(error) ERR Can not execute a function with write flag using fcall_ro. -``` - -Valkey returns this error because a function can, in theory, perform both read and write operations on the database. -As a safeguard and by default, Valkey assumes that the function does both, so it blocks its execution. -The server will reply with this error in the following cases: - -1. Executing a function with `FCALL` against a read-only replica. -2. Using `FCALL_RO` to execute a function. -3. A disk error was detected (Valkey is unable to persist so it rejects writes). - -In these cases, you can add the `no-writes` flag to the function's registration, disable the safeguard and allow them to run. -To register a function with flags use the [named arguments](lua-api.md#server.register_function_named_args) variant of `server.register_function`. - -The updated registration code snippet from the library looks like this: - -```lua -server.register_function('my_hset', my_hset) -server.register_function{ - function_name='my_hgetall', - callback=my_hgetall, - flags={ 'no-writes' } -} -server.register_function{ - function_name='my_hlastmodified', - callback=my_hlastmodified, - flags={ 'no-writes' } -} -``` - -Once we've replaced the library, Valkey allows running both `my_hgetall` and `my_hlastmodified` with `FCALL_RO` against a read-only replica: - -``` -127.0.0.1:6379> FCALL_RO my_hgetall 1 myhash -1) "myfield" -2) "some value" -3) "another_field" -4) "another value" -127.0.0.1:6379> FCALL_RO my_hlastmodified 1 myhash -"1640772721" -``` - -For the complete documentation flags, please refer to [Script flags](lua-api.md#script_flags). diff --git a/topics/geospatial.md b/topics/geospatial.md deleted file mode 100644 index e80204d1..00000000 --- a/topics/geospatial.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: "Geospatial" -description: > - Introduction to the Valkey Geospatial data type ---- - -Geospatial indexes let you store coordinates and search for them. -This data structure is useful for finding nearby points within a given radius, bounding box, or polygon shaped area. - -## Basic commands - -* `GEOADD` adds a location to a given geospatial index (note that longitude comes before latitude with this command). -* `GEOSEARCH` returns locations with a given radius, bounding box, or polygon shaped area. - -See the [complete list of geospatial index commands](../commands/#geo). - - -## Examples - -Suppose you're building a mobile app that lets you find all of the bike rental stations closest to your current location. - -Add several locations to a geospatial index: -``` -127.0.0.1:6379> GEOADD bikes:rentable -122.27652 37.805186 station:1 -(integer) 1 -127.0.0.1:6379> GEOADD bikes:rentable -122.2674626 37.8062344 station:2 -(integer) 1 -127.0.0.1:6379> GEOADD bikes:rentable -122.2469854 37.8104049 station:3 -(integer) 1 -``` - -Find all locations within a 5 kilometer radius of a given location, and return the distance to each location: -``` -127.0.0.1:6379> GEOSEARCH bikes:rentable FROMLONLAT -122.2612767 37.7936847 BYRADIUS 5 km WITHDIST -1) 1) "station:1" - 2) "1.8523" -2) 1) "station:2" - 2) "1.4979" -3) 1) "station:3" - 2) "2.2441" -``` - -Searching for all stations in a custom defined area or an irregularly shaped area by using the `BYPOLYGON` search option. -In this example, we are searching within the Downtown Oakland area using polygon vertices that enclose this area. - -``` -127.0.0.1:6379> GEOSEARCH bikes:rentable BYPOLYGON 5 -122.27490648273738 37.80962123634505 -122.26098358494566 37.80439605986292 -122.26584066888834 37.79562786995921 -122.27929133687068 37.80124920239011 -122.2783398259964 37.80451967488848 -1) "station:1" -2) "station:2" -``` diff --git a/topics/hashes.md b/topics/hashes.md deleted file mode 100644 index 5077f9a5..00000000 --- a/topics/hashes.md +++ /dev/null @@ -1,116 +0,0 @@ ---- -title: "Hashes" -description: > - Introduction to Hashes ---- - -Hashes are record types structured as collections of field-value pairs. -You can use hashes to represent basic objects and to store groupings of counters, among other things. - -``` -127.0.0.1:6379> HSET bike:1 model Deimos brand Ergonom type 'Enduro bikes' price 4972 -(integer) 4 -127.0.0.1:6379> HGET bike:1 model -"Deimos" -127.0.0.1:6379> HGET bike:1 price -"4972" -127.0.0.1:6379> HGETALL bike:1 -1) "model" -2) "Deimos" -3) "brand" -4) "Ergonom" -5) "type" -6) "Enduro bikes" -7) "price" -8) "4972" -``` - -While hashes are handy to represent *objects*, actually the number of fields you can -put inside a hash has no practical limits (other than available memory), so you can use -hashes in many different ways inside your application. - -The command `HSET` sets multiple fields of the hash, while `HGET` retrieves -a single field. `HMGET` is similar to `HGET` but returns an array of values: - -``` -127.0.0.1:6379> HMGET bike:1 model price no-such-field -1) "Deimos" -2) "4972" -3) (nil) -``` - -There are commands that are able to perform operations on individual fields -as well, like `HINCRBY`: - -``` -127.0.0.1:6379> HINCRBY bike:1 price 100 -(integer) 5072 -127.0.0.1:6379> HINCRBY bike:1 price -100 -(integer) 4972 -``` - -It is worth noting that small hashes (i.e., a few elements with small values) are -encoded in special way in memory that make them very memory efficient. - -## Basic commands - -* `HSET` sets the value of one or more fields on a hash. -* `HGET` returns the value at a given field. -* `HMGET` returns the values at one or more given fields. -* `HINCRBY` increments the value at a given field by the integer provided. - -See the [complete list of hash commands](../commands/#hash). - -## Examples - -* Store counters for the number of times bike:1 has been ridden, has crashed, or has changed owners: -``` -127.0.0.1:6379> HINCRBY bike:1:stats rides 1 -(integer) 1 -127.0.0.1:6379> HINCRBY bike:1:stats rides 1 -(integer) 2 -127.0.0.1:6379> HINCRBY bike:1:stats rides 1 -(integer) 3 -127.0.0.1:6379> HINCRBY bike:1:stats crashes 1 -(integer) 1 -127.0.0.1:6379> HINCRBY bike:1:stats owners 1 -(integer) 1 -127.0.0.1:6379> HGET bike:1:stats rides -"3" -127.0.0.1:6379> HMGET bike:1:stats owners crashes -1) "1" -2) "1" -``` - -## Field expiration - -In Valkey 9.0 we added the ability to associate an expiration time with a hash field. When set, the field and it's corresponding value are automatically deleted after the time has past. -Once a hash field expiration time is past, it will no longer be available and all of the hash command APIs will treat this field as "nonexistent". -Note that expired hash fields are deleted via a periodic job. -For this reason it might take time between when fields logically expire and when hash fields are deleted. -During this time, logically expired fields still consume memory and some some hash commands (e.g. [`HLEN`](../commands/hlen.md)) might still take logically expired fields into account in hash object cardinality calculations. -Another side effect of using volatile fields (fields with time to live) in hash objects, is the ability to randomly choose from hash objects. When large hash objects have most of their volatile fields logically expired, some commands like [`HRANDFIELD`](../commands/hrandfield.md) might not be able to collect elements which are not logically expired and may return an empty reply. - -### Command API - -[`HEXPIRE`](../commands/hexpire.md), [`HPEXPIRE`](../commands/hpexpire.md), [`HEXPIREAT`](../commands/hexpireat.md), [`HPEXPIREAT`](../commands/hpexpireat.md) and [`HPERSIST`](../commands/hpersist.md) commands are used in order to set or manipulate the expiration time of specific hash fields. - -[`HEXPIRETIME`](../commands/hexpiretime.md), [`HEXPIRETIME`](../commands/hpexpiretime.md), [`HTTL`](../commands/httl.md) and [`HPTTL`](../commands/hpttl.md) commands are used in order to query the expiration time of specific hash fields. - -[`HSETEX`](../commands/hsetex.md) allows setting multiple hash fields and values while also associate an expiration time with each field. - -[`HGETEX`](../commands/hgetex.md) allows fetching multiple hash fields values while also mutating their expiration time. - -Note that some commands which override hash fields (e.g. `HSET` and `HMSET`) will remove an expiration time associated with a hash field. -The [`HSETEX`](../commands/hsetex.md) supports the `KEEPTTL` flag, which allows overriding hash fields without mutating their expiration time. - -## Performance - -Most Hash commands are O(1). - -A few commands - such as `HKEYS`, `HVALS`, and `HGETALL` - are O(n), where _n_ is the number of field-value pairs. - -## Limits - -Every hash can store up to 4,294,967,295 (2^32 - 1) field-value pairs. -In practice, your hashes are limited only by the overall memory on the VMs hosting your Valkey deployment. diff --git a/topics/history.md b/topics/history.md deleted file mode 100644 index 66ba9117..00000000 --- a/topics/history.md +++ /dev/null @@ -1,184 +0,0 @@ ---- -title: "History" -description: How the Valkey project started ---- - -Valkey is a fork of the open-source Redis (REmote DIctionary Server) database -created in 2009 by the Italian hacker Salvatore “antirez” Sanfilippo. He -announced it on [Hacker News][hn] on Feb 25, 2009. [GitHub][gh] and -[Instagram][insta] were among the early adopters. - -[hn]: https://news.ycombinator.com/item?id=494649 -[gh]: https://github.blog/2009-11-03-introducing-resque/ -[insta]: https://instagram-engineering.com/storing-hundreds-of-millions-of-simple-key-value-pairs-in-redis-1091ae80f74c - -Early works of Salvatore Sanfilippo ------------------------------------ - -At the time, Salvatore “antirez” was already known for inventing the [Idle -scan][idle-scan] port scanning technique, the [Hping][hping] TCP/IP packet -generator and analyzer, the [Jim] TCL interpreter and the [LLOOGG][lloogg] -real-time log analyzer. To improve it, he created an in-memory database called -called [LLOOGG Memory DB][lmdb], which was a proof-of-concept of what later -became Redis and Valkey. - -[idle-scan]: https://en.wikipedia.org/wiki/Idle_scan -[hping]: https://en.wikipedia.org/wiki/Hping -[jim]: https://jim.tcl-lang.org/index.html/doc/www/www/about/ -[lloogg]: https://github.com/antirez/lloogg/blob/master/README.md -[lmdb]: https://gist.github.com/antirez/6ca04dd191bdb82aad9fb241013e88a8 - -Early contributions and sponsorships ------------------------------------- - -During 2009, Engine Yard contributed blocking POP (BLPOP) and part of the -Virtual Memory implementation (later deleted), Hitmeister contributed part of -the Cluster implementation and Citrusbyte contributed part of Virtual Memory -implementation. In 2010, Slicehost (acquired by Rackspace) provided Virtual -Machines for testing in a virtualized environment and Linode provided virtual -machines for testing in a virtualized environment. Also thanks to the following -people or organizations that donated to the Project: Emil Vladev, [Brad -Jasper](https://bradjasper.com/) and [Mrkris](http://mrkris.com/). The -[Shuttleworth Foundation](https://en.wikipedia.org/wiki/Shuttleworth_Foundation) -donated 5000 USD to the project in form of a flash grant. - -Pieter Noordhuis and Matt Stancliff provided a significant amount of code and -ideas to the core and client libraries. - -The time with VMware --------------------- - -In March, 2010, Sanfilippo was hired by [VMware](https://vmware.com) to work on -Redis and Redis Tools. In his blog post [VMware: the new Redis -home][antirez-vmware], he writes: - -[antirez-vmware]: https://web.archive.org/web/20241017012850/http://oldblog.antirez.com/post/vmware-the-new-redis-home.html - -> Not only Redis will remain a totally open source project, but Redis Tools will -> be open sourced also (and this was an idea I got from VMware itself!). -> -> This is why I'm truly excited about joining VMware: together we'll build a -> better, free Redis, bringing Redis development to another level. - -VMware, and later Pivotal (a VMware spin-off), provided a 24 GB RAM workstation -for Salvatore to run the Redis CI test and other long running tests. Later, -Salvatore equipped the server with an SSD drive in order to test in the same -hardware with rotating and flash drives. VMware sponsored the project until May -2013, with the work of Salvatore Sanfilippo and Pieter Noordhuis. From May 2013 -to June 2015, Salvatore's work was sponsored by Pivotal. - -The Redis Labs era ------------------- - -In 2011, a company called Garantia Data was founded and started providing -database services based on Redis. In 2013, Garantia Data was changing its name -to RedisDB, but [decided to withdraw the change][redisdb] after complaints by -Sanfilippo: - -[redisdb]: https://www.forbes.com/sites/benkepes/2013/11/04/was-garantia-is-now-redisdb-either-way-nosql-is-hot/ - -> If this is true, it is not a good thing as the current informal rule was: use -> "Redis" in company names that are selling Redis services, but in a way that -> makes it distinguishable from Redis as a project. There are many examples like -> OpenRedis, RedisToGo, and so forth. However "RedisDB" is different as it is -> more like "We are Redis", (I even own the "redis-db.com" domain name since -> 2009! you can WHOIS it to check). So in my opinion calling the company -> "RedisDB" is wrong, especially since I and Garantia Data from time to time -> have friendly conversations as we are both part of the "Redis ecosystem", but -> I did not received any prior question about this issue. - -The following year, 2014, Garantia Data [changed its name to Redis Labs][redislabs]. - -[redislabs]: https://techcrunch.com/2014/01/29/database-provider-garantia-data-makes-another-name-change-this-time-to-redis-labs/ - -In 2015, Salvatore left Pivotal for Redis Labs. He writes in his blog post -[Thanks Pivotal, Hello Redis Labs](https://web.archive.org/web/20241123010805/http://antirez.com/news/91): - -> Redis Labs was willing to continue what VMware and Pivotal started. I'll be -> able to work as I do currently, spending all my time in the open source side -> of the project, while Redis Labs continues to provide Redis users with an -> hassles-free Redis experience of managed instances and products. - -In 2018, Redis Labs changed the license of some of its modules from AGPL to a -source-available license. The license prevents competing cloud providers from -offering these modules to customers and does therefore not fulfill the criteria -for an open source license. - -This was interpreted by some as if Redis is no longer open source. Sanfilippo -clarified on his blog [Redis will remain BSD licensed][antirez-remain-bsd]. - -Yiftach Shoolman, CTO and co-founder of Redis Labs, also clarified in in the -company's blog that [Redis' License is BSD and will remain -BSD][will-remain-bsd]. He repeated this promise in [a comment on Hacker -News][hn-always-bsd], writing “let me assure you that Redis remains and always -will remain, open source, BSD license”. - -[antirez-remain-bsd]: https://web.archive.org/web/20241111062719/http://antirez.com/news/120 -[will-remain-bsd]: https://redis.io/blog/redis-license-bsd-will-remain-bsd/ -[hn-always-bsd]: https://news.ycombinator.com/item?id=17819392 - -In 2020, Salvatore Sanfilippo announced in his blog post [The end of the Redis -adventure](https://web.archive.org/web/20241123005834/http://antirez.com/news/133) that he was stepping back as the Redis -maintainer, handing over the maintenance to Yossi Gottlieb and Oran Agra at -Redis Labs. The two created a “core team” to maintain the project and invited -Itamar Haber from Redis Labs, Zhao Zhao from Alibaba and Madelyn Olson from -Amazon. The members were selected “based on demonstrated, long-term personal -involvement and contributions”. This was described in the projects -[Governance][governance-2020] page which was the inspiration for the current -[Valkey governance][valkey-governance]. - -[governance-2020]: https://web.archive.org/web/20200709170526/https://redis.io/topics/governance -[valkey-governance]: https://github.com/valkey-io/valkey/blob/unstable/GOVERNANCE.md - -In 2021, the Redis Labs changed its name to Redis Ltd. or just Redis. In this -article, we're using the name Redis Ltd. when referring to the company to avoid -confusion. By this time, Redis Ltd. had acquired the trademark rights to the -name Redis and the logo from Sanfilippo. - -The end of open source Redis ----------------------------- - -In 2024, Redis Ltd. changed the license of Redis from the open source BSD -license to dual source-available licenses. This was announced in a blog post -[Redis Adopts Dual Source-Available Licensing][redis-source-avail] and the -license change was [committed to the repository][change-license-pr] the same day. - -[redis-source-avail]: https://redis.io/blog/redis-adopts-dual-source-available-licensing/ -[change-license-pr]: https://github.com/redis/redis/pull/13157 - -Neither of the licenses, Redis Source Available License (RSALv2) nor the Server -Side Public License (SSPLv1), are open source licenses, as neither meet the -criteria of an open source license. - -RSALv2 forbids the use of the software in database products, to prevent their -competitors from providing database products and services. Such a restriction is -not in line with [The Open Source Definition][osd], criterion #6 “The license -must not restrict anyone from making use of the program in a specific field of -endeavor” by the Open Source Initiative, nor “the freedom to run the program as -you wish, for any purpose (freedom 0)” in the Free Software Foundation's -definition of Free Software. The SSPL has similar restrictions, explained in the -[SSPL article on Wikipedia][sspl]. - -[osd]: https://opensource.org/osd -[sspl]: https://en.wikipedia.org/wiki/Server_Side_Public_License - -The birth of Valkey -------------------- - -Many contributors, including companies providing hosted Redis-derived or -Redis-compatible database services, just like Redis Ltd. does, have been using -and contributing to Redis just as long as Redis Ltd. has existed. It was -therefore and easy decision for many of them to continue the open source -development as usual under the BSD license. - -As Redis Ltd. owns the trademark rights to the name Redis, the open source -project needed to continue under a different name. A group of six active -contributors (one from each of Alibaba, Amazon, Ericsson, Google, Huawei and -Tencent) with the support from several other companies launched Valkey as a -Linux Foundation project. It was announced in a [press release][lf-press-1] only -eight days after Redis' license change. Three weeks later, a [second press -release][lf-press-2] announced seven more companies joining and the first -release, Valkey 7.2.5. - -[lf-press-1]: https://www.linuxfoundation.org/press/linux-foundation-launches-open-source-valkey-community -[lf-press-2]: https://www.linuxfoundation.org/press/valkey-community-announces-release-candidate-amid-growing-support-for-open-source-data-store diff --git a/topics/hotkeys.md b/topics/hotkeys.md deleted file mode 100644 index b0fe2665..00000000 --- a/topics/hotkeys.md +++ /dev/null @@ -1,135 +0,0 @@ ---- -title: "Hot key tracking" -description: > - Finding the most frequently accessed keys on a Valkey server ---- - -A small number of keys often receives a disproportionate share of the traffic. On -a cluster those keys limit how evenly load can be spread, since a single hot key -cannot be split across shards; on a single server they are the keys worth caching -client-side, sharding across several keys, or rate-limiting. Hot key tracking -finds them, on the server, from the traffic the server actually serves. - -## How it works - -Counting every access to every key exactly would cost memory proportional to the -keyspace and add work to every lookup. Tracking approximates instead: it records -a random `hotkeys-sampling-percentage` of accesses, and tracks at most -`hotkeys-top-k` keys at a time. The result is an approximate set of candidates: -neither exact top-K membership nor the relative order of the entries is -guaranteed, and a key quieter than the top-K may not appear at all. - -Counts accumulate in a *live* window. When `hotkeys-window-seconds` has elapsed -the live window is *frozen* and a fresh one starts. -[`HOTKEYS GET`](../commands/hotkeys-get.md) always reports the frozen window — -the last one to complete — and never the partial window still accumulating. A -report therefore describes a recent, completed interval rather than an average -since the server started, and the figures in one reply are all measured over the -same interval. - -If the server stalls long enough that the live window has spanned at least twice -`hotkeys-window-seconds` by the time it rotates, its counts no longer describe a -single window. Both the live and the frozen state are then discarded, and -`HOTKEYS GET` returns an empty result until the next valid window completes. - -Keys are tracked over the whole keyspace, not per logical database. There is one -top-K list, and every key competes for a place in it whichever database it -belongs to; each entry records the database it was accessed in so the keys can be -told apart. - -State is per node. Each server tracks only the accesses it serves, so on a -cluster query each node and read each reply on its own; there is no aggregated, -cluster-wide view. - -## Configuration - -Tracking is disabled by default. Enable it by setting `hotkeys-top-k` to a -positive value. - -| Parameter | Default | Range | Meaning | -| --- | --- | --- | --- | -| `hotkeys-top-k` | `0` (disabled) | 0-1000 | Number of keys tracked: `0` disables tracking entirely, any positive value enables it | -| `hotkeys-sampling-percentage` | `1` | 1-100 | Percentage of client key accesses that are sampled; `100` samples every access | -| `hotkeys-window-seconds` | `1` | 1-300 | Length of the reporting window | - -All three can be changed at runtime with -[`CONFIG SET`](../commands/config-set.md). A change takes at least one full -window to take effect, since a report always describes a window that has already -completed. - -## Choosing the sampling percentage and window - -Both `hotkeys-sampling-percentage` and `hotkeys-window-seconds` can improve -accuracy by increasing the number of samples a key contributes to each -measurement window. Each comes with a different trade-off: a higher sampling -percentage increases per-access overhead, while a longer window provides more -samples but makes the report slower to reflect changes in access patterns, since -samples from earlier in the window are still included. The defaults (1% sampling -and a 1-second window) keep overhead low while allowing the report to react -quickly to changing traffic. Increase either setting when the hot key rates you -care about are too low to resolve reliably. - -## What counts as an access - -Accesses are sampled at individual key lookups and at successful key removals, -not once per command and key pair. So a command that touches several keys -contributes one access for each of them, and a command that both reads and -removes the same key contributes two: `MGET a b c` records one access against -each of `a`, `b` and `c`, while `GETDEL` on an existing key records two against -that one key. - -A lookup counts whether or not the key exists, which helps reveal load caused by -missing keys or repeated requests for keys that have been evicted. A removal only -counts when it removes something, so [`DEL`](../commands/del.md) and -[`UNLINK`](../commands/unlink.md) on an existing key count as accesses while the -same commands on a missing key record nothing. Client-driven traffic during data -imports is counted as well. - -Internal activity is not counted. This includes the write stream a replica -applies from its primary and the commands a server loads from an RDB or AOF file, -introspection lookups such as those made by [`OBJECT`](../commands/object.md), -administrative bulk slot deletion, and background maintenance such as active -defragmentation. Key expiration and eviction are also not counted, because the -removal itself is internal activity — but a client lookup that triggers a lazy -expiration is still counted, since the lookup was initiated by the client. - -## State and resets - -Hot key tracking keeps statistics for both the current (live) window and the last -completed window. You can clear this state explicitly with -[`HOTKEYS RESET`](../commands/hotkeys-reset.md), or it is cleared automatically -when an operation discards an entire database or slot range. - -The following operations clear hot key state: - -* [`FLUSHDB`](../commands/flushdb.md) and [`FLUSHALL`](../commands/flushall.md) -* A full sync or RDB reload that empties the dataset -* A cluster reset -* Dropping a slot - -Normal key activity does not clear hot key state: `DEL` and `UNLINK` are treated -as accesses, and neither expiration nor eviction clears the tracking state. - -### Renaming and moving keys - -Hot key statistics are associated with a key's name and database, rather than -with the underlying key itself. As a result, renaming or moving a key does not -transfer its statistics to its new name or database. - -After [`RENAME`](../commands/rename.md), [`MOVE`](../commands/move.md), or -[`SWAPDB`](../commands/swapdb.md), the existing statistics remain associated with -the key's previous identity, and clients still accessing that old name or -database keep adding to them — a lookup of a key that is no longer there is -counted like any other. Once no further accesses are recorded against it, the -entry ages out of the tracking windows: it leaves the live window at the next -window rotation, and the last-completed (frozen) window one rotation later. So a -report can continue to show the old key name or database for up to roughly twice -`hotkeys-window-seconds` after the last access to it. - -## Commands - -* [`HOTKEYS GET`](../commands/hotkeys-get.md): the hottest keys of the last - completed window. -* [`HOTKEYS RESET`](../commands/hotkeys-reset.md): clear all collected - statistics. -* [`HOTKEYS HELP`](../commands/hotkeys-help.md): help text for the subcommands. diff --git a/topics/hyperloglogs.md b/topics/hyperloglogs.md deleted file mode 100644 index 8a719262..00000000 --- a/topics/hyperloglogs.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -title: "HyperLogLog" -description: > - HyperLogLog is a probabilistic data structure that estimates the cardinality of a set. ---- - -HyperLogLog is a probabilistic data structure that estimates the cardinality of a set. As a probabilistic data structure, HyperLogLog trades perfect accuracy for efficient space utilization. - -The HyperLogLog implementation uses up to 12 KB and provides a standard error of 0.81%. - -Counting unique items usually requires an amount of memory -proportional to the number of items you want to count, because you need -to remember the elements you have already seen in the past in order to avoid -counting them multiple times. However, a set of algorithms exist that trade -memory for precision: they return an estimated measure with a standard error, -which, in the case of the Valkey implementation for HyperLogLog, is less than 1%. -The magic of this algorithm is that you no longer need to use an amount of memory -proportional to the number of items counted, and instead can use a -constant amount of memory; 12k bytes in the worst case, or a lot less if your -HyperLogLog (We'll just call them HLL from now) has seen very few elements. - -HLLs in Valkey, while technically a different data structure, are encoded -as a String, so you can call `GET` to serialize a HLL, and `SET` -to deserialize it back to the server. - -Conceptually the HLL API is like using Sets to do the same task. You would -`SADD` every observed element into a set, and would use `SCARD` to check the -number of elements inside the set, which are unique since `SADD` will not -re-add an existing element. - -While you don't really *add items* into an HLL, because the data structure -only contains a state that does not include actual elements, the API is the -same: - -* Every time you see a new element, you add it to the count with `PFADD`. -* When you want to retrieve the current approximation of unique elements added using the `PFADD` command, you can use the `PFCOUNT` command. If you need to merge two different HLLs, the `PFMERGE` command is available. Since HLLs provide approximate counts of unique elements, the result of the merge will give you an approximation of the number of unique elements across both source HLLs. - -``` -127.0.0.1:6379> PFADD bikes Hyperion Deimos Phoebe Quaoar -(integer) 1 -127.0.0.1:6379> PFCOUNT bikes -(integer) 4 -127.0.0.1:6379> PFADD commuter_bikes Salacia Mimas Quaoar -(integer) 1 -127.0.0.1:6379> PFMERGE all_bikes bikes commuter_bikes -OK -127.0.0.1:6379> PFCOUNT all_bikes -(integer) 6 -``` - -Some examples of use cases for this data structure is counting unique queries -performed by users in a search form every day, number of unique visitors to a web page and other similar cases. - -Valkey is also able to perform the union of HLLs, please check the -[full documentation](../commands/#hyperloglog) for more information. - -## Use cases - -**Anonymous unique visits of a web page (SaaS, analytics tools)** - -This application answers these questions: - -- How many unique visits has this page had on this day? -- How many unique users have played this song? -- How many unique users have viewed this video? - -**Note:** -Storing the IP address or any other kind of personal identifier is against the law in some countries, which makes it impossible to get unique visitor statistics on your website. - -One HyperLogLog is created per page (video/song) per period, and every IP/identifier is added to it on every visit. - -## Basic commands - -* `PFADD` adds an item to a HyperLogLog. -* `PFCOUNT` returns an estimate of the number of items in the set. -* `PFMERGE` combines two or more HyperLogLogs into one. - -See the [complete list of HyperLogLog commands](../commands/#hyperloglog). - -## Performance - -Writing (`PFADD`) to and reading from (`PFCOUNT`) the HyperLogLog is done in constant time and space. -Merging HLLs is O(n), where _n_ is the number of sketches. - -## Limits - -The HyperLogLog can estimate the cardinality of sets with up to 18,446,744,073,709,551,616 (2^64) members. - -## Learn more - -* This blog post on [the HyperLogLog data structure](https://web.archive.org/web/20241019222035/http://antirez.com/news/75) has a lot of details about the data structure and its implementation in Valkey. diff --git a/topics/index.md b/topics/index.md deleted file mode 100644 index 6c0e4b20..00000000 --- a/topics/index.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: "Valkey Documentation" ---- - -The Valkey documentation is managed in markdown files in the -[valkey-doc repository](https://github.com/valkey-io/valkey-doc). -It's released under the -[Creative Commons Attribution-ShareAlike 4.0 International license](https://creativecommons.org/licenses/by-sa/4.0/). - -# Valkey Documentation -## 1. Introduction - -* What is Valkey? See [Introduction](introduction.md). -* [Quick start](quickstart.md): Get started with Valkey. -* [Valkey Bundle](valkey-bundle.md): Get started with Valkey Bundle. -* [FAQ](faq.md): Frequently asked questions. - -## 2. Developer Guide -### Core Concepts -* [Data types](data-types.md): Keys are strings, but values can be of many different data types. -* [The full list of commands](../commands/), with documentation for each of them. -* [Pipelining](pipelining.md): How to send multiple commands at once, saving on round trip time. -* [Transactions](transactions.md): Valkey's approach to atomic transactions. -* [Expires](../commands/expire.md): How to set a Time To Live (TTL) on key so that it will be automatically removed from the server when it expires. -* [Pub/Sub](pubsub.md): Using Valkey as a message broker using the Publish/Subscribe messaging system. -* [Keyspace notifications](notifications.md): Get notifications of keyspace events via Pub/Sub. -* [Keyspace management](keyspace.md): How to alter, query, and navigate the keyspace. - -### Application Patterns & Tutorials - -* [Valkey as an LRU cache](lru-cache.md): How to configure Valkey as a cache with a fixed amount of memory and automatic eviction of keys. -* [Client side caching](client-side-caching.md): How a client can be notified by the server when a key has changed. -* [Distributed locks](distlock.md): Implementing a distributed lock manager. -* [Secondary indexes](indexing.md): How to simulate secondary indexes, composed indexes and traverse graphs using various data structures. -* [Writing a simple Twitter clone with PHP and Valkey](twitter-clone.md) - -## 3. Extending Valkey - -### Server-side scripting in Valkey -* [Programmability overview](programmability.md): An overview of programmability in Valkey. -* [Introduction to Eval Scripts](eval-intro.md): An introduction about using cached scripts. -* [Introduction to Valkey Functions](functions-intro.md): An introduction about using functions. -* [Valkey Lua API](lua-api.md): The embedded [Lua 5.1](https://lua.org) interpreter runtime environment and APIs. -* [Debugging Lua scripts](ldb.md): An overview of the native Valkey Lua debugger for cached scripts. - - -### Valkey modules API -* [Introduction to Valkey modules](modules-intro.md): Extend Valkey using dynamically linked modules. -* [Implementing native data types](modules-native-types.md): Modules scan implement new data types (data structures and more) that look like built-in data types. This documentation covers the API to do so. -* [Blocking operations](modules-blocking-ops.md): Write commands that can block the client (without blocking Valkey) and can execute tasks in other threads. -* [Modules API reference](modules-api-ref.md): Documentation of all module API functions. Low level details about API usage. - -## 4. Administration - -### Core Management -* [Installation](installation.md): How to install and configure Valkey. This targets people without prior experience with Valkey. -* [Release Downloads](https://valkey.io/download/releases/): Lists links to download all current and previous releases. -* [valkey-cli](cli.md): The Valkey command line interface, used for administration, troubleshooting and experimenting with Valkey. -* [Valkey Admin](https://valkey-admin.valkey.io/): An intuitive visual interface to monitor, manage, and interact with your Valkey deployments. -* [valkey-server](server.md): How to run the Valkey server. -* [Configuration](valkey.conf.md): How to configure Valkey. -* [Persistence](persistence.md): Options for configuring durability using disk backups. -* [Signals Handling](signals.md): How Valkey handles signals. -* [Connections Handling](clients.md): How Valkey handles clients connections. -* [Migration](migration.md): How to migrate from Redis to Valkey and check Redis compatibility. -* [Releases and Versioning](releases.md): Valkey's development cycle and version numbering. -* [Administration](admin.md): Various administration topics. - -### Deployment Topology -* [Replication](replication.md): What you need to know to set up primary-replica replication. -* [Sentinel](sentinel.md): Valkey Sentinel is one of the official high availability deployment modes. -* [Sentinel client spec](sentinel-clients.md): How to build clients for Valkey Sentinel. -* [Cluster tutorial](cluster-tutorial.md): A gentle introduction to Valkey Cluster, a deployment mode for horizontal scaling and high availability. -* [Cluster specification](cluster-spec.md): The more formal description of the behavior and algorithms used in Valkey Cluster. -* [Atomic slot migration](atomic-slot-migration.md): An overview of atomic slot migration in Valkey Cluster. -* [Forkless operations](forkless.md): Saving and fully syncing replicas without `fork()`. - -### Security -* [Security](security.md): An overview of Valkey's security. -* [Access Control Lists](acl.md): ACLs make it possible to allow users to run only selected commands and access only specific key patterns. -* [TLS](tls.md): How to use TLS for communication. - -### Platform Specific -* [ARM and Raspberry Pi](ARM.md): ARM and the Raspberry Pi are supported platforms. This page contains general information and benchmarks. -* [RDMA](RDMA.md): An overview of RDMA support. - - -## 5. Performance & Troubleshooting -* [Troubleshooting](problems.md): Problems? Bugs? High latency? Other issues? Use our problems troubleshooting page as a starting point to find more information. -* [Memory optimization](memory-optimization.md): Understand how Valkey uses RAM. -* [Hot key tracking](hotkeys.md): Find the most frequently accessed keys on a server. -* [Latency monitoring](latency-monitor.md): Integrated latency monitoring and reporting help tuning for low latency. -* [valkey-benchmark](benchmark.md): The benchmarking tool shipped with Valkey. -* [On-CPU profiling and tracing](performance-on-cpu.md): How to find on-CPU resource bottlenecks. -* [Debugging](debugging.md): How to debug Valkey server processes. -* [Diagnosing latency issues](latency.md): How to diagnose latency problems with Valkey. -* [Mass insertion of data](mass-insertion.md): How to add a big amount of data to a Valkey instance in a short time. - - -## 6. Low-Level Internals -* [Protocol specification](protocol.md): The client-server protocol, for client authors. -* [Command key specifications](key-specs.md): How to extract the names of keys accessed by every command. -* [Command tips](command-tips.md): Command tips communicate non-trivial execution modes and post-processing information about commands. -* [Command arguments](command-arguments.md): An overview of command arguments as returned by the `COMMAND DOCS` command. diff --git a/topics/indexing.md b/topics/indexing.md deleted file mode 100644 index 86839462..00000000 --- a/topics/indexing.md +++ /dev/null @@ -1,744 +0,0 @@ ---- -title: Secondary indexing -description: > - Building secondary indexes in Valkey ---- - -Valkey is not exactly a key-value store, since values can be complex data structures. However it has an external key-value shell: at API level data is addressed by the key name. It is fair to say that, natively, Valkey only offers *primary key access*. However since Valkey is a data structures server, its capabilities can be used for indexing, in order to create secondary indexes of different kinds, including composite (multi-column) indexes. - -This document explains how it is possible to create indexes in Valkey using the following data structures: - -* Sorted sets to create secondary indexes by ID or other numerical fields. -* Sorted sets with lexicographical ranges for creating more advanced secondary indexes, composite indexes and graph traversal indexes. -* Sets for creating random indexes. -* Lists for creating simple iterable indexes and last N items indexes. - -Implementing and maintaining indexes with Valkey is an advanced topic, so most -users that need to perform complex queries on data should understand if they -are better served by a relational store. However often, especially in caching -scenarios, there is the explicit need to store indexed data into Valkey in order to speedup common queries which require some form of indexing in order to be executed. - -Simple numerical indexes with sorted sets -=== - -The simplest secondary index you can create with Valkey is by using the -sorted set data type, which is a data structure representing a set of -elements ordered by a floating point number which is the *score* of -each element. Elements are ordered from the smallest to the highest score. - -Since the score is a double precision float, indexes you can build with -vanilla sorted sets are limited to things where the indexing field is a number -within a given range. - -The two commands to build these kind of indexes are `ZADD` and -`ZRANGE` with the `BYSCORE` argument to respectively add items and retrieve items within a -specified range. - -For instance, it is possible to index a set of person names by their -age by adding element to a sorted set. The element will be the name of the -person and the score will be the age. - - ZADD myindex 25 Manuel - ZADD myindex 18 Anna - ZADD myindex 35 Jon - ZADD myindex 67 Helen - -In order to retrieve all persons with an age between 20 and 40, the following -command can be used: - - ZRANGE myindex 20 40 BYSCORE - 1) "Manuel" - 2) "Jon" - -By using the **WITHSCORES** option of `ZRANGE` it is also possible -to obtain the scores associated with the returned elements. - -The `ZCOUNT` command can be used in order to retrieve the number of elements -within a given range, without actually fetching the elements, which is also -useful, especially given the fact the operation is executed in logarithmic -time regardless of the size of the range. - -Ranges can be inclusive or exclusive, please refer to the `ZRANGE` -command documentation for more information. - -**Note**: Using the `ZRANGE` with the `BYSCORE` and `REV` arguments, it is possible to query a range in -reversed order, which is often useful when data is indexed in a given -direction (ascending or descending) but we want to retrieve information -the other way around. - -Using objects IDs as associated values ---- - -In the above example we associated names to ages. However in general we -may want to index some field of an object which is stored elsewhere. -Instead of using the sorted set value directly to store the data associated -with the indexed field, it is possible to store just the ID of the object. - -For example I may have Hashes representing users. Each user is -represented by a single key, directly accessible by ID: - - HSET user:1 id 1 username antirez ctime 1444809424 age 38 - HSET user:2 id 2 username maria ctime 1444808132 age 42 - HSET user:3 id 3 username jballard ctime 1443246218 age 33 - -If I want to create an index in order to query users by their age, I -could do: - - ZADD user.age.index 38 1 - ZADD user.age.index 42 2 - ZADD user.age.index 33 3 - -This time the value associated with the score in the sorted set is the -ID of the object. So once I query the index with `ZRANGE` with the `BYSCORE` argument, I'll -also have to retrieve the information I need with `HGETALL` or similar -commands. The obvious advantage is that objects can change without touching -the index, as long as we don't change the indexed field. - -In the next examples we'll almost always use IDs as values associated with -the index, since this is usually the more sounding design, with a few -exceptions. - -Updating simple sorted set indexes ---- - -Often we index things which change over time. In the above -example, the age of the user changes every year. In such a case it would -make sense to use the birth date as index instead of the age itself, -but there are other cases where we simply want some field to change from -time to time, and the index to reflect this change. - -The `ZADD` command makes updating simple indexes a very trivial operation -since re-adding back an element with a different score and the same value -will simply update the score and move the element at the right position, -so if the user `antirez` turned 39 years old, in order to update the -data in the hash representing the user, and in the index as well, we need -to execute the following two commands: - - HSET user:1 age 39 - ZADD user.age.index 39 1 - -The operation may be wrapped in a `MULTI`/`EXEC` transaction in order to -make sure both fields are updated or none. - -Turning multi dimensional data into linear data ---- - -Indexes created with sorted sets are able to index only a single numerical -value. Because of this you may think it is impossible to index something -which has multiple dimensions using this kind of indexes, but actually this -is not always true. If you can efficiently represent something -multi-dimensional in a linear way, they it is often possible to use a simple -sorted set for indexing. - -For example the [Valkey geo indexing API](../commands/geoadd.md) uses a sorted -set to index places by latitude and longitude using a technique called -[Geo hash](https://en.wikipedia.org/wiki/Geohash). The sorted set score -represents alternating bits of longitude and latitude, so that we map the -linear score of a sorted set to many small *squares* in the earth surface. -By doing an 8+1 style center plus neighborhoods search it is possible to -retrieve elements by radius. - -Limits of the score ---- - -Sorted set elements scores are double precision floats. It means that -they can represent different decimal or integer values with different -errors, because they use an exponential representation internally. -However what is interesting for indexing purposes is that the score is -always able to represent without any error numbers between -9007199254740992 -and 9007199254740992, which is `-/+ 2^53`. - -When representing much larger numbers, you need a different form of indexing -that is able to index numbers at any precision, called a lexicographical -index. - -Lexicographical indexes -=== - -Sorted Sets have an interesting property. When elements are added -with the same score, they are sorted lexicographically, comparing the -strings as binary data with the `memcmp()` function. - -For people that don't know the C language nor the `memcmp` function, what -it means is that elements with the same score are sorted comparing the -raw values of their bytes, byte after byte. If the first byte is the same, -the second is checked and so forth. If the common prefix of two strings is -the same then the longer string is considered the greater of the two, -so "foobar" is greater than "foo". - -There are commands such as `ZRANGE` and `ZLEXCOUNT` that -are able to query and count ranges in a lexicographically fashion, assuming -they are used with sorted sets where all the elements have the same score. - -This Valkey feature is basically equivalent to a `b-tree` data structure which -is often used in order to implement indexes with traditional databases. -As you can guess, because of this, it is possible to use this Valkey data -structure in order to implement pretty fancy indexes. - -Before we dive into using lexicographical indexes, let's check how -sorted sets behave in this special mode of operation. Since we need to -add elements with the same score, we'll always use the special score of -zero. - - ZADD myindex 0 baaa - ZADD myindex 0 abbb - ZADD myindex 0 aaaa - ZADD myindex 0 bbbb - -Fetching all the elements from the sorted set immediately reveals that they -are ordered lexicographically. - - ZRANGE myindex 0 -1 - 1) "aaaa" - 2) "abbb" - 3) "baaa" - 4) "bbbb" - -Now we can use `ZRANGE` with the `BYLEX` argument in order to perform range queries. - - ZRANGE myindex [a (b BYLEX - 1) "aaaa" - 2) "abbb" - -Note that in the range queries we prefixed the `min` and `max` elements -identifying the range with the special characters `[` and `(`. -This prefixes are mandatory, and they specify if the elements -of the range are inclusive or exclusive. So the range `[a (b` means give me -all the elements lexicographically between `a` inclusive and `b` exclusive, -which are all the elements starting with `a`. - -There are also two more special characters indicating the infinitely negative -string and the infinitely positive string, which are `-` and `+`. - - ZRANGE myindex [b + BYLEX - 1) "baaa" - 2) "bbbb" - -That's it basically. Let's see how to use these features to build indexes. - -A first example: completion ---- - -An interesting application of indexing is completion. Completion is what -happens when you start typing your query into a search engine: the user -interface will anticipate what you are likely typing, providing common -queries that start with the same characters. - -A naive approach to completion is to just add every single query we -get from the user into the index. For example if the user searches `banana` -we'll just do: - - ZADD myindex 0 banana - -And so forth for each search query ever encountered. Then when we want to -complete the user input, we execute a range query using `ZRANGE` with the `BYLEX` argument. -Imagine the user is typing "bit" inside the search form, and we want to -offer possible search keywords starting for "bit". We send Valkey a command -like that: - - ZRANGE myindex "[bit" "[bit\xff" BYLEX - -Basically we create a range using the string the user is typing right now -as start, and the same string plus a trailing byte set to 255, which is `\xff` in the example, as the end of the range. This way we get all the strings that start for the string the user is typing. - -Note that we don't want too many items returned, so we may use the **LIMIT** option in order to reduce the number of results. - -Adding frequency into the mix ---- - -The above approach is a bit naive, because all the user searches are the same -in this way. In a real system we want to complete strings according to their -frequency: very popular searches will be proposed with a higher probability -compared to search strings typed very rarely. - -In order to implement something which depends on the frequency, and at the -same time automatically adapts to future inputs, by purging searches that -are no longer popular, we can use a very simple *streaming algorithm*. - -To start, we modify our index in order to store not just the search term, -but also the frequency the term is associated with. So instead of just adding -`banana` we add `banana:1`, where 1 is the frequency. - - ZADD myindex 0 banana:1 - -We also need logic in order to increment the index if the search term -already exists in the index, so what we'll actually do is something like -that: - - ZRANGE myindex "[banana:" + BYLEX LIMIT 0 1 - 1) "banana:1" - -This will return the single entry of `banana` if it exists. Then we -can increment the associated frequency and send the following two -commands: - - ZREM myindex 0 banana:1 - ZADD myindex 0 banana:2 - -Note that because it is possible that there are concurrent updates, the -above three commands should be send via a [Lua script](../commands/eval.md) -instead, so that the Lua script will atomically get the old count and -re-add the item with incremented score. - -So the result will be that, every time a user searches for `banana` we'll -get our entry updated. - -There is more: our goal is to just have items searched very frequently. -So we need some form of purging. When we actually query the index -in order to complete the user input, we may see something like that: - - ZRANGE myindex "[banana:" + BYLEX LIMIT 0 10 - 1) "banana:123" - 2) "banaooo:1" - 3) "banned user:49" - 4) "banning:89" - -Apparently nobody searches for "banaooo", for example, but the query was -performed a single time, so we end presenting it to the user. - -This is what we can do. Out of the returned items, we pick a random one, -decrement its score by one, and re-add it with the new score. -However if the score reaches 0, we simply remove the item from the list. -You can use much more advanced systems, but the idea is that the index in -the long run will contain top searches, and if top searches will change over -the time it will adapt automatically. - -A refinement to this algorithm is to pick entries in the list according to -their weight: the higher the score, the less likely entries are picked -in order to decrement its score, or evict them. - -Normalizing strings for case and accents ---- - -In the completion examples we always used lowercase strings. However -reality is much more complex than that: languages have capitalized names, -accents, and so forth. - -One simple way do deal with this issues is to actually normalize the -string the user searches. Whatever the user searches for "Banana", -"BANANA" or "Ba'nana" we may always turn it into "banana". - -However sometimes we may like to present the user with the original -item typed, even if we normalize the string for indexing. In order to -do this, what we do is to change the format of the index so that instead -of just storing `term:frequency` we store `normalized:frequency:original` -like in the following example: - - ZADD myindex 0 banana:273:Banana - -Basically we add another field that we'll extract and use only for -visualization. Ranges will always be computed using the normalized strings -instead. This is a common trick which has multiple applications. - -Adding auxiliary information in the index ---- - -When using a sorted set in a direct way, we have two different attributes -for each object: the score, which we use as an index, and an associated -value. When using lexicographical indexes instead, the score is always -set to 0 and basically not used at all. We are left with a single string, -which is the element itself. - -Like we did in the previous completion examples, we are still able to -store associated data using separators. For example we used the colon in -order to add the frequency and the original word for completion. - -In general we can add any kind of associated value to our indexing key. -In order to use a lexicographical index to implement a simple key-value store -we just store the entry as `key:value`: - - ZADD myindex 0 mykey:myvalue - -And search for the key with: - - ZRANGE myindex [mykey: + BYLEX LIMIT 0 1 - 1) "mykey:myvalue" - -Then we extract the part after the colon to retrieve the value. -However a problem to solve in this case is collisions. The colon character -may be part of the key itself, so it must be chosen in order to never -collide with the key we add. - -Since lexicographical ranges in Valkey are binary safe you can use any -byte or any sequence of bytes. However if you receive untrusted user -input, it is better to use some form of escaping in order to guarantee -that the separator will never happen to be part of the key. - -For example if you use two null bytes as separator `"\0\0"`, you may -want to always escape null bytes into two bytes sequences in your strings. - -Numerical padding ---- - -Lexicographical indexes may look like good only when the problem at hand -is to index strings. Actually it is very simple to use this kind of index -in order to perform indexing of arbitrary precision numbers. - -In the ASCII character set, digits appear in the order from 0 to 9, so -if we left-pad numbers with leading zeroes, the result is that comparing -them as strings will order them by their numerical value. - - ZADD myindex 0 00324823481:foo - ZADD myindex 0 12838349234:bar - ZADD myindex 0 00000000111:zap - - ZRANGE myindex 0 -1 - 1) "00000000111:zap" - 2) "00324823481:foo" - 3) "12838349234:bar" - -We effectively created an index using a numerical field which can be as -big as we want. This also works with floating point numbers of any precision -by making sure we left pad the numerical part with leading zeroes and the -decimal part with trailing zeroes like in the following list of numbers: - - 01000000000000.11000000000000 - 01000000000000.02200000000000 - 00000002121241.34893482930000 - 00999999999999.00000000000000 - -Using numbers in binary form ---- - -Storing numbers in decimal may use too much memory. An alternative approach -is just to store numbers, for example 128 bit integers, directly in their -binary form. However for this to work, you need to store the numbers in -*big endian format*, so that the most significant bytes are stored before -the least significant bytes. This way when Valkey compares the strings with -`memcmp()`, it will effectively sort the numbers by their value. - -Keep in mind that data stored in binary format is less observable for -debugging, harder to parse and export. So it is definitely a trade off. - -Composite indexes -=== - -So far we explored ways to index single fields. However we all know that -SQL stores are able to create indexes using multiple fields. For example -I may index products in a very large store by room number and price. - -I need to run queries in order to retrieve all the products in a given -room having a given price range. What I can do is to index each product -in the following way: - - ZADD myindex 0 0056:0028.44:90 - ZADD myindex 0 0034:0011.00:832 - -Here the fields are `room:price:product_id`. I used just four digits padding -in the example for simplicity. The auxiliary data (the product ID) does not -need any padding. - -With an index like that, to get all the products in room 56 having a price -between 10 and 30 dollars is very easy. We can just run the following -command: - - ZRANGE myindex [0056:0010.00 [0056:0030.00 BYLEX - -The above is called a composed index. Its effectiveness depends on the -order of the fields and the queries I want to run. For example the above -index cannot be used efficiently in order to get all the products having -a specific price range regardless of the room number. However I can use -the primary key in order to run queries regardless of the price, like -*give me all the products in room 44*. - -Composite indexes are very powerful, and are used in traditional stores -in order to optimize complex queries. In Valkey they could be useful both -to implement a very fast in-memory Valkey index of something stored into -a traditional data store, or in order to directly index Valkey data. - -Updating lexicographical indexes -=== - -The value of the index in a lexicographical index can get pretty fancy -and hard or slow to rebuild from what we store about the object. So one -approach to simplify the handling of the index, at the cost of using more -memory, is to also take alongside to the sorted set representing the index -a hash mapping the object ID to the current index value. - -So for example, when we index we also add to a hash: - - MULTI - ZADD myindex 0 0056:0028.44:90 - HSET index.content 90 0056:0028.44:90 - EXEC - -This is not always needed, but simplifies the operations of updating -the index. In order to remove the old information we indexed for the object -ID 90, regardless of the *current* fields values of the object, we just -have to retrieve the hash value by object ID and `ZREM` it in the sorted -set view. - -Representing and querying graphs using a hexastore -=== - -One cool thing about composite indexes is that they are handy in order -to represent graphs, using a data structure which is called -[Hexastore](https://www.vldb.org/pvldb/vol1/1453965.pdf). - -The hexastore provides a representation for relations between objects, -formed by a *subject*, a *predicate* and an *object*. -A simple relation between objects could be: - - antirez is-friend-of matteocollina - -In order to represent this relation I can store the following element -in my lexicographical index: - - ZADD myindex 0 spo:antirez:is-friend-of:matteocollina - -Note that I prefixed my item with the string **spo**. It means that -the item represents a subject,predicate,object relation. - -In can add 5 more entries for the same relation, but in a different order: - - ZADD myindex 0 sop:antirez:matteocollina:is-friend-of - ZADD myindex 0 ops:matteocollina:is-friend-of:antirez - ZADD myindex 0 osp:matteocollina:antirez:is-friend-of - ZADD myindex 0 pso:is-friend-of:antirez:matteocollina - ZADD myindex 0 pos:is-friend-of:matteocollina:antirez - -Now things start to be interesting, and I can query the graph in many -different ways. For example, who are all the people `antirez` -*is friend of*? - - ZRANGE myindex "[spo:antirez:is-friend-of:" "[spo:antirez:is-friend-of:\xff" BYLEX - 1) "spo:antirez:is-friend-of:matteocollina" - 2) "spo:antirez:is-friend-of:wonderwoman" - 3) "spo:antirez:is-friend-of:spiderman" - -Or, what are all the relationships `antirez` and `matteocollina` have where -the first is the subject and the second is the object? - - ZRANGE myindex "[sop:antirez:matteocollina:" "[sop:antirez:matteocollina:\xff" BYLEX - 1) "sop:antirez:matteocollina:is-friend-of" - 2) "sop:antirez:matteocollina:was-at-conference-with" - 3) "sop:antirez:matteocollina:talked-with" - -By combining different queries, I can ask fancy questions. For example: -*Who are all my friends that, like beer, live in Barcelona, and matteocollina consider friends as well?* -To get this information I start with an `spo` query to find all the people -I'm friend with. Then for each result I get I perform an `spo` query -to check if they like beer, removing the ones for which I can't find -this relation. I do it again to filter by city. Finally I perform an `ops` -query to find, of the list I obtained, who is considered friend by -matteocollina. - -Make sure to check [Matteo Collina's slides about Levelgraph](https://nodejsconfit.levelgraph.io/) in order to better understand these ideas. - -Multi dimensional indexes -=== - -A more complex type of index is an index that allows you to perform queries -where two or more variables are queried at the same time for specific -ranges. For example I may have a data set representing persons age and -salary, and I want to retrieve all the people between 50 and 55 years old -having a salary between 70000 and 85000. - -This query may be performed with a multi column index, but this requires -us to select the first variable and then scan the second, which means we -may do a lot more work than needed. It is possible to perform these kinds of -queries involving multiple variables using different data structures. -For example, multi-dimensional trees such as *k-d trees* or *r-trees* are -sometimes used. Here we'll describe a different way to index data into -multiple dimensions, using a representation trick that allows us to perform -the query in a very efficient way using Valkey lexicographical ranges. - -Let's say we have points in the space, which represent our data samples, where `x` and `y` are our coordinates. The max value of both variables is 400. - -In the next figure, the blue box represents our query. We want all the points where `x` is between 50 and 100, and where `y` is between 100 and 300. - -![Points in the space](2idx_0.png) - -In order to represent data that makes these kinds of queries fast to perform, -we start by padding our numbers with 0. So for example imagine we want to -add the point 10,25 (x,y) to our index. Given that the maximum range in the -example is 400 we can just pad to three digits, so we obtain: - - x = 010 - y = 025 - -Now what we do is to interleave the digits, taking the leftmost digit -in x, and the leftmost digit in y, and so forth, in order to create a single -number: - - 001205 - -This is our index, however in order to more easily reconstruct the original -representation, if we want (at the cost of space), we may also add the -original values as additional columns: - - 001205:10:25 - -Now, let's reason about this representation and why it is useful in the -context of range queries. For example let's take the center of our blue -box, which is at `x=75` and `y=200`. We can encode this number as we did -earlier by interleaving the digits, obtaining: - - 027050 - -What happens if we substitute the last two digits respectively with 00 and 99? -We obtain a range which is lexicographically continuous: - - 027000 to 027099 - -What this maps to is to a square representing all values where the `x` -variable is between 70 and 79, and the `y` variable is between 200 and 209. -To identify this specific area, we can write random points in that interval. - -![Small area](2idx_1.png) - -So the above lexicographic query allows us to easily query for points in -a specific square in the picture. However the square may be too small for -the box we are searching, so that too many queries are needed. -So we can do the same but instead of replacing the last two digits with 00 -and 99, we can do it for the last four digits, obtaining the following -range: - - 020000 029999 - -This time the range represents all the points where `x` is between 0 and 99 -and `y` is between 200 and 299. Drawing random points in this interval -shows us this larger area. - -![Large area](2idx_2.png) - -So now our area is too big for our query, and still our search box is -not completely included. We need more granularity, but we can easily obtain -it by representing our numbers in binary form. This time, when we replace -digits instead of getting squares which are ten times bigger, we get squares -which are just two times bigger. - -Our numbers in binary form, assuming we need just 9 bits for each variable -(in order to represent numbers up to 400 in value) would be: - - x = 75 -> 001001011 - y = 200 -> 011001000 - -So by interleaving digits, our representation in the index would be: - - 000111000011001010:75:200 - -Let's see what are our ranges as we substitute the last 2, 4, 6, 8, ... -bits with 0s ad 1s in the interleaved representation: - - 2 bits: x between 74 and 75, y between 200 and 201 (range=2) - 4 bits: x between 72 and 75, y between 200 and 203 (range=4) - 6 bits: x between 72 and 79, y between 200 and 207 (range=8) - 8 bits: x between 64 and 79, y between 192 and 207 (range=16) - -And so forth. Now we have definitely better granularity! -As you can see substituting N bits from the index gives us -search boxes of side `2^(N/2)`. - -So what we do is check the dimension where our search box is smaller, -and check the nearest power of two to this number. Our search box -was 50,100 to 100,300, so it has a width of 50 and a height of 200. -We take the smaller of the two, 50, and check the nearest power of two -which is 64. 64 is 2^6, so we would work with indexes obtained replacing -the latest 12 bits from the interleaved representation (so that we end -replacing just 6 bits of each variable). - -However single squares may not cover all our search, so we may need more. -What we do is to start with the left bottom corner of our search box, -which is 50,100, and find the first range by substituting the last 6 bits -in each number with 0. Then we do the same with the right top corner. - -With two trivial nested for loops where we increment only the significant -bits, we can find all the squares between these two. For each square we -convert the two numbers into our interleaved representation, and create -the range using the converted representation as our start, and the same -representation but with the latest 12 bits turned on as end range. - -For each square found we perform our query and get the elements inside, -removing the elements which are outside our search box. - -Turning this into code is simple. Here is a Ruby example: - -```ruby -def spacequery(x0,y0,x1,y1,exp) - bits=exp*2 - x_start = x0/(2**exp) - x_end = x1/(2**exp) - y_start = y0/(2**exp) - y_end = y1/(2**exp) - (x_start..x_end).each{|x| - (y_start..y_end).each{|y| - x_range_start = x*(2**exp) - x_range_end = x_range_start | ((2**exp)-1) - y_range_start = y*(2**exp) - y_range_end = y_range_start | ((2**exp)-1) - puts "#{x},#{y} x from #{x_range_start} to #{x_range_end}, y from #{y_range_start} to #{y_range_end}" - - # Turn it into interleaved form for ZRANGE query. - # We assume we need 9 bits for each integer, so the final - # interleaved representation will be 18 bits. - xbin = x_range_start.to_s(2).rjust(9,'0') - ybin = y_range_start.to_s(2).rjust(9,'0') - s = xbin.split("").zip(ybin.split("")).flatten.compact.join("") - # Now that we have the start of the range, calculate the end - # by replacing the specified number of bits from 0 to 1. - e = s[0..-(bits+1)]+("1"*bits) - puts "ZRANGE myindex [#{s} [#{e} BYLEX" - } - } -end - -spacequery(50,100,100,300,6) -``` - -While non immediately trivial this is a very useful indexing strategy that -in the future may be implemented in Valkey in a native way. -For now, the good thing is that the complexity may be easily encapsulated -inside a library that can be used in order to perform indexing and queries. -One example of such library is [Redimension](https://github.com/antirez/redimension), a proof of concept Ruby library which indexes N-dimensional data inside Valkey using the technique described here. - -Multi dimensional indexes with negative or floating point numbers -=== - -The simplest way to represent negative values is just to work with unsigned -integers and represent them using an offset, so that when you index, before -translating numbers in the indexed representation, you add the absolute value -of your smaller negative integer. - -For floating point numbers, the simplest approach is probably to convert them -to integers by multiplying the integer for a power of ten proportional to the -number of digits after the dot you want to retain. - -Non range indexes -=== - -So far we checked indexes which are useful to query by range or by single -item. However other Valkey data structures such as Sets or Lists can be used -in order to build other kind of indexes. They are very commonly used but -maybe we don't always realize they are actually a form of indexing. - -For instance I can index object IDs into a Set data type in order to use -the *get random elements* operation via `SRANDMEMBER` in order to retrieve -a set of random objects. Sets can also be used to check for existence when -all I need is to test if a given item exists or not or has a single boolean -property or not. - -Similarly lists can be used in order to index items into a fixed order. -I can add all my items into a List and rotate the list with -`RPOPLPUSH` using the same key name as source and destination. This is useful -when I want to process a given set of items again and again forever in the -same order. Think of an RSS feed system that needs to refresh the local copy -periodically. - -Another popular index often used with Valkey is a **capped list**, where items -are added with `LPUSH` and trimmed with `LTRIM`, in order to create a view -with just the latest N items encountered, in the same order they were -seen. - -Index inconsistency -=== - -Keeping the index updated may be challenging, in the course of months -or years it is possible that inconsistencies are added because of software -bugs, network partitions or other events. - -Different strategies could be used. If the index data is outside Valkey -*read repair* can be a solution, where data is fixed in a lazy way when -it is requested. When we index data which is stored in Valkey itself -the `SCAN` family of commands can be used in order to verify, update or -rebuild the index from scratch, incrementally. diff --git a/topics/installation.md b/topics/installation.md deleted file mode 100644 index 7ec932e3..00000000 --- a/topics/installation.md +++ /dev/null @@ -1,264 +0,0 @@ ---- -title: "Installation" -description: > - Install Valkey on Linux, macOS, and Windows ---- - -This is a an installation guide. You'll learn how to install, run, and experiment with the Valkey server process. - -The download page [valkey.io/download](https://valkey.io/download) lists the latest releases. - -## Install Valkey - -These are some ways to install Valkey. -Refer to [Valkey Administration](admin.md) for detailed setup tips. - -### From source - -Source releases are available from the GitHub [Releases](https://github.com/valkey-io/valkey/releases) page. - -Unpack the tarball (e.g. `tar -xzvf valkey-8.0.1.tar.gz`) and follow the instructions in the included README.md. - -### Containers - -Containers on [Docker Hub](https://hub.docker.com/r/valkey/valkey/). - -### MacOS - -#### Using [Homebrew](https://brew.sh/) to install and run Valkey: - -```bash -brew install valkey -# To run Valkey as a service, use -brew services start valkey -# Check that it's running using -brew services info valkey -# and stop it using -brew services stop valkey -``` - -#### Using [MacPorts](https://www.macports.org/): - -```bash -sudo port install valkey -``` - -### Linux/BSD package managers - -The following package managers are known to be supported, but the list is not exhaustive and may not be up to date. -If you see an issue, feel free to submit a PR to update this list. -You can use the [pkgs.org](https://pkgs.org/download/valkey) website (linux/unix only) or [repology.org](https://repology.org/project/valkey/versions) to check which versions of Valkey are available for your distributions. - -#### apt (Debian based) - -Currently available on: -Debian/Ubuntu/Mint/Devuan/Raspbian/PureOS - -```bash -sudo apt update -sudo apt install valkey -# For symlinked binaries to redis-cli and other redis-* tools (on Ubuntu) -sudo apt install valkey-redis-compat -``` - -#### apk (Alpine Linux/Kali Linux/Wolfi) - -```bash -sudo apk update -sudo apk add valkey -# Below relevant for Alpine. -# For valkey-cli -sudo apk add valkey-cli -# For symlinked binaries to redis-cli and redis-server -sudo apk add valkey-compat -``` - -#### yum (CentOS/RHEL/Fedora) - -```bash -sudo yum install valkey -# For symlinked binaries to redis-cli and redis-server -sudo yum install valkey-compat-redis -# For valkey-doc (can be used with man, e.g. `man hgetall`, `man valkey.conf`, etc.) -sudo yum install valkey-doc -``` - -Some versions of CentOS and RHEL may not have Valkey in their default repositories. -You can use the EPEL repository - https://fedoraproject.org/wiki/EPEL to install Valkey. - -#### dnf (Fedora) - -```bash -sudo dnf install valkey -# For symlinked binaries to redis-cli and redis-server -sudo dnf install valkey-compat-redis -# For valkey-doc (can be used with man, e.g. `man hgetall`, `man valkey.conf`, etc.) -sudo dnf install valkey-doc -``` - -#### Other distributions - -```bash -# ALT Linux -sudo apt-get install valkey -# Arch Linux/Manjaro -sudo pacman -Sy valkey -# FreeBSD -sudo pkg install valkey -# NixOS -nix-env -i valkey -# openSUSE -sudo zypper install valkey -# Solus -sudo eopkg install valkey -# Void Linux -sudo xbps-install -Su valkey -# Exherbo -cave resolve -x dev-db/valkey -``` - -#### Miscellaneous - -Available on [SlackBuilds](https://slackbuilds.org/repository/15.0/system/valkey/) -and openpkg on [OpenPKG](http://www.openpkg.org/). - -### Windows - -Valkey is not officially supported on Windows. However, you can install Valkey -on Windows for development using WSL (Windows Subsystem for Linux). - -## Test if you can connect using the CLI - -If you're not yet running Valkey as a system service, -you can run Valkey in the foreground using `valkey-server` and stop it using Ctrl-C. - -When you have Valkey up and running, you can connect using `valkey-cli`. - -External programs talk to Valkey using a TCP socket and a Valkey specific protocol. This protocol is implemented in the Valkey client libraries for the different programming languages. However, to make hacking with Valkey simpler, Valkey provides a command line utility that can be used to send commands to Valkey. This program is called **valkey-cli**. - -The first thing to do to check if Valkey is working properly is sending a **PING** command using `valkey-cli`: - -``` -$ valkey-cli ping -PONG -``` - -Running **valkey-cli** followed by a command name and its arguments will send this command to the Valkey instance running on localhost at port 6379. You can change the host and port used by `valkey-cli` - just try the `--help` option to check the usage information. - -Another interesting way to run `valkey-cli` is without arguments: the program will start in interactive mode. You can type different commands and see their replies. - -``` -$ valkey-cli -127.0.0.1:6379> ping -PONG -``` - -## Securing Valkey - -By default Valkey binds to **all the interfaces** and has no authentication at all. If you use Valkey in a very controlled environment, separated from the external internet and in general from attackers, that's fine. However, if an unhardened Valkey is exposed to the internet, it is a big security concern. If you are not 100% sure your environment is secured properly, please check the following steps in order to make Valkey more secure: - -1. Make sure the port Valkey uses to listen for connections (by default 6379 and additionally 16379 if you run Valkey in cluster mode, plus 26379 for Sentinel) is firewalled, so that it is not possible to contact Valkey from the outside world. -2. Use a configuration file where the `bind` directive is set in order to guarantee that Valkey listens on only the network interfaces you are using. For example, only the loopback interface (127.0.0.1) if you are accessing Valkey locally from the same computer. -3. Set up authentication using [Access Control List (ACL)](acl.md) or use the `requirepass` option to add an additional layer of security so that clients will be required to authenticate using the `AUTH` command. -4. Use [TLS](tls.md) to encrypt traffic between Valkey servers and Valkey clients if your environment requires encryption. - -Make sure you understand the above and apply **at least** a firewall layer. After the firewall is in place, try to connect with `valkey-cli` from an external host to confirm that the instance is not reachable. - -## Use Valkey from your application - -Of course using Valkey just from the command line interface is not enough as the goal is to use it from your application. To do so, you need to download and install a Valkey client library for your programming language. - -You'll find a [full list of clients for different languages in this page](../clients/). - -## Valkey persistence - -You can learn [how Valkey persistence works on this page](persistence.md). -It is important to understand that, if you start Valkey with the default configuration, Valkey will spontaneously save the dataset only from time to time. -For example, after at least five minutes if you have at least 100 changes in your data. -If you want your database to persist and be reloaded after a restart, make sure to call the [SAVE](../commands/save.md) command manually every time you want to force a data set snapshot. -Alternatively, you can save the data on disk before quitting by using the [SHUTDOWN](../commands/shutdown.md) command: - -``` -$ valkey-cli shutdown -``` - -This way, Valkey will save the data on disk before quitting. Reading the [persistence page](persistence.md) is strongly suggested to better understand how Valkey persistence works. - -## Install Valkey as a system service - -Running Valkey from the command line is fine just to hack a bit or for development. However, at some point you'll have some actual application to run on a real server. -For this kind of usage, it's highly recommended to install Valkey as a system service so that everything will start properly after a system restart. -The available packages for supported Linux distributions already include the capability of starting the Valkey server as a service. - -Valkey supports systemd, but this document was written for init scripts, before systemd was widely adapted. -There are many guides online for how to set up a systemd service. - -The remainder of this section explains how to set up Valkey using an init script, for distros like Alpine Linux that don't use systemd. - -If you have not yet run `make install` after building the Valkey source, you will need to do so before continuing. By default, `make install` will copy the `valkey-server` and `valkey-cli` binaries to `/usr/local/bin`. - -- Create a directory in which to store your Valkey config files and your data: - - ``` - sudo mkdir /etc/valkey - sudo mkdir /var/valkey - ``` - -- Copy the init script that you'll find in the Valkey distribution under the **utils** directory into `/etc/init.d`. We suggest calling it with the name of the port where you are running this instance of Valkey. Make sure the resulting file has `0755` permissions. - - ``` - sudo cp utils/valkey_init_script /etc/init.d/valkey_6379 - ``` - -- Edit the init script. - - ``` - sudo vi /etc/init.d/valkey_6379 - ``` - -Make sure to set the `VALKEYPORT` variable to the port you are using. -Both the pid file path and the configuration file name depend on the port number. - -- Copy the template configuration file you'll find in the root directory of the Valkey distribution into `/etc/valkey/` using the port number as the name, for instance: - - ``` - sudo cp valkey.conf /etc/valkey/6379.conf - ``` - -- Create a directory inside `/var/valkey` that will work as both data and working directory for this Valkey instance: - - ``` - sudo mkdir /var/valkey/6379 - ``` - -- Edit the configuration file, making sure to perform the following changes: - - Set **daemonize** to yes (by default it is set to no). - - Set the **pidfile** to `/var/run/valkey_6379.pid`, modifying the port as necessary. - - Change the **port** accordingly. In our example it is not needed as the default port is already `6379`. - - Set your preferred **loglevel**. - - Set the **logfile** to `/var/log/valkey_6379.log`. - - Set the **dir** to `/var/valkey/6379` (very important step!). -- Finally, add the new Valkey init script to all the default runlevels using the following command: - - ``` - sudo update-rc.d valkey_6379 defaults - ``` - -You are done! Now you can try running your instance with: - -``` -sudo /etc/init.d/valkey_6379 start -``` - -Make sure that everything is working as expected: - -1. Try pinging your instance within a `valkey-cli` session using the `PING` command. -2. Do a test save with `valkey-cli save` and check that a dump file is correctly saved to `/var/valkey/6379/dump.rdb`. -3. Check that your Valkey instance is logging to the `/var/log/valkey_6379.log` file. -4. If it's a new machine where you can try it without problems, make sure that after a reboot everything is still working. - -## Configuring Valkey - -The above instructions don't include all of the Valkey configuration parameters that you could change. For example, to use AOF persistence instead of RDB persistence, or to set up replication, and so forth. - -You should also read the example [valkey.conf](https://github.com/valkey-io/valkey/blob/unstable/valkey.conf) file, which is heavily annotated to help guide you on making changes. Further details can also be found in the [configuration article on this site](valkey.conf.md). diff --git a/topics/introduction.md b/topics/introduction.md deleted file mode 100644 index 61f9579d..00000000 --- a/topics/introduction.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -title: Introduction -description: Learn about the Valkey open source project ---- - -Valkey is an open source (BSD licensed), in-memory __data structure store__ used as a database, cache, message broker, and streaming engine. Valkey provides [data structures](data-types.md) such as -[strings](strings.md), [hashes](hashes.md), [lists](lists.md), [sets](sets.md), [sorted sets](sorted-sets.md) with range queries, [bitmaps](bitmaps.md), [hyperloglogs](hyperloglogs.md), [geospatial indexes](geospatial.md), and [streams](streams-intro.md). Valkey has built-in [replication](replication.md), [Lua scripting](eval-intro.md), [LRU eviction](lru-cache.md), [transactions](transactions.md), and different levels of [on-disk persistence](persistence.md), and provides high availability via [Valkey Sentinel](sentinel.md) and automatic partitioning with [Valkey Cluster](cluster-tutorial.md). - -You can run __atomic operations__ -on these types, like [appending to a string](../commands/append.md); -[incrementing the value in a hash](../commands/hincrby.md); [pushing an element to a -list](../commands/lpush.md); [computing set intersection](../commands/sinter.md), -[union](../commands/sunion.md) and [difference](../commands/sdiff.md); -or [getting the member with highest ranking in a sorted set](../commands/zrange.md). - -To achieve top performance, Valkey works with an -**in-memory dataset**. Depending on your use case, Valkey can persist your data either -by periodically [dumping the dataset to disk](persistence.md#snapshotting) -or by [appending each command to a disk-based log](persistence.md#append-only-file). You can also disable persistence if you just need a feature-rich, networked, in-memory cache. - -Valkey supports [asynchronous replication](replication.md), with fast non-blocking synchronization and auto-reconnection with partial resynchronization on net split. - -Valkey also includes: - -* [Transactions](transactions.md) -* [Pub/Sub](pubsub.md) -* [Lua scripting](../commands/eval.md) -* [Keys with a limited time-to-live](../commands/expire.md) -* [LRU eviction of keys](lru-cache.md) -* [Automatic failover](sentinel.md) - -You can use Valkey from most programming languages. See [clients](../clients/). - -Valkey is written in **ANSI C 11** with Atomics and a few GCC/Clang built-ins like `__builtin_clz()`. -It works on most POSIX systems like Linux, \*BSD and MacOS, without external dependencies. -Linux and MacOS are the two operating systems where Valkey is developed and tested the most, and we **recommend using Linux for deployment**. -Valkey may work on Solaris-derived systems like Illumos, but support is *best effort*. -Supported hardware includes x86-64 (AKA amd64), x86 (32-bit) and AArch64 (64-bit ARM). -It is also known to work on IBM z/Architecture like s390x and builds for this system are available from the Fedora distro. -There is no official support for Windows builds. diff --git a/topics/key-specs.md b/topics/key-specs.md deleted file mode 100644 index a75f2ec8..00000000 --- a/topics/key-specs.md +++ /dev/null @@ -1,246 +0,0 @@ ---- - title: "Command key specifications" - linkTitle: "Command key specifications" - weight: 3 - description: What are command key specification and how to use them in your client - aliases: - - /topics/key-specs ---- - -Many of the commands in Valkey accept key names as input arguments. -The 9th element in the reply of `COMMAND` (and `COMMAND INFO`) is an array that consists of the command's key specifications. - -A _key specification_ describes a rule for extracting the names of one or more keys from the arguments of a given command. -Key specifications provide a robust and flexible mechanism, compared to the _first key_, _last key_ and _step_ scheme employed until Redis OSS 7.0. -Before introducing these specifications, Valkey clients had no trivial programmatic means to extract key names for all commands. - -Cluster-aware Valkey clients had to have the keys' extraction logic hard-coded in the cases of commands such as `EVAL` and `ZUNIONSTORE` that rely on a _numkeys_ argument or `SORT` and its many clauses. -Alternatively, the `COMMAND GETKEYS` can be used to achieve a similar extraction effect but at a higher latency. - -A Valkey client isn't obligated to support key specifications. -It can continue using the legacy _first key_, _last key_ and _step_ scheme along with the [_movablekeys_ flag](../commands/command.md#flags) that remain unchanged. - -However, a Valkey client that implements key specifications support can consolidate most of its keys' extraction logic. -Even if the client encounters an unfamiliar type of key specification, it can always revert to the `COMMAND GETKEYS` command. - -That said, most cluster-aware clients only require a single key name to perform correct command routing, so it is possible that although a command features one unfamiliar specification, its other specification may still be usable by the client. - -Key specifications are maps with the following keys: - -1. **begin_search:**: the starting index for keys' extraction. -2. **find_keys:** the rule for identifying the keys relative to the BS. -3. **notes**: notes about this key spec, if there are any. -4. **flags**: indicate the type of data access. - -## begin_search - -The _begin\_search_ value of a specification informs the client of the extraction's beginning. -The value is a map. -There are three types of `begin_search`: - -1. **index:** key name arguments begin at a constant index. -2. **keyword:** key names start after a specific keyword (token). -3. **unknown:** an unknown type of specification - see the [incomplete flag section](#incomplete) for more details. - -### index - -The _index_ type of `begin_search` indicates that input keys appear at a constant index. -It is a map under the _spec_ key with a single key: - -1. **index:** the 0-based index from which the client should start extracting key names. - -### keyword - -The _keyword_ type of `begin_search` means a literal token precedes key name arguments. -It is a map under the _spec_ with two keys: - -1. **keyword:** the keyword (token) that marks the beginning of key name arguments. -2. **startfrom:** an index to the arguments array from which the client should begin searching. - This can be a negative value, which means the search should start from the end of the arguments' array, in reverse order. - For example, _-2_'s meaning is to search reverse from the penultimate argument. - -More examples of the _keyword_ search type include: - -* `SET` has a `begin_search` specification of type _index_ with a value of _1_. -* `XREAD` has a `begin_search` specification of type _keyword_ with the values _"STREAMS"_ and _1_ as _keyword_ and _startfrom_, respectively. -* `MIGRATE` has a _start_search_ specification of type _keyword_ with the values of _"KEYS"_ and _-2_. - -## find_keys - -The `find_keys` value of a key specification tells the client how to continue the search for key names. -`find_keys` has three possible types: - -1. **range:** keys stop at a specific index or relative to the last argument. -2. **keynum:** an additional argument specifies the number of input keys. -3. **unknown:** an unknown type of specification - see the [incomplete flag section](#incomplete) for more details. - -### range - -The _range_ type of `find_keys` is a map under the _spec_ key with three keys: - -1. **lastkey:** the index, relative to `begin_search`, of the last key argument. - This can be a negative value, in which case it isn't relative. - For example, _-1_ indicates to keep extracting keys until the last argument, _-2_ until one before the last, and so on. -2. **keystep:** the number of arguments that should be skipped, after finding a key, to find the next one. -3. **limit:** if _lastkey_ is has the value of _-1_, we use the _limit_ to stop the search by a factor. - _0_ and _1_ mean no limit. - _2_ means half of the remaining arguments, 3 means a third, and so on. - -### keynum - -The _keynum_ type of `find_keys` is a map under the _spec_ key with three keys: - -* **keynumidx:** the index, relative to `begin_search`, of the argument containing the number of keys. -* **firstkey:** the index, relative to `begin_search`, of the first key. - This is usually the next argument after _keynumidx_, and its value, in this case, is greater by one. -* **keystep:** Tthe number of arguments that should be skipped, after finding a key, to find the next one. - -Examples: - -* The `SET` command has a _range_ of _0_, _1_ and _0_. -* The `MSET` command has a _range_ of _-1_, _2_ and _0_. -* The `XREAD` command has a _range_ of _-1_, _1_ and _2_. -* The `ZUNION` command has a _start_search_ type _index_ with the value _1_, and `find_keys` of type _keynum_ with values of _0_, _1_ and _1_. - -**Note:** -this isn't a perfect solution as the module writers can come up with anything. -However, this mechanism should allow the extraction of key name arguments for the vast majority of commands. - -## notes - -Notes about non-obvious key specs considerations, if applicable. - -## flags - -A key specification can have additional flags that provide more details about the key. -These flags are divided into three groups, as described below. - -### Access type flags - -The following flags declare the type of access the command uses to a key's value or its metadata. -A key's metadata includes LRU/LFU counters, type, and cardinality. -These flags do not relate to the reply sent back to the client. - -Every key specification has precisely one of the following flags: - -* **RW:** the read-write flag. - The command modifies the data stored in the value of the key or its metadata. - This flag marks every operation that isn't distinctly a delete, an overwrite, or read-only. -* **RO:** the read-only flag. - The command only reads the value of the key (although it doesn't necessarily return it). -* **OW:** the overwrite flag. - The command overwrites the data stored in the value of the key. -* **RM:** the remove flag. - The command deletes the key. - -### Logical operation flags - -The following flags declare the type of operations performed on the data stored as the key's value and its TTL (if any), not the metadata. -These flags describe the logical operation that the command executes on data, driven by the input arguments. -The flags do not relate to modifying or returning metadata (such as a key's type, cardinality, or existence). - -Every key specification may include the following flag: - -* **access:** the access flag. - This flag indicates that the command returns, copies, or somehow uses the user's data that's stored in the key. - -In addition, the specification may include precisely one of the following: - -* **update:** the update flag. - The command updates the data stored in the key's value. - The new value may depend on the old value. - This flag marks every operation that isn't distinctly an insert or a delete. -* **insert:** the insert flag. - The command only adds data to the value; existing data isn't modified or deleted. -* **delete:** the delete flag. - The command explicitly deletes data from the value stored at the key. - -### Miscellaneous flags - -Key specifications may have the following flags: - -* **not_key:** this flag indicates that the specified argument isn't a key. - This argument is treated the same as a key when computing which slot a command should be assigned to for Valkey cluster. - For all other purposes this argument should not be considered a key. -* **incomplete:** this flag is explained below. -* **variable_flags:** this flag is explained below. - -### incomplete - -Some commands feature exotic approaches when it comes to specifying their keys, which makes extraction difficult. -Consider, for example, what would happen with a call to `MIGRATE` that includes the literal string _"KEYS"_ as an argument to its _AUTH_ clause. -Our key specifications would miss the mark, and extraction would begin at the wrong index. - -Thus, we recognize that key specifications are incomplete and may fail to extract all keys. -However, we assure that even incomplete specifications never yield the wrong names of keys, providing that the command is syntactically correct. - -In the case of `MIGRATE`, the search begins at the end (_startfrom_ has the value of _-1_). -If and when we encounter a key named _"KEYS"_, we'll only extract the subset of the key name arguments after it. -That's why `MIGRATE` has the _incomplete_ flag in its key specification. - -Another case of incompleteness is the `SORT` command. -Here, the `begin_search` and `find_keys` are of type _unknown_. -The client should revert to calling the `COMMAND GETKEYS` command to extract key names from the arguments, short of implementing it natively. -The difficulty arises, for example, because the string _"STORE"_ is both a keyword (token) and a valid literal argument for `SORT`. - -**Note:** -the only commands with _incomplete_ key specifications are `SORT` and `MIGRATE`. -We don't expect the addition of such commands in the future. - -### variable_flags - -In some commands, the flags for the same key name argument can depend on other arguments. -For example, consider the `SET` command and its optional _GET_ argument. -Without the _GET_ argument, `SET` is write-only, but it becomes a read and write command with it. -When this flag is present, it means that the key specification flags cover all possible options, but the effective flags depend on other arguments. - -## Examples - -### `SET`'s key specifications - -``` - 1) 1) "flags" - 2) 1) RW - 2) access - 3) update - 3) "begin_search" - 4) 1) "type" - 2) "index" - 3) "spec" - 4) 1) "index" - 2) (integer) 1 - 5) "find_keys" - 6) 1) "type" - 2) "range" - 3) "spec" - 4) 1) "lastkey" - 2) (integer) 0 - 3) "keystep" - 4) (integer) 1 - 5) "limit" - 6) (integer) 0 -``` - -### `ZUNION`'s key specifications - -``` - 1) 1) "flags" - 2) 1) RO - 2) access - 3) "begin_search" - 4) 1) "type" - 2) "index" - 3) "spec" - 4) 1) "index" - 2) (integer) 1 - 5) "find_keys" - 6) 1) "type" - 2) "keynum" - 3) "spec" - 4) 1) "keynumidx" - 2) (integer) 0 - 3) "firstkey" - 4) (integer) 1 - 5) "keystep" - 6) (integer) 1 -``` diff --git a/topics/keyspace.md b/topics/keyspace.md deleted file mode 100644 index 8a6f17cd..00000000 --- a/topics/keyspace.md +++ /dev/null @@ -1,140 +0,0 @@ ---- -title: "Keyspace" -description: > - Managing keys in Valkey: Key expiration, scanning, altering and querying the key space ---- - -Valkey keys are binary safe; this means that you can use any binary sequence as a -key, from a string like "foo" to the content of a JPEG file. -The empty string is also a valid key. - -A few other rules about keys: - -* Very long keys are not a good idea. For instance a key of 1024 bytes is a bad - idea not only memory-wise, but also because the lookup of the key in the - dataset may require several costly key-comparisons. Even when the task at hand - is to match the existence of a large value, hashing it (for example - with SHA1) is a better idea, especially from the perspective of memory - and bandwidth. -* Very short keys are often not a good idea. There is little point in writing - "u1000flw" as a key if you can instead write "user:1000:followers". The latter - is more readable and the added space is minor compared to the space used by - the key object itself and the value object. While short keys will obviously - consume a bit less memory, your job is to find the right balance. -* Try to stick with a schema. For instance "object-type:id" is a good - idea, as in "user:1000". Dots or dashes are often used for multi-word - fields, as in "comment:4321:reply.to" or "comment:4321:reply-to". -* The maximum allowed key size is 512 MB. - -## Altering and querying the key space - -There are commands that are not defined on particular types, but are useful -in order to interact with the space of keys, and thus, can be used with -keys of any type. - -For example the `EXISTS` command returns 1 or 0 to signal if a given key -exists or not in the database, while the `DEL` command deletes a key -and associated value, whatever the value is. - - > set mykey hello - OK - > exists mykey - (integer) 1 - > del mykey - (integer) 1 - > exists mykey - (integer) 0 - -From the examples you can also see how `DEL` itself returns 1 or 0 depending on whether -the key was removed (it existed) or not (there was no such key with that -name). - -There are many key space related commands, but the above two are the -essential ones together with the `TYPE` command, which returns the kind -of value stored at the specified key: - - > set mykey x - OK - > type mykey - string - > del mykey - (integer) 1 - > type mykey - none - -## Key expiration - -Before moving on, we should look at an important Valkey feature that works regardless of the type of value you're storing: key expiration. Key expiration lets you set a timeout for a key, also known as a "time to live", or "TTL". When the time to live elapses, the key is automatically destroyed. - -A few important notes about key expiration: - -* They can be set both using seconds or milliseconds precision. -* However the expire time resolution is always 1 millisecond. -* Information about expires are replicated and persisted on disk, the time virtually passes when your Valkey server remains stopped (this means that Valkey saves the date at which a key will expire). - -Use the `EXPIRE` command to set a key's expiration: - - > set key some-value - OK - > expire key 5 - (integer) 1 - > get key (immediately) - "some-value" - > get key (after some time) - (nil) - -The key vanished between the two `GET` calls, since the second call was -delayed more than 5 seconds. In the example above we used `EXPIRE` in -order to set the expire (it can also be used in order to set a different -expire to a key already having one, like `PERSIST` can be used in order -to remove the expire and make the key persistent forever). However we -can also create keys with expires using other Valkey commands. For example -using `SET` options: - - > set key 100 ex 10 - OK - > ttl key - (integer) 9 - -The example above sets a key with the string value `100`, having an expire -of ten seconds. Later the `TTL` command is called in order to check the -remaining time to live for the key. - -In order to set and check expires in milliseconds, check the `PEXPIRE` and -the `PTTL` commands, and the full list of `SET` options. - -## Navigating the keyspace - -### Scan -To incrementally iterate over the keys in a Valkey database in an efficient manner, you can use the `SCAN` command. - -Since `SCAN` allows for incremental iteration, returning only a small number of elements per call, it can be used in production without the downside of commands like `KEYS` or `SMEMBERS` that may block the server for a long time (even several seconds) when called against big collections of keys or elements. - -However while blocking commands like `SMEMBERS` are able to provide all the elements that are part of a Set in a given moment. -The `SCAN` family of commands only offer limited guarantees about the returned elements since the collection that we incrementally iterate can change during the iteration process. - -### Keys - -Another way to iterate over the keyspace is to use the `KEYS` command, but this approach should be used with care, since `KEYS` will block the Valkey server until all keys are returned. - -**Warning**: consider `KEYS` as a command that should only be used in production -environments with extreme care. - -`KEYS` may ruin performance when it is executed against large databases. -This command is intended for debugging and special operations, such as changing -your keyspace layout. -Don't use `KEYS` in your regular application code. -If you're looking for a way to find keys in a subset of your keyspace, consider -using `SCAN` or [sets][tdts]. - -[tdts]: data-types.md#sets - -Supported glob-style patterns: - -* `h?llo` matches `hello`, `hallo` and `hxllo` -* `h*llo` matches `hllo` and `heeeello` -* `h[ae]llo` matches `hello` and `hallo,` but not `hillo` -* `h[^e]llo` matches `hallo`, `hbllo`, ... but not `hello` -* `h[a-b]llo` matches `hallo` and `hbllo` - -Use `\` to escape special characters if you want to match them verbatim. diff --git a/topics/large-object-configuration.md b/topics/large-object-configuration.md deleted file mode 100644 index f9e05497..00000000 --- a/topics/large-object-configuration.md +++ /dev/null @@ -1,247 +0,0 @@ ---- -title: "Valkey Large Object - Configuration and Monitoring" -description: Configuration parameters, ACL category, and INFO fields of the Valkey Large Object module ---- - -> **Note:** [valkey-large-object](https://github.com/valkey-io/valkey-large-object) is at version 0.x. -> Commands, arguments, replies, and configuration can change before version 1.0. - -## Set configurations - -The configuration names have the `largeobj.` prefix, for example `largeobj.segment-size`. -Set the configurations when the module loads, with the full names. -Memory sizes can have units, such as `64mb` and `1gb`. - -In `valkey.conf`, put each configuration on its own line: - -``` -loadmodule /path/to/libvalkey_large_object.so -largeobj.operating-mode Dram -largeobj.segment-size 64mb -largeobj.max-object-size 32mb -``` - -On the command line: - -```bash -valkey-server --loadmodule /path/to/libvalkey_large_object.so \ - --largeobj.operating-mode Dram \ - --largeobj.segment-size 64mb \ - --largeobj.max-object-size 32mb -``` - -With [`MODULE LOADEX`](../commands/module-loadex.md): - -``` -MODULE LOADEX /path/to/libvalkey_large_object.so CONFIG largeobj.operating-mode Dram CONFIG largeobj.segment-size 64mb CONFIG largeobj.max-object-size 32mb -``` - -The configurations with `No` in the Mutable column can be set only when the module loads. -A lower `largeobj.max-object-size` does not change objects that are already stored. - -## Disk directory - -> **Warning:** In `Tiered` mode, the module deletes the `largeobj.disk-dir` directory and all its contents at startup and at shutdown, then creates it again, empty. -> Set `largeobj.disk-dir` to a new, empty directory that only this module uses, below the mount point (for example `/mnt/nvme/largeobj`). -> Never use a directory that has other data, or a mount point. - -## Configuration parameters - -This table shows the configurations that you are most likely to set. -For the full list, see the [module repository](https://github.com/valkey-io/valkey-large-object). - -| Name | Type | Default | Range | Mutable | Description | -|:-----|:-----|:--------|:------|:--------|:------------| -| `largeobj.operating-mode` | enum | `Dram` | `Dram`, `Tiered` | No | `Dram`: objects are in DRAM only. `Tiered`: objects are on NVMe and DRAM is a read cache. | -| `largeobj.disk-dir` | string | `""` | - | No | Directory for object files. Necessary in `Tiered` mode. Must be on XFS, the only supported file system, with `O_DIRECT` and user extended attributes, and a writable parent. **Deleted at startup and shutdown: see [Disk directory](#disk-directory).** | -| `largeobj.disk-dir-shards` | integer | `1024` | 1 to 65536 | No | `Tiered`: number of subdirectories of `largeobj.disk-dir` for the object files. More subdirectories let file creates and deletes run in parallel. | -| `largeobj.segment-size` | memory | `1gb` | 1mb to 1gb | No | Size of each DRAM pool segment and disk staging segment. Must be at least two times `largeobj.chunk-size`. The pool grows in segments; in `Tiered` mode it also shrinks. Each pool has at most 16384 segments: the DRAM pool stops at 16384 x `largeobj.segment-size`, and `largeobj.disk-staging-size` / `largeobj.segment-size` must not be more than 16384. | -| `largeobj.disk-staging-size` | memory | `1gb` | 1mb to 2^63-1 | No | `Tiered`: total size of the DRAM staging buffers for disk I/O. | -| `largeobj.disk-maxmemory` | memory | `0` | 0 to 2^63-1 | Yes | Maximum disk use in `largeobj.disk-dir`. Each file counts as its length rounded up to 4KB, or, on a striped XFS, to the stripe unit for files of at least one stripe unit. On XFS, each file also counts its inode. A file also counts the metadata blocks that it uses outside its inode (see `disk_metadata_spills`). `0` is unlimited. | -| `largeobj.max-object-size` | memory | `512mb` | 1 to 2^63-1 | Yes | Maximum object size for `BLOB.TCP_SET` and `BLOB.RDMA_SET`. `BLOB.TCP_SET` is also limited by the core `proto-max-bulk-len` (default 512MB). | -| `largeobj.max-promote-size` | memory | `256mb` | 0 to 2^63-1 | Yes | `Tiered`: maximum size of an object that is promoted from disk to DRAM. `0` disables promotion. | -| `largeobj.chunk-size` | memory | `1mb` | 4096 to 256mb | No | Chunk size for streaming I/O. Must be a multiple of 4096. | -| `largeobj.max-buffers-per-op` | integer | `64` | 2 to 1024 | Yes | Maximum number of `largeobj.chunk-size` buffers that one streaming operation holds. In `Tiered` mode, a lower value lets more disk operations share the disk staging buffers. | -| `largeobj.min-buffers-per-op` | integer | `2` | 1 to 1024 | Yes | `Tiered`: minimum number of `largeobj.chunk-size` buffers that a disk operation must get to start. If fewer buffers are free, the operation fails with `ERR disk staging buffer pool exhausted; retry later`. Must not be more than `largeobj.max-buffers-per-op`. | -| `largeobj.worker-threads` | integer | `8` | 1 to 32 | No | Number of worker threads for asynchronous I/O. | -| `largeobj.scaling-shrink-watermark` | integer (%) | `90` | 50 to 95 | Yes | Server `used_memory` / `maxmemory`, in percent, above which the DRAM pool does not expand. In `Tiered` mode, the pool also releases segments above this value (the objects stay on disk). | -| `largeobj.promote-min-hits` | integer | `1` | 1 to 255 | Yes | `Tiered`: number of disk reads of an object; the read that reaches this number promotes the object to DRAM. `1` promotes on the first read. | -| `largeobj.fabric-provider` | enum | `EfaDirect` | `EfaDirect`, `Emulated` | No | libfabric provider for RDMA. `EfaDirect`: EFA hardware (see [Providers](large-object-rdma.md#providers)). `Emulated`: libfabric over TCP sockets, for development and tests only. | -| `largeobj.fabric-interfaces` | string | `""` | - | No | Comma-separated list of fabric domains to use. Empty uses all domains that the provider finds. | -| `largeobj.fabric-crc-pool-threads` | integer | `2` | 1 to 1024 | No | Number of threads that calculate checksums for `BLOB.RDMA_SET` transfers. | -| `largeobj.max-rdma-registered-bytes` | memory | `380gb` | 0 to 2^63-1 | Yes | Maximum bytes of DRAM pool and disk staging segments that are registered with the fabric. The pool does not expand above this value. `0` is unlimited. No effect when the fabric is not available. | -| `largeobj.enabled` | bool | `yes` | `yes`, `no` | Yes | `no` rejects all large object commands with `DISABLED largeobj module is disabled`. Stored keys stay, and core commands such as `DEL` still work on them. | - -## Cross-configuration rules - -The module checks these rules when it loads. -It checks them again when `CONFIG SET` changes `largeobj.disk-maxmemory`, `largeobj.max-object-size`, `largeobj.max-promote-size`, `largeobj.max-buffers-per-op`, or `largeobj.min-buffers-per-op`. -If a rule is not satisfied, the module does not load, or `CONFIG SET` fails with the error in the table. - -| Rule | Mode | Error | -|:-----|:-----|:------| -| `largeobj.disk-maxmemory` is `0` or equal to or larger than `largeobj.max-object-size` | `Tiered` | `ERR largeobj.disk-maxmemory must be >= largeobj.max-object-size in Tiered mode` | -| `largeobj.disk-staging-size` is equal to or larger than `largeobj.segment-size` | `Tiered` | `ERR largeobj.disk-staging-size must be >= largeobj.segment-size` | -| `largeobj.segment-size` is equal to or larger than two times `largeobj.chunk-size` | All | `ERR largeobj.segment-size must be >= 2 * largeobj.chunk-size` | -| `largeobj.chunk-size` is a multiple of 4096 | All | `ERR largeobj.chunk-size must be a multiple of 4096` | -| `largeobj.max-buffers-per-op` is equal to or larger than `largeobj.min-buffers-per-op` | All | `ERR largeobj.max-buffers-per-op must be >= largeobj.min-buffers-per-op` | -| An object of `largeobj.max-object-size` fits in one segment | `Dram` | `ERR largeobj.segment-size is insufficient for largeobj.max-object-size` | -| An object of `largeobj.max-promote-size` fits in one segment | `Tiered` | `ERR largeobj.segment-size is insufficient for largeobj.max-promote-size` | - -An object "fits in one segment" when its chunks, plus 4KB of overhead for each chunk, plus 4KB, are not larger than `largeobj.segment-size`. -Thus `largeobj.max-object-size` must be a little smaller than `largeobj.segment-size` in `Dram` mode. -For example, with 64MB segments and the default `largeobj.chunk-size`, the largest `largeobj.max-object-size` is 66842624 bytes (`largeobj.segment-size` minus 260KB). -In `Tiered` mode, `largeobj.max-promote-size` (default 256MB) must fit in one segment, with the same overhead as `largeobj.max-object-size` (with 64MB segments, at most 66842624). -The default values (`largeobj.segment-size` `1gb`, `largeobj.max-object-size` `512mb`, `largeobj.chunk-size` `1mb`) satisfy all rules. - -## Memory and eviction - -The DRAM limit is the core Valkey `maxmemory` setting, together with `largeobj.scaling-shrink-watermark`. -When the fabric is available, `largeobj.max-rdma-registered-bytes` also limits the DRAM pool. -The maximum number of segments also limits the DRAM pool (see `largeobj.segment-size` in [Configuration parameters](#configuration-parameters)). - -A write can evict other large objects to make space. -The core `maxmemory-policy` setting controls which objects the module can evict: - -* `allkeys-*` policies - any large object. -* `volatile-*` policies - only large object keys that have a TTL. -* `noeviction` - no object. - The write fails with an `OOM` error. - -The module evicts in least recently used (LRU) order for all policies. -A read and a TTL change count as a use. -For the `*-lfu`, `*-random`, and `volatile-ttl` policies, the module also uses LRU order, and the server log shows a warning. - -* `Dram` mode - Eviction occurs only when `maxmemory` is set. -* `Tiered` mode - Eviction removes object files when `largeobj.disk-maxmemory` is larger than `0`. - `maxmemory` is not necessary for disk eviction. - When the DRAM cache is full, the module drops cached copies with the lowest LFU score (demotion). - The objects stay on disk. - -An evicted key stays in the keyspace until the module deletes it, within a few milliseconds when the backlog is small. -Until then, a read returns nil, but `EXISTS` and `DBSIZE` still count the key. -`pending_evictions` shows how many evicted keys wait to be deleted. - -## ACL - -The module adds the ACL category `@largeobj`. -All large object commands are in this category, and no other commands are. - -| Command | @largeobj | @read | @write | @connection | @fast | -|:--------|:----------|:------|:-------|:------------|:------| -| `BLOB.TCP_SET` | y | | y | | y | -| `BLOB.TCP_GET` | y | y | | | y | -| `BLOB.RDMA_HELLO` | y | | | y | y | -| `BLOB.RDMA_SET` | y | | y | | y | -| `BLOB.RDMA_GET` | y | y | | | y | -| `BLOB.INFO` | y | y | | | y | - -For example, this user can use all large object commands on keys that start with `kv:`: - -``` -127.0.0.1:6379> ACL SETUSER cache-client on >password +@largeobj ~kv:* -OK -``` - -`DEL` and `UNLINK` are not in `@largeobj`, so a user that must delete large object keys also needs these commands, for example `+@largeobj +del +unlink`. - -To stop a user from using the module, remove the category from the user, for example `ACL SETUSER -@largeobj`. - -## Security - -* The TCP commands carry the object data on the normal Valkey connection. - If you use Valkey TLS, TLS also protects this data. -* The RDMA commands carry only the command, the key, the client memory regions, and the reply on the Valkey connection. - The object data moves directly between client memory and server memory over the fabric, not through the Valkey connection. - Valkey TLS does not protect this data, and the module does not encrypt it. -* In `Tiered` mode, the module does not encrypt the object files in `largeobj.disk-dir`. - If you need encryption at rest, use file system or disk encryption. -* For an RDMA transfer, the server reads or writes only the client memory regions that the command names, at the client endpoint of the session of that connection. -* The server registers its own memory for local access only. - A client cannot read or write server memory directly; the server starts every transfer. - -## What to watch - -The field names in this table are without the `largeobj_` prefix (see [INFO fields](#info-fields)). - -| Field | What it tells you | Action | -|:------|:------------------|:-------| -| `evictions` | Large object keys evicted to make space. | If it grows fast, add memory or disk, or store fewer objects. | -| `pending_evictions` | Evicted keys that the module did not delete yet. | If it stays high, the module cannot delete keys as fast as it evicts them. | -| `dram_pool_exhausted`, `disk_capacity_exceeded` | Writes that the module failed with `OOM`. A write that core Valkey rejects with `OOM` before the module runs is not counted. | Raise `maxmemory` or `largeobj.disk-maxmemory`, or use a `maxmemory-policy` that permits eviction. | -| `disk_staging_buffer_exhausted` | `Tiered` disk operations that failed because of too much concurrency. | Raise `largeobj.disk-staging-size`, lower `largeobj.max-buffers-per-op`, or send fewer concurrent operations. | -| `disk_write_errors`, `disk_read_errors` | Failed disk I/O. | Look at the server log and the disk health. | -| `rdma_read_errors`, `rdma_write_errors`, `crc_mismatch` | Failed RDMA transfers. | Look at the client: registered regions, endpoint, and checksum. | - -The core `evicted_keys` field in `INFO stats` does not count large objects that the module evicts. -The module deletes the evicted keys itself (with an unlink), not through core eviction. -Use `evictions` in `INFO largeobj` instead. - -## INFO fields - -Use `INFO largeobj` to see the module metrics. -When `largeobj.enabled` is `no` and no large objects are stored, `INFO largeobj` returns no sections. -Valkey adds the `largeobj_` prefix to each section name and field name, for example section `largeobj_core_metrics` and field `largeobj_num_objects`. -The tables below show the names without the prefix. -They show only the most important fields. -For the full list, see the [module repository](https://github.com/valkey-io/valkey-large-object). - -### `core_metrics` - -| Field | Description | -|:------|:------------| -| `num_objects` | Number of large objects. | -| `inflight_requests` | Number of large object commands that are in progress. | - -### `evictions` - -| Field | Description | -|:------|:------------| -| `evictions` | Number of objects evicted to make space for a write. `Tiered` cache drops are demotions and are not counted. | -| `pending_evictions` | Number of evicted keys that the module did not finish deleting. These keys read as missing. | - -### `dram` - -| Field | Description | -|:------|:------------| -| `dram_segments` | Number of DRAM pool segments. | -| `dram_allocated_bytes` | Bytes allocated in the DRAM pool. | -| `dram_capacity_bytes` | Pool capacity: (segments minus draining segments) multiplied by the segment size. | -| `dram_utilization_pct` | DRAM pool use in percent. | -| `dram_objects` | Number of objects in DRAM. | -| `cache_hits` | `Tiered` only: reads served from the DRAM cache. | -| `cache_misses` | `Tiered` only: reads served from disk. | -| `cache_promotions` | `Tiered` only: objects promoted to the DRAM cache. | -| `cache_demotions` | `Tiered` only: cached copies dropped from DRAM. | -| `dram_rdma_registered_segments` | DRAM pool segments registered with the fabric. `0` when the fabric is not available. | - -### `disk` - -This section is only in `Tiered` mode. - -| Field | Description | -|:------|:------------| -| `disk_used_bytes` | Bytes used in `largeobj.disk-dir`, counted as for `largeobj.disk-maxmemory`. | -| `disk_utilization_pct` | `disk_used_bytes` as a percent of `largeobj.disk-maxmemory`. `0.00` when `largeobj.disk-maxmemory` is `0`. | -| `disk_metadata_spills` | Number of object files that use disk blocks outside their inode, in addition to their data. For example, a file that has more extents than its inode can list uses one more block. These blocks count in `disk_used_bytes`. | - -### `rdma` - -| Field | Description | -|:------|:------------| -| `rdma_sessions` | Number of open RDMA sessions. | -| `rdma_read_bytes` | Bytes that the server read from client memory (`BLOB.RDMA_SET`). | -| `rdma_write_bytes` | Bytes that the server wrote into client memory (`BLOB.RDMA_GET`). | - -### `error_metrics` - -| Field | Description | -|:------|:------------| -| `disk_read_errors` | Failed disk reads. | -| `disk_write_errors` | Failed disk writes. | -| `rdma_read_errors` | Failed RDMA reads from client memory. | -| `rdma_write_errors` | Failed RDMA writes into client memory. | -| `dram_pool_exhausted` | Writes that could not get DRAM pool memory. | -| `disk_staging_buffer_exhausted` | `Tiered` disk reads and writes that failed with `ERR disk staging buffer pool exhausted; retry later`, because too many disk operations ran at the same time for the disk staging buffers. | -| `disk_capacity_exceeded` | Writes that failed because of `largeobj.disk-maxmemory`. | -| `crc_mismatch` | `BLOB.RDMA_SET` writes rejected because the `CRC` value did not agree. | diff --git a/topics/large-object-getting-started.md b/topics/large-object-getting-started.md deleted file mode 100644 index c50015ae..00000000 --- a/topics/large-object-getting-started.md +++ /dev/null @@ -1,262 +0,0 @@ ---- -title: "Valkey Large Object - Getting Started" -description: How to build, load, and try the Valkey Large Object module ---- - -> **Note:** [valkey-large-object](https://github.com/valkey-io/valkey-large-object) is at version 0.x. -> Commands, arguments, replies, and configuration can change before version 1.0. - -This page shows how to build the module from source, load it into Valkey, and run your first commands. - -## Requirements - -* Valkey - Valkey 8.0 or later. -* Linux on `x86_64` or `aarch64` - The module has no architecture-specific code. -* Linux 5.1 or later (`Tiered` mode only) - The module uses io_uring for disk I/O, with the operations `IORING_OP_READV`, `IORING_OP_WRITEV`, `IORING_OP_READ_FIXED`, and `IORING_OP_WRITE_FIXED`, and with registered buffers (`IORING_REGISTER_BUFFERS`). - These are in Linux 5.1 and later. -* Rust - A recent stable Rust toolchain with `cargo`, for example from [rustup](https://rustup.rs/). -* Build tools - `clang` and its development files (for example `libclang-dev`), `gcc`, `make`, `git`, and `pkg-config`. -* libfabric - libfabric 2.0 or later and its development files are necessary at build time, also when you use only TCP. - The module uses the libfabric 2.0 interface (symbol version `FABRIC_1.8`), and the build needs the header `rdma/fi_collective.h`. - An older libfabric, for example 1.8.0, fails. - The build finds libfabric with `pkg-config`; check with `pkg-config --modversion libfabric`. - If libfabric is in a different location, or the default libfabric is older than 2.0, set `PKG_CONFIG_PATH` to the `lib/pkgconfig` directory of the newer one. - Then also set `LD_LIBRARY_PATH` to its `lib` directory when you run `valkey-server` or `build.sh`. -* EFA (optional) - The default fabric provider, `EfaDirect`, uses Elastic Fabric Adapter (EFA) hardware for RDMA. - Without RDMA hardware, use the TCP commands. - To develop and test RDMA client code without RDMA hardware, set `largeobj.fabric-provider` to `Emulated` (see [Providers](large-object-rdma.md#providers)). -* Locked memory - The module registers (pins) each segment one time for each fabric domain, and one more time for io_uring in `Tiered` mode. - This counts against `RLIMIT_MEMLOCK`. - Set the limit to `unlimited` (for example `ulimit -l unlimited`, or `LimitMEMLOCK=infinity` in a systemd unit), or to at least the total segment bytes times the number of registrations. -* RDMA clients - The libfabric provider of the client must support RMA (`FI_RMA`) with remote read and remote write, and the client needs a locked-memory limit for its registered buffers (see [Roles](large-object-rdma.md#roles)). -* XFS (`Tiered` mode only) - XFS is the only supported file system for `largeobj.disk-dir`, for example XFS on a local NVMe disk. - The module needs `O_DIRECT` and user extended attributes (`user.*` attributes): it stores a small header for each object file in the `user.lobj` extended attribute. - Other file systems, for example ext4, are not supported, also when they have these features. - On such a file system, the module loads with a warning in the log. - The module does not check for `O_DIRECT` and extended attributes when it loads. - On a file system without them, every write fails with `ERR disk write failed`. - -## Build from source - -```bash -git clone https://github.com/valkey-io/valkey-large-object -cd valkey-large-object -cargo build --release -``` - -The build writes the module library to `target/release/libvalkey_large_object.so`. - -The repository also has a `build.sh` script. -`./build.sh build` runs format and lint checks, the release build, and the unit tests. -`./build.sh` with no arguments also runs the integration tests against a Valkey server. - -If `bindgen` cannot find the standard C headers (for example `stddef.h`), add the GCC include directory: - -```bash -BINDGEN_EXTRA_CLANG_ARGS="-I$(gcc -print-file-name=include)" cargo build --release -``` - -## Load the module - -Set the module configurations with their full `largeobj.` names after `--loadmodule`. -Memory sizes can have units, such as `64mb`. -To load the module from `valkey.conf` or with `MODULE LOADEX`, see [Set configurations](large-object-configuration.md#set-configurations). -For all parameters, see [Valkey Large Object - Configuration and Monitoring](large-object-configuration.md). - -### Dram mode - -This example loads the module in `Dram` mode with 64MB segments. -`largeobj.max-object-size` must fit in one segment, so this example sets it to 32MB. - -```bash -valkey-server --port 6379 \ - --maxmemory 4gb \ - --maxmemory-policy allkeys-lru \ - --loadmodule ./target/release/libvalkey_large_object.so \ - --largeobj.operating-mode Dram \ - --largeobj.segment-size 64mb \ - --largeobj.max-object-size 32mb -``` - -In `Dram` mode, `maxmemory` is the DRAM limit, and `largeobj.max-rdma-registered-bytes` and the maximum number of segments also limit the DRAM pool. -With `allkeys-lru`, a write evicts the least recently used large objects when the module is full, and does not fail with `OOM`. -See [Memory and eviction](large-object-configuration.md#memory-and-eviction). - -### Tiered mode - -> **Warning:** In `Tiered` mode, the module deletes the `largeobj.disk-dir` directory and all its contents at startup and at shutdown, then creates it again, empty. -> Set `largeobj.disk-dir` to a new, empty directory that only this module uses, below the mount point (for example `/mnt/nvme/largeobj`). -> Never use a directory that has other data, or a mount point. - -This example stores objects on NVMe in `/mnt/nvme/largeobj` and uses DRAM as a read cache. -It uses 64MB segments, a 32MB maximum object size and promotion size, a 10GB disk limit, and 64MB of disk staging buffers. - -```bash -valkey-server --port 6379 \ - --maxmemory 4gb \ - --maxmemory-policy allkeys-lru \ - --loadmodule ./target/release/libvalkey_large_object.so \ - --largeobj.operating-mode Tiered \ - --largeobj.disk-dir /mnt/nvme/largeobj \ - --largeobj.segment-size 64mb \ - --largeobj.max-object-size 32mb \ - --largeobj.max-promote-size 32mb \ - --largeobj.disk-maxmemory 10gb \ - --largeobj.disk-staging-size 64mb -``` - -The module puts the object files in `largeobj.disk-dir-shards` subdirectories of `largeobj.disk-dir` (default 1024, named `0000` to `03ff`), and makes these subdirectories when it starts. - -### Load failures - -The module does not load if a configuration value is out of range, if the cross-configuration rules are not satisfied, or if the storage cannot start (for example, in `Tiered` mode, a `largeobj.disk-dir` that the module cannot create or clean). -The server log shows the cause. - -These are log messages that you are most likely to see when the module does not load: - -| Log message | Cause and fix | -|:------------|:--------------| -| ``libfabric.so.1: version `FABRIC_1.8' not found`` | An older libfabric is loaded at run time. Set `LD_LIBRARY_PATH` to the `lib` directory of libfabric 2.0 or later. | -| `fatal error: fi_collective.h: No such file or directory` (at build time) | The libfabric that `pkg-config` finds is older than 2.0. Set `PKG_CONFIG_PATH` to a newer libfabric. | -| `largeobj.segment-size is insufficient for largeobj.max-object-size` or `largeobj.max-promote-size` | See [Cross-configuration rules](large-object-configuration.md#cross-configuration-rules). | -| `largeobj: startup failed to reset disk-dir : Device or resource busy (os error 16); aborting module load` | `Tiered` mode: `largeobj.disk-dir` is a mount point. The module deletes the contents of the mounted file system, then cannot remove the mount point. Use a dedicated subdirectory of the mount for `largeobj.disk-dir`. | -| `largeobj: startup failed to reset disk-dir : ; aborting module load`, with an error such as `Permission denied` or `Read-only file system` | `Tiered` mode: the module deletes and creates `largeobj.disk-dir` at startup, and it could not. Make the parent directory of `largeobj.disk-dir` and the file system writable by the server user. | -| `largeobj: startup failed to reset disk-dir : disk-dir is required in Tiered operating mode; aborting module load` | `Tiered` mode: `largeobj.disk-dir` is not set. Set `largeobj.disk-dir` to a directory on the disk. | -| `largeobj: storage init failed: failed to create disk-dir shards under : ` | `Tiered` mode: the module could not create the `largeobj.disk-dir-shards` subdirectories, for example because the file system is full or read-only. Free space or fix the mount. | -| `largeobj: storage init failed: disk-dir has a block size of B, which does not divide the 4096 B I/O alignment; ...` | `Tiered` mode: the file system block size does not divide 4096, for example 64KB blocks. The module cannot count disk use exactly, so it does not load. Put `largeobj.disk-dir` on a file system with a block size of 4096 B or less. | -| `largeobj: storage init failed: cannot read disk-dir XFS geometry: `, or `cannot open disk-dir : `, or `cannot statfs disk-dir : ` | `Tiered` mode: the module could not read the file system geometry that it needs to count disk use, so it does not load. Make sure that the mount is healthy and that the server can read `largeobj.disk-dir`. | -| `largeobj: storage init failed: too many segments (DRAM , NVMe ). Max 16384 per pool. Increase segment-size or decrease disk-staging-size` | `Tiered` mode: `largeobj.disk-staging-size` divided by `largeobj.segment-size` is more than 16384. Make `largeobj.segment-size` larger or `largeobj.disk-staging-size` smaller. | -| `IORING_REGISTER_BUFFERS failed: Cannot allocate memory (os error 12)` | `Tiered` mode: the locked-memory limit is too low. Raise `RLIMIT_MEMLOCK` (see [Requirements](#requirements)). | -| `EFA registration of segment at ... failed (fatal)` | The server aborts, because a segment cannot be registered with the fabric. Raise the locked-memory limit (`ulimit -l`, `LimitMEMLOCK`), or set a lower `largeobj.max-rdma-registered-bytes`. | - -If the fabric provider does not start, the module loads and only the TCP commands are available. -The server log then shows `largeobj: fabric unavailable, RDMA path disabled`. - -If `largeobj.disk-dir` is not on XFS, the module loads, and the log shows `largeobj: disk-dir is not on XFS; disk usage is charged in 4096 B blocks`. -Only XFS is supported. -If `largeobj.disk-dir` does not support `O_DIRECT` or user extended attributes, the module loads, but every `Tiered` write fails with `ERR disk write failed`. - -In `Tiered` mode, for all features the module needs an open-file limit of at least `2 x maxclients + 128 + largeobj.max-cached-fds`. -With the defaults (`maxclients` 10000, `largeobj.max-cached-fds` 16384), this is 36512. -Raise the limit with `ulimit -n` or `LimitNOFILE`, or set a lower `maxclients`. -With the default `largeobj.fd-reserve` value `Lenient`, the module also loads with a lower limit: - -* Below `2 x maxclients + 128`, the file descriptor cache is off. - With the default `maxclients` 10000, the log shows, for example, `fd placement and the fd cache are off; set LimitNOFILE to at least 20128 to turn them on`. -* Between that value and the full value, the file descriptor cache is smaller. - With `maxclients` 1000 and an open-file limit of 10240, the log shows, for example, `the fd cache holds 8112; set LimitNOFILE to at least 18512 to cache all`. - -With `largeobj.fd-reserve` set to `Strict`, the module does not load if the full limit is not available. - -### Errors at run time - -| Error | Cause and fix | -|:------|:--------------| -| `OOM command not allowed when used memory > 'maxmemory'.` | The DRAM pool is full, and eviction cannot free space. Use `allkeys-lru` or `volatile-lru`, or raise `maxmemory`. | -| `OOM command not allowed when used disk space > 'largeobj.disk-maxmemory'.` | `Tiered` mode: the disk limit is reached, and eviction cannot free space. Use a policy that permits eviction, or raise `largeobj.disk-maxmemory`. | -| `ERR disk staging buffer pool exhausted; retry later` | `Tiered` mode: too many concurrent disk operations for the disk staging buffers, not a lack of DRAM for data. A retry later can succeed. Raise `largeobj.disk-staging-size`, lower `largeobj.max-buffers-per-op`, or send fewer concurrent operations. | -| `ERR max object size exceeded` | The object is larger than `largeobj.max-object-size`. | -| `ERR failed to set key` | Rare: the server could not store the key after the write. Retry. | -| `ERR Protocol error: invalid bulk length`, and the connection closes | A `BLOB.TCP_SET` value is larger than the core `proto-max-bulk-len` (default 512MB). Raise `proto-max-bulk-len`, or use `BLOB.RDMA_SET`. | -| `ERR no RDMA session (call BLOB.RDMA_HELLO first)` | The connection has no RDMA session, for example a new connection after a cluster redirect. Send `BLOB.RDMA_HELLO` on it. | -| `ERR RDMA read failed`, `ERR RDMA write failed` | The transfer to or from client memory failed, for example because the client endpoint is gone or a region is not registered. | -| `ERR disk write failed`, `ERR disk read failed` | `Tiered` mode: disk I/O failed. Look at the server log. If every write fails, `largeobj.disk-dir` does not support `O_DIRECT` or user extended attributes. | -| `ERR command not allowed in MULTI, scripts or module calls` | The data commands are blocking commands. See [Limitations](large-object.md#limitations). | -| `DISABLED largeobj module is disabled` | `largeobj.enabled` is `no`. | - -## Verify the module - -Use `MODULE LIST` to make sure that the module is loaded. -The module name is `largeobj`. - -``` -127.0.0.1:6379> MODULE LIST -1) 1) "name" - 2) "largeobj" - 3) "ver" - 4) (integer) 1 - ... -``` - -To see the module commands, filter by the module ACL category: - -``` -127.0.0.1:6379> COMMAND LIST FILTERBY ACLCAT largeobj -1) "BLOB.TCP_SET" -2) "BLOB.TCP_GET" -3) "BLOB.RDMA_SET" -4) "BLOB.RDMA_GET" -5) "BLOB.INFO" -6) "BLOB.RDMA_HELLO" -``` - -The order of the list can be different. -`ver` is the version number that the module registers: 1 for version 0.1.0. - -## First commands - -Store a value, read it, and get its metadata with `valkey-cli`: - -``` -127.0.0.1:6379> BLOB.TCP_SET greeting hello -OK -127.0.0.1:6379> BLOB.TCP_GET greeting -"hello" -127.0.0.1:6379> BLOB.INFO greeting -1) len -2) (integer) 5 -3) crc -4) (integer) 2591144780 -5) tier -6) dram -127.0.0.1:6379> BLOB.INFO greeting LEN -(integer) 5 -127.0.0.1:6379> BLOB.TCP_GET missing -(nil) -``` - -The `crc` value is the CRC32C checksum of the bytes `hello`. - -To store a file as an object, use the `-x` option of `valkey-cli`, which reads the last argument from standard input: - -```bash -valkey-cli -x BLOB.TCP_SET model:embeddings:v1 < embeddings.bin -``` - -Look at the module metrics: - -``` -127.0.0.1:6379> INFO largeobj -# largeobj_core_metrics -largeobj_num_objects:1 -largeobj_inflight_requests:0 - -# largeobj_evictions -largeobj_evictions:0 -largeobj_pending_evictions:0 -... -``` - -Delete the object with the core `DEL` command: - -``` -127.0.0.1:6379> DEL greeting -(integer) 1 -127.0.0.1:6379> BLOB.INFO greeting -(nil) -``` - -## Unload and clean up - -You cannot unload the module with `MODULE UNLOAD`, because it registers a data type. -To remove the module, stop the server and start it again without the module. - -All large objects are lost when the server stops (see [Persistence behavior](large-object.md#persistence-behavior)). -In `Tiered` mode, the module deletes `largeobj.disk-dir` at shutdown, or at the next startup after the server stops unexpectedly (see [Disk directory](large-object-configuration.md#disk-directory)). - -## Next steps - -* [Valkey Large Object - Use Cases and Examples](large-object-use-cases.md) -* [Valkey Large Object - RDMA Transfers](large-object-rdma.md) -* [Valkey Large Object - Configuration and Monitoring](large-object-configuration.md) -* [Large object command reference](../commands/#large-object) diff --git a/topics/large-object-rdma.md b/topics/large-object-rdma.md deleted file mode 100644 index d0ab33a7..00000000 --- a/topics/large-object-rdma.md +++ /dev/null @@ -1,201 +0,0 @@ ---- -title: "Valkey Large Object - RDMA Transfers" -description: How RDMA transfers work in the Valkey Large Object module ---- - -> **Note:** [valkey-large-object](https://github.com/valkey-io/valkey-large-object) is at version 0.x. -> Commands, arguments, replies, and configuration can change before version 1.0. - -The RDMA commands move object bytes between the server and client memory with [libfabric](https://ofiwg.github.io/libfabric/). -The value bytes do not go through the Valkey connection. -The Valkey connection carries only the command, the key, a list of memory regions, and a short reply. - -## Comparison with Valkey RDMA connections - -Valkey also has its own [RDMA support](RDMA.md), which is a connection type for the full RESP protocol. -The two features are different and independent. - -| | Valkey RDMA connection | Large object RDMA commands | -|:--|:--|:--| -| What RDMA carries | All commands and replies, in place of TCP | Only the object payload of `BLOB.RDMA_SET` and `BLOB.RDMA_GET` | -| Commands and replies | Over RDMA | Over the normal Valkey connection, usually TCP | -| How to turn it on | Load `valkey-rdma.so` with `bind` and `port` (see [RDMA support](RDMA.md)) | Load the module and set `largeobj.fabric-provider` | -| RDMA interface | RDMA verbs with reliable connection (RC) queue pairs | libfabric, with the `EfaDirect` or `Emulated` provider | -| Data movement | Each side writes the RESP byte stream into a receive buffer of the other side | The server does one-sided RDMA reads and writes between registered client memory and its DRAM segments | -| Session setup | RDMA connection setup and feature negotiation | `BLOB.RDMA_HELLO` one time on each Valkey connection | -| Payload checksum | Not part of the protocol | CRC32C of each object | -| Status | Experimental | Version 0.x; can change before version 1.0 | - -The module does not use the Valkey RDMA connection type. -The large object commands are not supported on a Valkey RDMA connection. - -## Roles - -The server is the RDMA initiator, and the client is passive during the transfer. - -* For [`BLOB.RDMA_GET`](../commands/blob.rdma_get.md), the server does RDMA writes (`fi_write`) into client memory. -* For [`BLOB.RDMA_SET`](../commands/blob.rdma_set.md), the server does RDMA reads (`fi_read`) from client memory. - -The client memory is memory that the client registers with its libfabric domain, usually host memory. -Client device memory, for example GPU memory (`FI_HMEM`), is not supported. - -Client requirements: - -* The libfabric provider of the client must support RMA (`FI_RMA`) with remote read and remote write, because the server reads from and writes into client memory. -* The client registers its buffers with `fi_mr_reg`, which counts against the locked-memory limit (`RLIMIT_MEMLOCK`) of the client process. - Set the client limit to at least the total size of its registered buffers, or to `unlimited`. - -The server registers only host memory. -When the module loads, it sets the libfabric environment variable `FI_HMEM` to `system`, unless `FI_HMEM` is already set. -Thus libfabric on the server does not start device memory interfaces, for example CUDA on a GPU host. - -## Session model - -An RDMA session belongs to one Valkey connection. -In cluster mode, a client that follows a `MOVED` or `ASK` redirect to another node must send `BLOB.RDMA_HELLO` on that connection first. -Else `BLOB.RDMA_SET` and `BLOB.RDMA_GET` fail with `ERR no RDMA session (call BLOB.RDMA_HELLO first)`. - -1. The client opens a libfabric endpoint and gets its endpoint address with `fi_getname`. -2. The client registers each buffer that it will use with `fi_mr_reg`. - Each registration gives a remote key (`rkey`). -3. The client sends [`BLOB.RDMA_HELLO`](../commands/blob.rdma_hello.md) with its endpoint address as a hexadecimal string, one time on the connection. -4. The server adds the client address to the address vector of each of its fabric services. - The reply is an array with one hexadecimal server address for each fabric service. -5. The client adds every returned server address to its own address vector with `fi_av_insert`. -6. The client sends `BLOB.RDMA_SET` and `BLOB.RDMA_GET` commands on the same connection. -7. The session ends when the connection closes. - -The session keeps only the address routing information. -It does not keep memory regions or remote keys. -The client sends the regions in each command, so it can use a different buffer for each request. - -A second `BLOB.RDMA_HELLO` on the same connection fails with `ERR RDMA session already established`. -To start a new session, open a new connection. - -The server does not check the session for a missing key. -Thus `BLOB.RDMA_GET` on a missing key returns nil also when the connection has no session. - -## HELLO handshake - -``` -BLOB.RDMA_HELLO client-rdma-address -``` - -* When `largeobj.fabric-provider` is `EfaDirect`, the decoded address must be exactly 32 bytes. -* When `largeobj.fabric-provider` is `Emulated`, the decoded address must be a socket address: 16 bytes for IPv4 (`sockaddr_in`) or 28 bytes for IPv6 (`sockaddr_in6`). - -``` -127.0.0.1:6379> BLOB.RDMA_HELLO -1) "" -2) "" -``` - -## Memory region triples - -`BLOB.RDMA_SET` and `BLOB.RDMA_GET` describe client memory as one or more triples: - -``` -rkey addr len [rkey addr len ...] -``` - -* `rkey` - the remote key from the client memory registration. -* `addr` - the address of the region in client memory. - This is a virtual address, or an offset in the registered buffer when the provider does not use virtual addresses (`FI_MR_VIRT_ADDR`). - `0` is a valid value. -* `len` - the length of the region in bytes. - `0` is not valid. - -All three values are unsigned decimal integers. -Hexadecimal and negative values are rejected. -The number of arguments after the fixed arguments must be a multiple of 3. -A command can have a maximum of 256 triples. - -The server fills or reads the regions in the order of the command. -A chunk of the object can continue from the end of one region into the next region. -Thus one object can span buffers on several devices, or several buffers on one device. - -## Length rules - -* The sum of all region lengths must be equal to or larger than the object length. - For `BLOB.RDMA_SET`, the object length is the `total-len` argument. - For `BLOB.RDMA_GET`, it is the length of the stored object. -* Surplus region space is permitted. - For `BLOB.RDMA_GET`, the reply gives the object length, which shows where the valid data ends. -* `total-len` must be larger than 0 and not larger than `largeobj.max-object-size`. - -## CRC behavior - -The server calculates a CRC32C (Castagnoli) checksum of the bytes of each stored object. - -* `BLOB.RDMA_SET` can include `CRC ` directly after `total-len`. - The keyword is not case-sensitive, and the value is an unsigned 32-bit decimal integer. - The server calculates the checksum of the bytes that it read. - If the two values are different, the command fails with `ERR CRC mismatch after transfer` and the server does not store the object. -* `BLOB.RDMA_GET` replies with a two-element array, `[obj_len, crc32c]`, after all RDMA writes are complete. - To make sure that the data is correct end to end, calculate the CRC32C of the first `obj_len` bytes in your regions and compare it with the reply. -* [`BLOB.INFO`](../commands/blob.info.md) returns the stored checksum with the `CRC` field. - -The `largeobj.fabric-crc-pool-threads` configuration sets the number of server threads that calculate checksums of the data that `BLOB.RDMA_SET` transfers. - -## Providers - -The `largeobj.fabric-provider` configuration selects the libfabric provider when the module loads. - -| Provider | Use | Address | -|:---------|:----|:--------| -| `EfaDirect` (default) | [Elastic Fabric Adapter (EFA)](https://aws.amazon.com/hpc/efa/) hardware RDMA | 32 bytes | -| `Emulated` | libfabric over TCP sockets, for development and tests only | 16 or 28 bytes (socket address) | - -Use `Emulated` to develop and test RDMA client code (the `BLOB.RDMA_*` flow) on a host without RDMA hardware. -It runs libfabric over TCP sockets, so it is not for production and it is not faster than `BLOB.TCP_SET` and `BLOB.TCP_GET`. -In production on hosts without RDMA hardware, use the TCP commands. -For a test on one host, you can also set `largeobj.fabric-interfaces` to `lo` to serve only on the loopback interface. - -If the provider does not start, the module loads and only the TCP commands are available. -`BLOB.RDMA_HELLO` then fails with `ERR RDMA provider unavailable on this instance`. - -## Multiple fabric interfaces - -A host can have more than one fabric interface (domain). -By default, the module starts one fabric service on each domain that the provider finds. -To use only some domains, set `largeobj.fabric-interfaces` to a comma-separated list of domain names. - -The `BLOB.RDMA_HELLO` reply has one server address for each fabric service. -The client must add all of them, because the server can send a transfer from any of its fabric services. -For each transfer, the server picks two fabric services at random and uses the one with fewer transfers in progress. - -At startup, the server log shows each service address as `largeobj: fabric service rdma address `. - -All DRAM pool segments, and in `Tiered` mode all disk staging segments, are registered with the fabric when the module starts and when the pool expands. -The `largeobj.max-rdma-registered-bytes` configuration (default 380GB) limits the total size of registered segments, so that the pool stays below the registration limit of the device. -The pool does not expand above this limit. -The `dram_rdma_registered_segments` field in `INFO largeobj` shows the number of registered DRAM pool segments. - -## Cancel and timeout - -If the server cannot post a transfer for 1 second (for example, because the client endpoint is gone), the command fails with `ERR RDMA read failed` or `ERR RDMA write failed`. -There is no other server-side timeout or abort for a transfer. -To stop a transfer, close the connection. -The client must keep its registered regions valid until it receives the reply. - -## Errors - -These are the RDMA errors that you are most likely to see. -For the full list, see the [module repository](https://github.com/valkey-io/valkey-large-object). - -| Error | Cause | -|:------|:------| -| `ERR RDMA provider unavailable on this instance` | The fabric did not start. | -| `ERR rdma address must be 32 bytes`, `ERR rdma address is not a valid sockaddr` | The `BLOB.RDMA_HELLO` address does not agree with the fabric provider. | -| `ERR RDMA session already established` | A second `BLOB.RDMA_HELLO` on the same connection. | -| `ERR no RDMA session (call BLOB.RDMA_HELLO first)` | `BLOB.RDMA_SET` or `BLOB.RDMA_GET` without a session. | -| `ERR memory address args must be rkey, addr, len triples` | The region arguments are not a multiple of 3. | -| `ERR client memory address length smaller than object length ` | The regions are too small for the object. | -| `ERR max object size exceeded` | `total-len` is larger than `largeobj.max-object-size`. | -| `ERR CRC mismatch after transfer` | The checksum of the transferred bytes is not equal to the `CRC` value. Nothing is stored. | -| `ERR RDMA read failed`, `ERR RDMA write failed` | An RDMA transfer from or into client memory failed. | - -Both commands return `WRONGTYPE` when the key holds a different data type. -`BLOB.RDMA_SET` can also return the same storage errors as [`BLOB.TCP_SET`](../commands/blob.tcp_set.md), for example the `OOM` errors. - -For the RDMA fields in `INFO largeobj`, see [What to watch](large-object-configuration.md#what-to-watch) and [`rdma`](large-object-configuration.md#rdma). diff --git a/topics/large-object-use-cases.md b/topics/large-object-use-cases.md deleted file mode 100644 index f887be42..00000000 --- a/topics/large-object-use-cases.md +++ /dev/null @@ -1,144 +0,0 @@ ---- -title: "Valkey Large Object - Use Cases and Examples" -description: Common use cases and worked examples for the Valkey Large Object module ---- - -> **Note:** [valkey-large-object](https://github.com/valkey-io/valkey-large-object) is at version 0.x. -> Commands, arguments, replies, and configuration can change before version 1.0. - -This page shows common patterns for the large object module. -The TCP examples use `valkey-cli`. -The RDMA examples show the flow of an RDMA-capable client, because `valkey-cli` cannot do RDMA transfers. -See [Valkey Large Object - RDMA Transfers](large-object-rdma.md) for the details of each RDMA step. - -## Common use cases - -### Offload and share an LLM inference KV cache - -Large language model (LLM) inference engines calculate attention key/value tensors (the KV cache) for each prompt prefix. -When GPU memory is full, the engine discards blocks of this cache, and it must calculate them again when a similar prompt comes. -A cache connector in the inference engine can store the blocks in Valkey instead. -Other GPU servers that connect to the same Valkey nodes can then use the blocks again. - -A common key pattern is a hash of the token prefix and the model identity, for example `kv:::`. -With RDMA, the server writes each block directly into a registered host buffer of the inference engine. -GPU memory (`FI_HMEM`) is not supported as a client buffer. -To read more blocks in parallel, a client can send requests for different keys to many Valkey nodes at the same time. - -### Stage model weights, embeddings, and artifacts - -Many workers can need the same large artifact at the same time, for example model weight shards, embedding tables, or tokenizer files. -Load each shard into Valkey one time, and let the workers read it from Valkey. -Use `Tiered` mode when the total size of the artifacts is larger than the DRAM that you want to use. -Frequently read objects are then served from the DRAM cache. - -### Large blob cache in front of object storage - -Applications can put a cache in front of an object store for large immutable blobs, for example images, media segments, or data set files. -On a miss, the application reads the blob from the object store and writes it to Valkey with a TTL. -Later reads come from Valkey. -The module does not persist objects, so the object store stays the source of truth. - -## Example: store and read a blob over TCP - -Store a file, look at its metadata, and read it again: - -```bash -valkey-cli -x BLOB.TCP_SET artifact:tokenizer:v3 < tokenizer.json -valkey-cli BLOB.INFO artifact:tokenizer:v3 -``` - -Use the cache-aside pattern with a TTL. -In this example, the value `123456789` represents the bytes from the object store: - -``` -127.0.0.1:6379> BLOB.TCP_GET blob:images:4711 -(nil) -127.0.0.1:6379> BLOB.TCP_SET blob:images:4711 123456789 -OK -127.0.0.1:6379> EXPIRE blob:images:4711 3600 -(integer) 1 -127.0.0.1:6379> BLOB.INFO blob:images:4711 LEN -(integer) 9 -127.0.0.1:6379> TTL blob:images:4711 -(integer) 3600 -``` - -To make sure that a blob did not change, compare the CRC32C that your application calculates with the stored value: - -``` -127.0.0.1:6379> BLOB.INFO blob:images:4711 CRC -(integer) 3808858755 -``` - -In `Tiered` mode, `BLOB.INFO` shows where the object is now: - -``` -127.0.0.1:6379> BLOB.INFO artifact:tokenizer:v3 TIER -disk -127.0.0.1:6379> BLOB.TCP_GET artifact:tokenizer:v3 -"..." -127.0.0.1:6379> BLOB.INFO artifact:tokenizer:v3 TIER -dram -``` - -With the default `largeobj.promote-min-hits` (1), the first read promotes the object into the DRAM cache. -After the promotion is complete, `TIER` shows `dram`. -Objects larger than `largeobj.max-promote-size` stay on disk. - -## Example: KV cache blocks over RDMA - -This pseudo-flow shows how a cache connector can store and load KV cache blocks with RDMA. -`fi_*` are libfabric calls in the client. -`valkey.call` sends a Valkey command on one connection. - -``` -# One time for each Valkey connection -ep = fi_endpoint(...) -my_addr = fi_getname(ep) -servers = valkey.call("BLOB.RDMA_HELLO", hex(my_addr)) -for s in servers: - fi_av_insert(unhex(s)) - -# One time for each buffer (registration is expensive, so do it at startup) -# Host memory only: GPU memory (FI_HMEM) is not supported -mr = fi_mr_reg(buffer, buffer_size) -rkey = fi_mr_key(mr) - -# Save one block (the block is in buffer at offset off, size n) -crc = crc32c(buffer[off : off + n]) -valkey.call("BLOB.RDMA_SET", key, n, "CRC", crc, rkey, addr(buffer) + off, n) -# Reply "OK": the server has read all bytes and stored the object - -# Load one block into buffer at offset off -reply = valkey.call("BLOB.RDMA_GET", key, rkey, addr(buffer) + off, n) -if reply is nil: - # Cache miss: calculate the block again -else: - obj_len, crc = reply - # Optional end-to-end check - assert crc32c(buffer[off : off + obj_len]) == crc -``` - -One block can span several buffers. -Send one triple for each buffer, in the order of the bytes: - -``` -BLOB.RDMA_GET kv:m1:9f2c:layers-0-15 1001 140230000000000 4194304 1002 140230100000000 4194304 -``` - -The total length of the regions must be equal to or larger than the object. -If the reply is `[6291456, ]`, the first 4MB are in the first buffer and the remaining 2MB are at the start of the second buffer. - -## Tips - -* Send `BLOB.RDMA_HELLO` one time on each connection, and keep the connection open. - A connection pool with a session on each connection prevents a handshake on each request. -* Register buffers one time and use them again. - Memory registration is expensive. -* To send many large object commands together, use a [pipeline](pipelining.md). - The data commands are not permitted in transactions or scripts (see [Limitations](large-object.md#limitations)). -* Keep each object at or below `largeobj.max-object-size`. - Split larger data into more keys, for example one key for each layer range or each shard. -* Do not use large objects as the only copy of data. - The module has no persistence and no replication. diff --git a/topics/large-object.md b/topics/large-object.md deleted file mode 100644 index f1546597..00000000 --- a/topics/large-object.md +++ /dev/null @@ -1,181 +0,0 @@ ---- -title: "Valkey Large Object - Overview" -description: Valkey Large Object Module Overview ---- - -> **Note:** [valkey-large-object](https://github.com/valkey-io/valkey-large-object) is at version 0.x. -> Commands, arguments, replies, and configuration can change before version 1.0. - -The [valkey-large-object](https://github.com/valkey-io/valkey-large-object) module (BSD-3-Clause) adds a data type and commands to store large binary values in Valkey. -Typical values are blocks of a machine learning KV cache, tensors, embeddings, and other blobs that are megabytes or larger in size. -The module keeps objects in DRAM, or in a tiered layout where NVMe holds each object and DRAM is a read cache. -Clients can transfer values over the normal Valkey connection (TCP), or over RDMA with [libfabric](https://ofiwg.github.io/libfabric/). -With RDMA, the server writes object bytes directly into client memory and reads them directly from client memory, for example with an Elastic Fabric Adapter (EFA) (see [Providers](large-object-rdma.md#providers)). - -The module registers with the name `largeobj`. -Its value type is `largeob-k`. - -## Key concepts - -### Operating modes - -The `largeobj.operating-mode` configuration selects one of two modes when the module loads. - -* `Dram` (default) - All objects are in a DRAM pool. - The pool is a set of pre-allocated segments. - The mode does no disk I/O. -* `Tiered` - The module writes each object to a file on NVMe in `largeobj.disk-dir`. - DRAM is a read cache. - By default, the first read of an object promotes it into DRAM (see `largeobj.promote-min-hits` and `largeobj.max-promote-size`). - When the cache is full, the module drops cached copies with the lowest LFU score. - The module uses io_uring with `O_DIRECT` for disk I/O. - -### Segments and maximum object size - -The module allocates memory in fixed-size segments (`largeobj.segment-size`, from 1MB to 1GB). -In `Dram` mode, an object must fit in a single segment. -Thus an object of `largeobj.max-object-size` bytes, plus a small overhead for each chunk, must fit in one segment, and the largest object in `Dram` mode is less than 1GB. -The module also divides objects into chunks (`largeobj.chunk-size`) for streaming I/O. -Each chunk adds a small allocation overhead in the segment. -Each pool has at most 16384 segments, so the DRAM pool does not grow past 16384 x `largeobj.segment-size` (1TB with 64MB segments), also when `maxmemory` is larger. - -The default `largeobj.max-object-size` is 512MB. -The smallest object is 1 byte. -See [Cross-configuration rules](large-object-configuration.md#cross-configuration-rules) for the rules that relate these values. - -### Transports - -* TCP - [`BLOB.TCP_SET`](../commands/blob.tcp_set.md) and [`BLOB.TCP_GET`](../commands/blob.tcp_get.md) send the value in the RESP command and reply. - These commands are always available and work with any Valkey client. -* RDMA - [`BLOB.RDMA_SET`](../commands/blob.rdma_set.md) and [`BLOB.RDMA_GET`](../commands/blob.rdma_get.md) send only the key and a list of client memory regions. - The server reads or writes the value bytes with libfabric. - The client must first open a session with [`BLOB.RDMA_HELLO`](../commands/blob.rdma_hello.md). - -If the fabric does not start, the module still loads, and only the TCP commands are available. -See [Valkey Large Object - RDMA Transfers](large-object-rdma.md) for the full RDMA model. - -### CRC32C checksum - -The server calculates a CRC32C (Castagnoli) checksum of each object when it stores the object. -[`BLOB.INFO`](../commands/blob.info.md) and [`BLOB.RDMA_GET`](../commands/blob.rdma_get.md) return this value. -On [`BLOB.RDMA_SET`](../commands/blob.rdma_set.md), a client can send its own CRC32C value. -The server then rejects the write if the checksum of the transferred bytes is different. - -## Supported commands - -* [`BLOB.TCP_SET`](../commands/blob.tcp_set.md) - stores an object that is sent in the command. -* [`BLOB.TCP_GET`](../commands/blob.tcp_get.md) - returns an object as a bulk string. -* [`BLOB.RDMA_HELLO`](../commands/blob.rdma_hello.md) - opens an RDMA session on the connection. -* [`BLOB.RDMA_SET`](../commands/blob.rdma_set.md) - stores an object that the server reads from client memory. -* [`BLOB.RDMA_GET`](../commands/blob.rdma_get.md) - writes an object into client memory. -* [`BLOB.INFO`](../commands/blob.info.md) - returns the length, CRC32C, and storage tier of an object. - -See the [complete list of large object commands](../commands/#large-object). - -Core commands also operate on large object keys. -`DEL`, `UNLINK`, overwrite, expiry, and eviction free the object storage in the background. -See [Core commands on large object keys](#core-commands-on-large-object-keys). -`MEMORY USAGE` counts the payload only when the payload is in DRAM. - -When `notify-keyspace-events` includes module key type events (`d`), the module sends `largeobj.create` when a write creates a key and `largeobj.update` when a write replaces a value. - -## Limitations - -The current version has these limitations: - -* No persistence. - The module does not save object data to RDB or AOF. - Objects do not survive a server restart. - In `Tiered` mode, the module deletes `largeobj.disk-dir` at startup and shutdown (see [Disk directory](large-object-configuration.md#disk-directory)). - See [Persistence behavior](#persistence-behavior). -* No replication. - Replicas are not supported for large object data. - See [Replication](#replication). -* In cluster mode, slots that have large object keys cannot move. - See [Cluster mode](#cluster-mode). -* `BLOB.TCP_SET`, `BLOB.TCP_GET`, `BLOB.RDMA_SET`, and `BLOB.RDMA_GET` are blocking commands, so they cannot run in transactions, scripts, functions, or module calls. -* The module cannot be unloaded with `MODULE UNLOAD`. - Restart the server to remove it. - To stop users from using the module without a restart, use ACLs, for example `ACL SETUSER -@largeobj` (see [ACL](large-object-configuration.md#acl)). -* Active defragmentation is not implemented for large object memory. -* RDMA transfers have no server-side timeout other than a 1-second limit to post a transfer (see [Cancel and timeout](large-object-rdma.md#cancel-and-timeout)). - -### Persistence behavior - -These operations work while large object keys exist, but they do not keep the object data: - -* `SAVE`, `BGSAVE`, `SHUTDOWN` with save points, and the automatic RDB snapshots save the key names without the object data. -* `BGREWRITEAOF` keeps no object data. - With `aof-use-rdb-preamble yes` (the default), the rewritten AOF has the key names, as with `SAVE`. - With `aof-use-rdb-preamble no`, it has no large object keys. -* When the server loads an RDB file (at startup, with `DEBUG RELOAD`, or on a replica full synchronization), each large object key reads as missing. - The module starts to delete these keys within `largeobj.scaling-poll-ms` (default 2.5 seconds) after the load. - With many keys, this can take longer. - Until then, `EXISTS` and `DBSIZE` still count them. - For example, `EXISTS` still returns `1` directly after a `BLOB.TCP_GET` of the key returns nil, and returns `0` a few seconds later. -* `DUMP` returns a value without the object data. - `RESTORE` of that value fails with `ERR Bad data format`, so `MIGRATE` fails (see [Cluster mode](#cluster-mode)). - -The server log shows a warning, for example `largeobj: persistence is not supported: blobs are saved to RDB/DUMP without their data`, the first time that each case occurs. - -### Replication - -The module does not replicate large objects: - -* A large object write on the primary is not sent to the replica. - The replica does not have the key. -* At a full synchronization, the replica loads the large object keys without their data. - They read as missing, and the replica deletes them a few seconds later, as after an RDB load. -* In that time, a `COPY` from the primary of such a key fails on the replica. - The replica log then shows `This replica is sending an error to its primary: 'module key failed to copy'`. -* If a replica becomes the primary, it has no large objects. - -### Cluster mode - -The module loads on each node of a cluster. -Each command uses a single key (or no key for `BLOB.RDMA_HELLO`), so cluster clients can route commands by slot. - -* An RDMA session belongs to one connection to one node. - Send `BLOB.RDMA_HELLO` on each connection to each node, and add the server addresses of each node to the address vector. - Each node replies with its own server addresses. -* You cannot move a slot that has large object keys. - `MIGRATE` uses `DUMP` and `RESTORE`, which do not keep object data. - The key stays on the source node: - - ``` - 127.0.0.1:7395> MIGRATE 127.0.0.1 7394 foo 0 5000 - (error) ERR Target instance replied with error: ERR Bad data format - ``` - - Atomic slot migration (`CLUSTER MIGRATESLOTS`) is refused with `ERR The module largeobj does not support atomic slot migrations. Please ensure all modules have declared support for atomic slot migration and try again`. -* To add capacity, raise `maxmemory` (`Dram` mode) or `largeobj.disk-maxmemory` (`Tiered` mode) on the nodes, if the hosts have the memory or disk. - Both are mutable with `CONFIG SET`. - Else move a slot to a new node only when the slot has no large object keys: delete the large object keys in the slot first (or let them expire), move the slot, and then write the objects again. - Or make a new, larger cluster and write the objects to it. -* After a `MOVED` or `ASK` redirect, the client sends the command on a connection to the other node. - If that connection has no RDMA session, `BLOB.RDMA_SET` and `BLOB.RDMA_GET` fail with `ERR no RDMA session (call BLOB.RDMA_HELLO first)`. - Send `BLOB.RDMA_HELLO` on that connection first. - -### Core commands on large object keys - -These results are the same in `Dram` and `Tiered` mode. - -| Command | Result | -|:--------|:-------| -| `COPY` | Works. The copy has its own data. | -| `RENAME`, `RENAMENX` | Work. | -| `MOVE`, `SWAPDB` | Work. | -| `EXPIRE`, `PEXPIRE`, `TTL`, `PERSIST` | Work. | -| `TYPE` | Returns `largeob-k`. | -| `OBJECT ENCODING` | Returns `raw`. | -| `DUMP` | Returns a value without the object data. | -| `RESTORE` | Fails with `ERR Bad data format`. | -| `DEL`, `UNLINK` | Work. The module frees the storage in the background. | -| `FLUSHALL`, `FLUSHALL ASYNC` | Work. | - -## Topics - -* [Valkey Large Object - Getting Started](large-object-getting-started.md) - build the module, load it, and run your first commands. -* [Valkey Large Object - Use Cases and Examples](large-object-use-cases.md) - common patterns with worked examples. -* [Valkey Large Object - RDMA Transfers](large-object-rdma.md) - sessions, memory regions, checksums, and errors. -* [Valkey Large Object - Configuration and Monitoring](large-object-configuration.md) - configuration parameters, ACL, and `INFO` fields. diff --git a/topics/latency-monitor.md b/topics/latency-monitor.md deleted file mode 100644 index d8ec1cf9..00000000 --- a/topics/latency-monitor.md +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: "Latency monitoring" -description: Discovering slow server events in Valkey ---- - -Valkey is often used for demanding use cases, where it -serves a large number of queries per second per instance, but also has strict latency requirements for the average response -time and the worst-case latency. - -While Valkey is an in-memory system, it deals with the operating system in -different ways, for example, in the context of persisting to disk. -Moreover, Valkey implements a rich set of commands. Certain commands -are fast and run in constant or logarithmic time. Other commands have -`O(N)` complexity and can cause latency spikes. - -Finally, Valkey is *mostly* single-threaded. This is usually an advantage -from the point of view of the amount of work it can perform per core, and in -the latency figures it is able to provide. However, it poses -a challenge for latency, since the single thread -must be able to perform certain tasks incrementally, for -example key expiration, in a way that does not impact the other clients -that are served. -Some other operations, such as reading, parsing, polling, and writing to the socket, can be offloaded to a configurable pool of I/O threads, but command execution itself still happens on the main thread. - -For all these reasons, there is a feature called -**Latency Monitoring**, that helps the user to check and troubleshoot possible -latency problems. Latency monitoring is composed of the following conceptual -parts: - -* Latency hooks that sample different latency-sensitive code paths. -* Time series recording of latency spikes, split by different events. -* Reporting engine to fetch raw data from the time series. -* Analysis engine to provide human-readable reports and hints according to the measurements. - -The rest of this document covers the latency monitoring subsystem -details. For more information about the general topic of Valkey -and latency, see [Valkey latency problems troubleshooting](latency.md). - -## Events and time series - -Different monitored code paths have different names and are called *events*. -For example, `command` is an event that measures latency spikes of possibly slow -command executions, while `fast-command` is the event name for the monitoring -of the O(1) and O(log N) commands. Other events are less generic and monitor -specific operations performed by Valkey. For example, the `fork` event -only monitors the time taken by Valkey to execute the `fork(2)` system call. - -A latency spike is an event that takes more time to run than the configured latency -threshold. There is a separate time series associated with every monitored -event. This is how the time series work: - -* Every time a latency spike happens, it is logged in the appropriate time series. -* Every time series is composed of 160 elements. -* Each element is a pair made of a Unix timestamp of the time the latency spike was measured and the number of milliseconds the event took to execute. -* Latency spikes for the same event that occur in the same second are merged by taking the maximum latency. Even if continuous latency spikes are measured for a given event, which could happen with a low threshold, at least 160 seconds of history are available. -* Records the all-time maximum latency for every element. - -The framework monitors and logs latency spikes in the execution time of these events: - -* `command`: regular commands. -* `fast-command`: O(1) and O(log N) commands. -* `fork`: the `fork(2)` system call. -* `rdb-unlink-temp-file`: the `unlink(2)` system call. -* `aof-fsync-always`: the `fsync(2)` system call when invoked by the `appendfsync always` policy. -* `aof-write`: writing to the AOF - a catchall event for `write(2)` system calls. -* `aof-write-pending-fsync`: the `write(2)` system call when there is a pending fsync. -* `aof-write-active-child`: the `write(2)` system call when there are active child processes. -* `aof-write-alone`: the `write(2)` system call when no pending fsync and no active child process. -* `aof-fstat`: the `fstat(2)` system call. -* `aof-rename`: the `rename(2)` system call for renaming the temporary file after completing `BGREWRITEAOF`. -* `aof-rewrite-diff-write`: writing the differences accumulated while performing `BGREWRITEAOF`. -* `active-defrag-cycle`: the active defragmentation cycle. -* `expire-cycle`: the expiration cycle. -* `eviction-cycle`: the eviction cycle. -* `eviction-del`: deletes during the eviction cycle. - -## How to enable latency monitoring - -The acceptable latency depends on the application. -Some applications require all queries to complete within 1 millisecond. Other applications may tolerate occasional latency of 2 seconds for a small number of clients. - -Set a **latency threshold** in milliseconds to enable latency monitoring. -The default threshold is `0`, which disables latency monitoring. - -Valkey logs events that exceed the configured threshold as latency spikes. -Set the threshold according to the application's latency requirements. - -For example, if the application requires a maximum latency of 100 milliseconds, set the threshold to 100: - -``` -CONFIG SET latency-monitor-threshold 100 -``` - - -Latency monitoring is disabled by default. -Latency monitoring requires very little memory. However, enabling it increases the baseline memory usage of a Valkey instance. - -## Report information with the LATENCY command - -The user interface to the latency monitoring subsystem is the [`LATENCY`](../commands/latency.md) command. -Like many other Valkey commands, `LATENCY` accepts subcommands that modify its behavior. -These subcommands are: - -* [`LATENCY LATEST`](../commands/latency-latest.md) - returns the latest latency samples for all events. -* [`LATENCY HELP`](../commands/latency-help.md) - returns helpful text about the different subcommands. -* [`LATENCY HISTORY`](../commands/latency-history.md) - returns timestamp-latency samples for an event. -* [`LATENCY HISTOGRAM`](../commands/latency-histogram.md) - returns the cumulative distribution of latencies of a subset or all commands. -* [`LATENCY RESET`](../commands/latency-reset.md) - resets the latency data for one or more events. -* [`LATENCY GRAPH`](../commands/latency-graph.md) - returns a latency graph for an event. -* [`LATENCY DOCTOR`](../commands/latency-doctor.md) - returns a human-readable latency analysis report. - -Refer to each subcommand's documentation page for further information. diff --git a/topics/latency.md b/topics/latency.md deleted file mode 100644 index 158eb45d..00000000 --- a/topics/latency.md +++ /dev/null @@ -1,604 +0,0 @@ ---- -title: "Diagnosing latency issues" -description: Finding the causes of slow responses ---- - -This document will help you understand what the problem could be if you -are experiencing latency problems with Valkey. - -In this context *latency* is the maximum delay between the time a client -issues a command and the time the reply to the command is received by the -client. Usually Valkey processing time is extremely low, in the sub microsecond -range, but there are certain conditions leading to higher latency figures. - -I've little time, give me the checklist ---- - -The following documentation is very important in order to run Valkey in -a low latency fashion. However I understand that we are busy people, so -let's start with a quick checklist. If you fail following these steps, please -return here to read the full documentation. - -1. Make sure you are not running slow commands that are blocking the server. Use the Valkey [Slow Log feature](../commands/slowlog.md) to check this. -2. For EC2 users, make sure you use HVM based modern EC2 instances, like m3.medium. Otherwise fork() is too slow. -3. Transparent huge pages must be disabled from your kernel. Use `echo never > /sys/kernel/mm/transparent_hugepage/enabled` to disable them, and restart your Valkey process. -4. If you are using a virtual machine, it is possible that you have an intrinsic latency that has nothing to do with Valkey. Check the minimum latency you can expect from your runtime environment using `./valkey-cli --intrinsic-latency 100`. Note: you need to run this command in *the server* not in the client. -5. Enable and use the [Latency monitor](latency-monitor.md) feature of Valkey in order to get a human readable description of the latency events and causes in your Valkey instance. - -In general, use the following table for durability VS latency/performance tradeoffs, ordered from stronger safety to better latency. - -1. AOF + fsync always: this is very slow, you should use it only if you know what you are doing. -2. AOF + fsync every second: this is a good compromise. -3. AOF + fsync every second + no-appendfsync-on-rewrite option set to yes: this is as the above, but avoids to fsync during rewrites to lower the disk pressure. -4. AOF + fsync never. Fsyncing is up to the kernel in this setup, even less disk pressure and risk of latency spikes. -5. RDB. Here you have a vast spectrum of tradeoffs depending on the save triggers you configure. - -And now for people with 15 minutes to spend, the details... - -Measuring latency ------------------ - -If you are experiencing latency problems, you probably know how to measure -it in the context of your application, or maybe your latency problem is very -evident even macroscopically. However valkey-cli can be used to measure the -latency of a Valkey server in milliseconds, just try: - - valkey-cli --latency -h `host` -p `port` - -Using the internal Valkey latency monitoring subsystem ---- - -Valkey provides latency monitoring capabilities that -are able to sample different execution paths to understand where the -server is blocking. This makes debugging of the problems illustrated in -this documentation much simpler, so we suggest enabling latency monitoring -ASAP. Please refer to the [Latency monitor documentation](latency-monitor.md). - -While the latency monitoring sampling and reporting capabilities will make -it simpler to understand the source of latency in your Valkey system, it is still -advised that you read this documentation extensively to better understand -the topic of Valkey and latency spikes. - -Latency baseline ----------------- - -There is a kind of latency that is inherently part of the environment where -you run Valkey, that is the latency provided by your operating system kernel -and, if you are using virtualization, by the hypervisor you are using. - -While this latency can't be removed it is important to study it because -it is the baseline, or in other words, you won't be able to achieve a Valkey -latency that is better than the latency that every process running in your -environment will experience because of the kernel or hypervisor implementation -or setup. - -We call this kind of latency **intrinsic latency**, and `valkey-cli` -is able to measure it. This is an example run. - -Note: the argument `100` is the number of seconds the test will be executed. -The more time we run the test, the more likely we'll be able to spot -latency spikes. 100 seconds is usually appropriate, however you may want -to perform a few runs at different times. Please note that the test is CPU -intensive and will likely saturate a single core in your system. - - $ ./valkey-cli --intrinsic-latency 100 - Max latency so far: 1 microseconds. - Max latency so far: 16 microseconds. - Max latency so far: 50 microseconds. - Max latency so far: 53 microseconds. - Max latency so far: 83 microseconds. - Max latency so far: 115 microseconds. - -Note: valkey-cli in this special case needs to **run in the server** where you run or plan to run Valkey, not in the client. In this special mode valkey-cli does not connect to a Valkey server at all: it will just try to measure the largest time the kernel does not provide CPU time to run to the valkey-cli process itself. - -In the above example, the intrinsic latency of the system is just 0.115 -milliseconds (or 115 microseconds), which is a good news, however keep in mind -that the intrinsic latency may change over time depending on the load of the -system. - -In a virtualized environments with high load or if there are noisy neighbors, -you may get numbers like these: - - $ ./valkey-cli --intrinsic-latency 100 - Max latency so far: 573 microseconds. - Max latency so far: 695 microseconds. - Max latency so far: 919 microseconds. - Max latency so far: 1606 microseconds. - Max latency so far: 3191 microseconds. - Max latency so far: 9243 microseconds. - Max latency so far: 9671 microseconds. - -Here we have an intrinsic latency of 9.7 milliseconds: this means that we can't ask better than that to Valkey. However other runs at different times in different virtualization environments with higher load or with noisy neighbors can easily show even worse values. We were able to measure up to 40 milliseconds in -systems otherwise apparently running normally. - -Latency induced by network and communication --------------------------------------------- - -Clients connect to Valkey using a TCP/IP connection or a Unix domain connection. -The typical latency of a 1 Gbit/s network is about 200 us, while the latency -with a Unix domain socket can be as low as 30 us. It actually depends on your -network and system hardware. On top of the communication itself, the system -adds some more latency (due to thread scheduling, CPU caches, NUMA placement, -etc ...). System induced latencies are significantly higher on a virtualized -environment than on a physical machine. - -The consequence is even if Valkey processes most commands in sub microsecond -range, a client performing many roundtrips to the server will have to pay -for these network and system related latencies. - -An efficient client will therefore try to limit the number of roundtrips by -pipelining several commands together. This is fully supported by the servers -and most clients. Aggregated commands like MSET/MGET can be also used for -that purpose. A number of commands also support -variadic parameters for all data types. - -Here are some guidelines: - -+ If you can afford it, prefer a physical machine over a VM to host the server. -+ Do not systematically connect/disconnect to the server (especially true - for web based applications). Keep your connections as long lived as possible. -+ If your client is on the same host than the server, use Unix domain sockets. -+ Prefer to use aggregated commands (MSET/MGET), or commands with variadic - parameters (if possible) over pipelining. -+ Prefer to use pipelining (if possible) over sequence of roundtrips. -+ Valkey supports Lua server-side scripting to cover cases that are not suitable - for raw pipelining (for instance when the result of a command is an input for - the following commands). - -On Linux, some people can achieve better latencies by playing with process -placement (taskset), cgroups, real-time priorities (chrt), NUMA -configuration (numactl), or by using a low-latency kernel. Please note -vanilla Valkey is not really suitable to be bound on a **single** CPU core. -Valkey can fork background tasks that can be extremely CPU consuming -like `BGSAVE` or `BGREWRITEAOF`. These tasks must **never** run on the same core -as the main event loop. - -In most situations, these kind of system level optimizations are not needed. -Only do them if you require them, and if you are familiar with them. - -Valkey sequential command execution -------------------------------- - -Valkey uses a *mostly* single threaded design for command execution. This means that a single process -executes all the client commands sequentially, using a technique called **multiplexing**. -While multiple commands can have their I/O operations processed concurrently in the background, -only one command can be executed at any given moment. This is similar to how Node.js -works as well. However, both products are not often perceived as being slow. -This is caused in part by the small amount of time to complete a single command execution, -but primarily because these products are designed to not block on system calls, -such as reading data from or writing data to a socket. - - -Latency generated by slow commands ----------------------------------- - -A consequence of being single thread is that when a request is slow to serve -all the other clients will wait for this request to be served. When executing -normal commands, like `GET` or `SET` or `LPUSH` this is not a problem -at all since these commands are executed in constant (and very small) time. -However there are commands operating on many elements, like `SORT`, `LREM`, -`SUNION` and others. For instance taking the intersection of two big sets -can take a considerable amount of time. - -The algorithmic complexity of all commands is documented. A good practice -is to systematically check it when using commands you are not familiar with. - -If you have latency concerns you should either not use slow commands against -values composed of many elements, or you should run a replica using Valkey -replication where you run all your slow queries. - -It is possible to monitor slow commands using the Valkey -[Slow Log feature](../commands/slowlog.md). - -Additionally, you can use your favorite per-process monitoring program -(top, htop, prstat, etc ...) to quickly check the CPU consumption of the -main Valkey process. If it is high while the traffic is not, it is usually -a sign that slow commands are used. - -**IMPORTANT NOTE**: a VERY common source of latency generated by the execution -of slow commands is the use of the `KEYS` command in production environments. -`KEYS`, as documented in the Valkey documentation, should only be used for -debugging purposes. To -iterate the key space and other large collections incrementally, please check -the `SCAN`, `SSCAN`, `HSCAN` and `ZSCAN` commands for more information. - -Latency generated by fork -------------------------- - -In order to generate the RDB file in background, or to rewrite the Append Only File if AOF persistence is enabled, Valkey has to fork background processes. -The fork operation (running in the main thread) can induce latency by itself. - -Forking is an expensive operation on most Unix-like systems, since it involves -copying a good number of objects linked to the process. This is especially -true for the page table associated to the virtual memory mechanism. - -For instance on a Linux/AMD64 system, the memory is divided in 4 kB pages. -To convert virtual addresses to physical addresses, each process stores -a page table (actually represented as a tree) containing at least a pointer -per page of the address space of the process. So a large 24 GB Valkey instance -requires a page table of 24 GB / 4 kB * 8 = 48 MB. - -When a background save is performed, this instance will have to be forked, -which will involve allocating and copying 48 MB of memory. It takes time -and CPU, especially on virtual machines where allocation and initialization -of a large memory chunk can be expensive. - -Fork time in different systems ------------------------------- - -Modern hardware is pretty fast at copying the page table. -So are modern hardware-assisted virtualized environments, -but fork can be really slow in older virtualized environments without hardware support. -As of 2024, this is hardly a problem. - -You can measure the fork time for a Valkey instance by -performing a BGSAVE and looking at the `latest_fork_usec` field in the `INFO` command output. - -Latency induced by transparent huge pages ------------------------------------------ - -Unfortunately when a Linux kernel has transparent huge pages enabled, Valkey -incurs to a big latency penalty after the `fork` call is used in order to -persist on disk. Huge pages are the cause of the following issue: - -1. Fork is called, two processes with shared huge pages are created. -2. In a busy instance, a few event loops runs will cause commands to target a few thousand of pages, causing the copy on write of almost the whole process memory. -3. This will result in big latency and big memory usage. - -Make sure to **disable transparent huge pages** using the following command: - - echo never > /sys/kernel/mm/transparent_hugepage/enabled - -Latency induced by swapping (operating system paging) ------------------------------------------------------ - -Linux (and many other modern operating systems) is able to relocate memory -pages from the memory to the disk, and vice versa, in order to use the -system memory efficiently. - -If a Valkey page is moved by the kernel from the memory to the swap file, when -the data stored in this memory page is used by Valkey (for example accessing -a key stored into this memory page) the kernel will stop the Valkey process -in order to move the page back into the main memory. This is a slow operation -involving random I/Os (compared to accessing a page that is already in memory) -and will result into anomalous latency experienced by Valkey clients. - -The kernel relocates Valkey memory pages on disk mainly because of three reasons: - -* The system is under memory pressure since the running processes are demanding -more physical memory than the amount that is available. The simplest instance of -this problem is simply Valkey using more memory than is available. -* The Valkey instance data set, or part of the data set, is mostly completely idle -(never accessed by clients), so the kernel could swap idle memory pages on disk. -This problem is very rare since even a moderately slow instance will touch all -the memory pages often, forcing the kernel to retain all the pages in memory. -* Some processes are generating massive read or write I/Os on the system. Because -files are generally cached, it tends to put pressure on the kernel to increase -the filesystem cache, and therefore generate swapping activity. Please note it -includes Valkey RDB and/or AOF background threads which can produce large files. - -Fortunately Linux offers good tools to investigate the problem, so the simplest -thing to do is when latency due to swapping is suspected is just to check if -this is the case. - -The first thing to do is to checking the amount of Valkey memory that is swapped -on disk. In order to do so you need to obtain the Valkey instance pid: - - $ valkey-cli info | grep process_id - process_id:5454 - -Now enter the /proc file system directory for this process: - - $ cd /proc/5454 - -Here you'll find a file called **smaps** that describes the memory layout of -the Valkey process (assuming you are using Linux 2.6.16 or newer). -This file contains very detailed information about our process memory maps, -and one field called **Swap** is exactly what we are looking for. However -there is not just a single swap field since the smaps file contains the -different memory maps of our Valkey process (The memory layout of a process -is more complex than a simple linear array of pages). - -Since we are interested in all the memory swapped by our process the first thing -to do is to grep for the Swap field across all the file: - - $ cat smaps | grep 'Swap:' - Swap: 0 kB - Swap: 0 kB - Swap: 0 kB - Swap: 0 kB - Swap: 0 kB - Swap: 12 kB - Swap: 156 kB - Swap: 8 kB - Swap: 0 kB - Swap: 0 kB - Swap: 0 kB - Swap: 0 kB - Swap: 0 kB - Swap: 0 kB - Swap: 0 kB - Swap: 0 kB - Swap: 0 kB - Swap: 4 kB - Swap: 0 kB - Swap: 0 kB - Swap: 4 kB - Swap: 0 kB - Swap: 0 kB - Swap: 4 kB - Swap: 4 kB - Swap: 0 kB - Swap: 0 kB - Swap: 0 kB - Swap: 0 kB - Swap: 0 kB - -If everything is 0 kB, or if there are sporadic 4k entries, everything is -perfectly normal. Actually in our example instance (the one of a real web -site running Valkey and serving hundreds of users every second) there are a -few entries that show more swapped pages. To investigate if this is a serious -problem or not we change our command in order to also print the size of the -memory map: - - $ cat smaps | egrep '^(Swap|Size)' - Size: 316 kB - Swap: 0 kB - Size: 4 kB - Swap: 0 kB - Size: 8 kB - Swap: 0 kB - Size: 40 kB - Swap: 0 kB - Size: 132 kB - Swap: 0 kB - Size: 720896 kB - Swap: 12 kB - Size: 4096 kB - Swap: 156 kB - Size: 4096 kB - Swap: 8 kB - Size: 4096 kB - Swap: 0 kB - Size: 4 kB - Swap: 0 kB - Size: 1272 kB - Swap: 0 kB - Size: 8 kB - Swap: 0 kB - Size: 4 kB - Swap: 0 kB - Size: 16 kB - Swap: 0 kB - Size: 84 kB - Swap: 0 kB - Size: 4 kB - Swap: 0 kB - Size: 4 kB - Swap: 0 kB - Size: 8 kB - Swap: 4 kB - Size: 8 kB - Swap: 0 kB - Size: 4 kB - Swap: 0 kB - Size: 4 kB - Swap: 4 kB - Size: 144 kB - Swap: 0 kB - Size: 4 kB - Swap: 0 kB - Size: 4 kB - Swap: 4 kB - Size: 12 kB - Swap: 4 kB - Size: 108 kB - Swap: 0 kB - Size: 4 kB - Swap: 0 kB - Size: 4 kB - Swap: 0 kB - Size: 272 kB - Swap: 0 kB - Size: 4 kB - Swap: 0 kB - -As you can see from the output, there is a map of 720896 kB -(with just 12 kB swapped) and 156 kB more swapped in another map: -basically a very small amount of our memory is swapped so this is not -going to create any problem at all. - -If instead a non trivial amount of the process memory is swapped on disk your -latency problems are likely related to swapping. If this is the case with your -Valkey instance you can further verify it using the **vmstat** command: - - $ vmstat 1 - procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu---- - r b swpd free buff cache si so bi bo in cs us sy id wa - 0 0 3980 697932 147180 1406456 0 0 2 2 2 0 4 4 91 0 - 0 0 3980 697428 147180 1406580 0 0 0 0 19088 16104 9 6 84 0 - 0 0 3980 697296 147180 1406616 0 0 0 28 18936 16193 7 6 87 0 - 0 0 3980 697048 147180 1406640 0 0 0 0 18613 15987 6 6 88 0 - 2 0 3980 696924 147180 1406656 0 0 0 0 18744 16299 6 5 88 0 - 0 0 3980 697048 147180 1406688 0 0 0 4 18520 15974 6 6 88 0 - ^C - -The interesting part of the output for our needs are the two columns **si** -and **so**, that counts the amount of memory swapped from/to the swap file. If -you see non zero counts in those two columns then there is swapping activity -in your system. - -Finally, the **iostat** command can be used to check the global I/O activity of -the system. - - $ iostat -xk 1 - avg-cpu: %user %nice %system %iowait %steal %idle - 13.55 0.04 2.92 0.53 0.00 82.95 - - Device: rrqm/s wrqm/s r/s w/s rkB/s wkB/s avgrq-sz avgqu-sz await svctm %util - sda 0.77 0.00 0.01 0.00 0.40 0.00 73.65 0.00 3.62 2.58 0.00 - sdb 1.27 4.75 0.82 3.54 38.00 32.32 32.19 0.11 24.80 4.24 1.85 - -If your latency problem is due to Valkey memory being swapped on disk you need -to lower the memory pressure in your system, either adding more RAM if Valkey -is using more memory than the available, or avoiding running other memory -hungry processes in the same system. - -Latency due to AOF and disk I/O -------------------------------- - -Another source of latency is due to the Append Only File support on Valkey. -The AOF basically uses two system calls to accomplish its work. One is -write(2) that is used in order to write data to the append only file, and -the other one is fdatasync(2) that is used in order to flush the kernel -file buffer on disk in order to ensure the durability level specified by -the user. - -Both the write(2) and fdatasync(2) calls can be source of latency. -For instance write(2) can block both when there is a system wide sync -in progress, or when the output buffers are full and the kernel requires -to flush on disk in order to accept new writes. - -The fdatasync(2) call is a worse source of latency as with many combinations -of kernels and file systems used it can take from a few milliseconds to -a few seconds to complete, especially in the case of some other process -doing I/O. For this reason when possible Valkey does the fdatasync(2) call -in a different thread. - -We'll see how configuration can affect the amount and source of latency -when using the AOF file. - -The AOF can be configured to perform a fsync on disk in three different -ways using the **appendfsync** configuration option (this setting can be -modified at runtime using the **CONFIG SET** command). - -* When appendfsync is set to the value of **no** Valkey performs no fsync. -In this configuration the only source of latency can be write(2). -When this happens usually there is no solution since simply the disk can't -cope with the speed at which Valkey is receiving data, however this is -uncommon if the disk is not seriously slowed down by other processes doing -I/O. - -* When appendfsync is set to the value of **everysec** Valkey performs a -fsync every second. It uses a different thread, and if the fsync is still -in progress Valkey uses a buffer to delay the write(2) call up to two seconds -(since write would block on Linux if a fsync is in progress against the -same file). However if the fsync is taking too long Valkey will eventually -perform the write(2) call even if the fsync is still in progress, and this -can be a source of latency. - -* When appendfsync is set to the value of **always** a fsync is performed -at every write operation before replying back to the client with an OK code -(actually Valkey will try to cluster many commands executed at the same time -into a single fsync). In this mode performances are very low in general and -it is strongly recommended to use a fast disk and a file system implementation -that can perform the fsync in short time. - -Most Valkey users will use either the **no** or **everysec** setting for the -appendfsync configuration directive. The suggestion for minimum latency is -to avoid other processes doing I/O in the same system. -Using an SSD disk can help as well, but usually even non SSD disks perform -well with the append only file if the disk is spare as Valkey writes -to the append only file without performing any seek. - -If you want to investigate your latency issues related to the append only -file you can use the strace command under Linux: - - sudo strace -p $(pidof valkey-server) -T -e trace=fdatasync - -The above command will show all the fdatasync(2) system calls performed by -Valkey in the main thread. With the above command you'll not see the -fdatasync system calls performed by the background thread when the -appendfsync config option is set to **everysec**. In order to do so -just add the -f switch to strace. - -If you wish you can also see both fdatasync and write system calls with the -following command: - - sudo strace -p $(pidof valkey-server) -T -e trace=fdatasync,write - -However since write(2) is also used in order to write data to the client -sockets this will likely show too many things unrelated to disk I/O. -Apparently there is no way to tell strace to just show slow system calls so -I use the following command: - - sudo strace -f -p $(pidof valkey-server) -T -e trace=fdatasync,write 2>&1 | grep -v '0.0' | grep -v unfinished - -Latency generated by expires ----------------------------- - -Valkey evict expired keys in two ways: - -+ One *lazy* way expires a key when it is requested by a command, but it is found to be already expired. -+ One *active* way expires a few keys every 100 milliseconds. - -The active expiring is designed to be adaptive. An expire cycle is started every 100 milliseconds (10 times per second), and will do the following: - -+ Sample `ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP` keys, evicting all the keys already expired. -+ If the more than 25% of the keys were found expired, repeat. - -Given that `ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP` is set to 20 by default, and the process is performed ten times per second, usually just 200 keys per second are actively expired. This is enough to clean the DB fast enough even when already expired keys are not accessed for a long time, so that the *lazy* algorithm does not help. At the same time expiring just 200 keys per second has no effects in the latency a Valkey instance. - -However the algorithm is adaptive and will loop if it finds more than 25% of keys already expired in the set of sampled keys. But given that we run the algorithm ten times per second, this means that the unlucky event of more than 25% of the keys in our random sample are expiring at least *in the same second*. - -Basically this means that **if the database has many, many keys expiring in the same second, and these make up at least 25% of the current population of keys with an expire set**, Valkey can block in order to get the percentage of keys already expired below 25%. - -This approach is needed in order to avoid using too much memory for keys that are already expired, and usually is absolutely harmless since it's strange that a big number of keys are going to expire in the same exact second, but it is not impossible that the user used `EXPIREAT` extensively with the same Unix time. - -In short: be aware that many keys expiring at the same moment can be a source of latency. - -Valkey software watchdog ---- - -The *Valkey Software Watchdog* is a debugging tool -designed to track those latency problems that for one reason or the other -escaped an analysis using normal tools. - -The software watchdog is an experimental feature. While it is designed to -be used in production environments care should be taken to backup the database -before proceeding as it could possibly have unexpected interactions with the -normal execution of the Valkey server. - -It is important to use it only as *last resort* when there is no way to track the issue by other means. - -This is how this feature works: - -* The user enables the software watchdog using the `CONFIG SET` command. -* Valkey starts monitoring itself constantly. -* If Valkey detects that the server is blocked into some operation that is not returning fast enough, and that may be the source of the latency issue, a low level report about where the server is blocked is dumped on the log file. -* The user contacts the developers by opening an issue on GitHub, including the watchdog report in the message. - -Note that this feature cannot be enabled using the valkey.conf file, because it is designed to be enabled only in already running instances and only for debugging purposes. - -To enable the feature just use the following: - - CONFIG SET watchdog-period 500 - -The period is specified in milliseconds. In the above example I specified to log latency issues only if the server detects a delay of 500 milliseconds or greater. The minimum configurable period is 200 milliseconds. - -When you are done with the software watchdog you can turn it off setting the `watchdog-period` parameter to 0. **Important:** remember to do this because keeping the instance with the watchdog turned on for a longer time than needed is generally not a good idea. - -The following is an example of what you'll see printed in the log file once the software watchdog detects a delay longer than the configured one: - - [8547 | signal handler] (1333114359) - --- WATCHDOG TIMER EXPIRED --- - /lib/libc.so.6(nanosleep+0x2d) [0x7f16b5c2d39d] - /lib/libpthread.so.0(+0xf8f0) [0x7f16b5f158f0] - /lib/libc.so.6(nanosleep+0x2d) [0x7f16b5c2d39d] - /lib/libc.so.6(usleep+0x34) [0x7f16b5c62844] - ./valkey-server(debugCommand+0x3e1) [0x43ab41] - ./valkey-server(call+0x5d) [0x415a9d] - ./valkey-server(processCommand+0x375) [0x415fc5] - ./valkey-server(processInputBuffer+0x4f) [0x4203cf] - ./valkey-server(readQueryFromClient+0xa0) [0x4204e0] - ./valkey-server(aeProcessEvents+0x128) [0x411b48] - ./valkey-server(aeMain+0x2b) [0x411dbb] - ./valkey-server(main+0x2b6) [0x418556] - /lib/libc.so.6(__libc_start_main+0xfd) [0x7f16b5ba1c4d] - ./valkey-server() [0x411099] - ------ - -Note: in the example the **DEBUG SLEEP** command was used in order to block the server. The stack trace is different if the server blocks in a different context. - -If you happen to collect multiple watchdog stack traces you are encouraged to post everything in a GitHub issue. -The more traces we obtain, the simpler it will be to understand what the problem with your instance is. diff --git a/topics/ldap.md b/topics/ldap.md deleted file mode 100644 index e3080e50..00000000 --- a/topics/ldap.md +++ /dev/null @@ -1,214 +0,0 @@ ---- -title: "LDAP Authentication" -description: > - Introduction to LDAP / Active Directory Authentication ---- - -Valkey supports LDAP authentication through the official [valkey-ldap module](https://github.com/valkey-io/valkey-ldap), compatible with Valkey versions 7.2.x and above. To enable this feature, you must load the module on your Valkey server. - -This module allows Valkey to authenticate users using external LDAP-based systems, such as Active Directory. It seamlessly integrates Valkey’s authentication with enterprise identity management solutions, enabling organizations to leverage their existing authentication infrastructure. - -This module supports two LDAP authentication modes. The `bind` mode, and the `search+bind` mode. - -The `bind` mode is used when the username provided in the Valkey [`AUTH`](../commands/auth.md) command matches a substring of the distinguished name (DN) of user entries in the LDAP directory. The `search+bind` mode offers greater flexibility, allowing the username to match any attribute value of an LDAP user entry, making it suitable for more complex directory structures. - -## Bind Mode Authentication - -In the `bind` mode, the module constructs the distinguished name (DN) by adding a configurable prefix and suffix to the username. - -Typically, the prefix is set to `CN=` or `DOMAIN\` for Active Directory environments, while the suffix defines the remainder of the DN in non-Active Directory setups. - -Here’s an example of how to use `bind` mode for authentication. - -Consider the following LDAP user entry: - -``` -dn: uid=ben,ou=engineering,dc=valkey,dc=io -objectclass: person -objectclass: inetOrgPerson -cn: Ben Alex -sn: Alex -uid: ben -``` - -In this case, the DN is `uid=ben,ou=engineering,dc=valkey,dc=io`, and the username is `ben`. To use `bind` mode, set the prefix to `uid=` and the suffix to `,ou=engineering,dc=valkey,dc=io`. - -You can configure these values using the `ldap.bind_dn_prefix` and `ldap.bind_dn_suffix` options. - -## Search+Bind Authentication - -In the `search+bind` mode, the module first binds to the LDAP directory using a username and password of an account that has permissions to perform search operations in the LDAP directory. These credentials are stored in the module configuration, where you specify the bind DN (Distinguished Name) in `ldap.search_bind_dn` and the password in `ldap.search_bind_passwd`. - -If no username and password is configured for search bind account, an anonymous bind will be attempted to the directory. - -**Warning:** Anonymous binds can expose sensitive directory information if not properly restricted. -Ensure that your LDAP server is configured to limit access for anonymous users to prevent unintended data exposure. - -After the binding phase, a search operation is performed over the subtree at a configurable base DN string, which is set in the module configuration under the `ldap.search_base_dn` parameter. The module will then attempt to match the username specified in the `AUTH` command against the value of a configurable entry attribute, defined by the `ldap.search_attribute` parameter in the configuration. - -Once the user entry is found, the module retrieves the user’s DN from the attribute specified by the `ldap.search_dn_attribute` configuration option. It then re-binds to the LDAP directory as this user, using the extracted DN and the password provided in the `AUTH` command, to verify the login credentials. - -Here’s an example of how to use `search+bind` mode for authentication. - -Consider the following LDAP user entry: - -``` -dn: cn=Ben Alex,ou=engineering,dc=valkey,dc=io -objectClass: person -objectClass: inetOrgPerson -entryDN: cn=Ben Alex,ou=engineering,dc=valkey,dc=io -cn: Ben Alex -sn: Alex -uid: ben -``` - -In this example, the username `ben` is stored in the `uid` attribute, and the user's DN is stored in the `entryDN` attribute. Since it's not possible to construct the DN using the username with a prefix and suffix as in the `bind` mode, you need to use `search+bind` mode to locate the user entry and extract its DN. - -Set `ldap.search_attribute` to `uid` and `ldap.search_dn_attribute` to `entryDN` to match the username and retrieve the DN. - -You can also use the `ldap.search_filter` option to restrict which LDAP objects are included in the search. By default, `ldap.search_filter` is set to `objectClass=*`, which matches all objects. - -Internally, the module performs an LDAP search with a filter like `(&(objectClass=*)(uid=ben))`, which matches the entry above. It then extracts the DN from the `entryDN` attribute and re-binds using this DN and the password provided in the `AUTH` command to complete authentication. - -### Comparison with Bind Mode - -While `bind` mode is simpler and faster, as it directly constructs the DN from the username, it is best suited for environments where the directory structure is straightforward and usernames directly correspond to DN components. - -On the other hand, `search+bind` mode provides greater flexibility, allowing authentication in complex directory structures where usernames may not directly map to DN components. - -However, this flexibility comes at the cost of additional LDAP requests, making it slightly slower than `bind` mode. - -## Setting Up Valkey Users - -The LDAP server is used solely for authenticating users. -Authorization rules for each user must be configured in Valkey using either the [`ACL SETUSER`](../commands/acl-setuser.md) command, through entries in `valkey.conf`, or using an [ACL file](acl.md). -This means that user accounts must exist in Valkey in order for LDAP authentication to succeed. - -For example, to allow the user `bob` to authenticate via LDAP, a corresponding user named `bob` must be present in the Valkey ACL database. - -To ensure that `bob` cannot log in using password-based authentication, you can create the Valkey user without specifying a password. - -To create a user without a password, simply omit the password when running the `ACL SETUSER` command and define the appropriate ACL rules. For example: - -``` -ACL SETUSER bob on +@hash -``` - -After creating the user `bob` in Valkey, authentication will only be possible through the LDAP module. - -## Setting Up LDAP module - -All module configuration options are prefixed with `ldap.` and can be set using the `CONFIG SET` command. To view the current values of all module-related options, use the command `CONFIG GET ldap.*`. - -After the module is loaded in Valkey, the first thing that is required for the LDAP authentication to work is to configure the list of LDAP servers that should be used for the authentication. - -The configuration option `ldap.servers` accepts a space separated list of LDAP URLs of the form `ldap[s]://:`. - -After setting this option, the module will initialize the connection pools to the configured LDAP servers. - -The authentication mode `bind` vs `search+bind` is configured using the `ldap.auth_mode` option. - -### TLS Configuration - -The LDAP protocol supports two methods for securing connections between the client and the server: **LDAPS** and **STARTTLS**. - -- **LDAPS (LDAP over SSL):** - LDAPS secures the connection by establishing an SSL/TLS session as soon as the TCP connection is made, typically on port 636. All communication between the client and server is encrypted from the start. To use LDAPS, specify an LDAP URL with the `ldaps://` scheme. - -- **STARTTLS:** - STARTTLS starts with a standard, unencrypted LDAP connection (usually on port 389). The client then issues a STARTTLS command to upgrade the connection to TLS encryption. To enable this method, set the `ldap.use_starttls` option to `yes`. - -Both methods provide strong encryption for LDAP traffic. The choice depends on your environment and security requirements. Make sure your LDAP server is configured with valid SSL/TLS certificates to support secure connections. - -To verify LDAP server certificates, use the `ldap.tls_ca_cert_path` option to specify the path to a trusted CA certificate file. If this option is not set, the module will use the system’s default trusted CA certificates. - -If you need to use client certificates for authentication, configure the `ldap.tls_cert_path` and `ldap.tls_key_path` options with the paths to your client certificate and private key. - -## Monitoring - -The module extends the output of the `INFO` command by adding a new section called `ldap_status`, which provides status information for each LDAP server configured via the `ldap.servers` option. - -The `ldap_status` section includes a dictionary entry for each server, with the following possible fields: - -- `host`: The server hostname extracted from the URL specified in the `ldap.servers` configuration. -- `status`: Indicates the server's health. Possible values are `healthy` (the server is reachable and responds to LDAP operations) or `unhealthy` (the server cannot process LDAP operations). -- `ping_time_ms`: The round-trip time (RTT) for a simple LDAP operation, in milliseconds. This field is shown only for `healthy` servers. -- `error`: A description of the error that caused the server to be marked as `unhealthy`. This field is shown only for `unhealthy` servers. - -Example output from the `INFO` command: - -``` -# ldap_status -ldap_server_0:host=,status=unhealthy,error= -ldap_server_1:host=,status=healthy,ping_time_ms=1.645 -``` - -## Advanced Configuration - -The LDAP module provides several configuration options to help adapt authentication behavior to your network environment and LDAP server load. - -### LDAP Server Connection Management - -Because LDAP servers are often shared by multiple applications, it's important to limit the number of connections each application opens to avoid exhausting the server's resources. - -The `ldap.connection_pool_size` option specifies the maximum number of connections the module will open to each configured LDAP server. Set this value based on the expected number of concurrent authentication requests in Valkey and the maximum number of connections your LDAP server can support. - -If the number of parallel authentication requests exceeds the configured pool size, authentication latency may increase as requests wait for available connections. - -### LDAP Server Failure Detection - -The module includes a background process that periodically checks the status of each configured LDAP server. - -The frequency of these checks is controlled by the `ldap.failure_detector_interval` option, which accepts a value in seconds. - -If the failure detector determines that an LDAP server is unreachable or unable to process LDAP operations, it marks the server as "unhealthy" and automatically fails over authentication requests to another available LDAP server. - -If network latency between Valkey and the LDAP server is variable, or if the LDAP server is under heavy load, you can adjust the connection and operation timeouts using the `ldap.timeout_connection` and `ldap.timeout_ldap_operation` options. - - -## Configuration Options - -### General Options - -| Config Name | Type | Default | Description | -|------------------------|------------------------------|---------|---------------------------------------------------------------------------------------------------------------| -| `ldap.auth_mode` | Enum(`bind`, `search+bind`) | `bind` | The authentication method. | -| `ldap.servers` | string | `""` | Space-separated list of LDAP URLs in the form `ldap[s]://:`. | - -### TLS Options - -| Config Name | Type | Default | Description | -|-------------------------|---------|---------|--------------------------------------------------------------------------------------------------| -| `ldap.use_starttls` | boolean | `no` | Whether to upgrade to a TLS-encrypted connection using the STARTTLS operation (RFC 4513). | -| `ldap.tls_ca_cert_path` | string | `""` | Filesystem path to the CA certificate for validating the LDAP server certificate. | -| `ldap.tls_cert_path` | string | `""` | Filesystem path to the client certificate for TLS connections to the LDAP server. | -| `ldap.tls_key_path` | string | `""` | Filesystem path to the client certificate key for TLS connections to the LDAP server. | - -### Bind Mode Options - -| Config Name | Type | Default | Description | -|-----------------------|--------|----------|--------------------------------------------------------------------------------------------------| -| `ldap.bind_dn_prefix` | string | `"cn="` | String to prepend to the username from the `AUTH` command when forming the DN for LDAP bind. | -| `ldap.bind_dn_suffix` | string | `""` | String to append to the username from the `AUTH` command when forming the DN for LDAP bind. | - -### Search+Bind Mode Options - -| Config Name | Type | Default | Description | -|--------------------------|------------------------------|-------------------|--------------------------------------------------------------------------------------------------| -| `ldap.search_bind_dn` | string | `""` | DN of the user account used to perform LDAP searches. | -| `ldap.search_bind_passwd`| string | `""` | Password for the search bind user. | -| `ldap.search_base` | string | `""` | Base DN where the search for the user entry begins. | -| `ldap.search_filter` | string | `"objectClass=*"` | LDAP search filter to apply when searching for user entries. | -| `ldap.search_attribute` | string | `"uid"` | LDAP attribute to match against the username provided in the `AUTH` command. | -| `ldap.search_scope` | Enum(`base`, `one`, `sub`) | `sub` | Scope of the LDAP search. | -| `ldap.search_dn_attribute`| string | `"entryDN"` | Attribute containing the DN of the user entry. | - -### Advanced Options - -| Config Name | Type | Default | Description | -|------------------------------|--------|---------|--------------------------------------------------------------------------------------------------| -| `ldap.connection_pool_size` | number | `2` | Number of connections in each LDAP server's connection pool. | -| `ldap.failure_detector_interval` | number | `1` | Interval (in seconds) between each failure detector check. | -| `ldap.timeout_connection` | number | `10` | Number of seconds to wait when connecting to an LDAP server before timing out. | -| `ldap.timeout_ldap_operation`| number | `10` | Number of seconds to wait for an LDAP operation before timing out. | - diff --git a/topics/ldb.md b/topics/ldb.md deleted file mode 100644 index eae2d780..00000000 --- a/topics/ldb.md +++ /dev/null @@ -1,236 +0,0 @@ ---- -title: Debugging Lua scripts -description: How to use the built-in Lua debugger ---- - -Valkey includes a complete Lua debugger, that can be -used to make the task of writing complex Lua scripts much simpler. - -The Valkey Lua debugger, codenamed LDB, has the following important features: - -* It uses a server-client model, so it's a remote debugger. -The Valkey server acts as the debugging server, while the default client is `valkey-cli`. -However other clients can be developed by following the simple protocol implemented by the server. -* By default every new debugging session is a forked session. -It means that while the Valkey Lua script is being debugged, the server does not block and is usable for development or in order to execute multiple debugging sessions in parallel. -This also means that changes are **rolled back** after the script debugging session finished, so that's possible to restart a new debugging session again, using exactly the same Valkey data set as the previous debugging session. -* An alternative synchronous (non forked) debugging model is available on demand, so that changes to the dataset can be retained. -In this mode the server blocks for the time the debugging session is active. -* Support for step by step execution. -* Support for static and dynamic breakpoints. -* Support from logging the debugged script into the debugger console. -* Inspection of Lua variables. -* Tracing of Valkey commands executed by the script. -* Pretty printing of Valkey and Lua values. -* Infinite loops and long execution detection, which simulates a breakpoint. - -## Quick start - -A simple way to get started with the Lua debugger is to watch this video -introduction: - - - -> Important Note: please make sure to avoid debugging Lua scripts using your Valkey production server. -Use a development server instead. -Also note that using the synchronous debugging mode (which is NOT the default) results in the Valkey server blocking for all the time the debugging session lasts. - -To start a new debugging session using `valkey-cli` do the following: - -1. Create your script in some file with your preferred editor. Let's assume you are editing your Valkey Lua script located at `/tmp/script.lua`. -2. Start a debugging session with: - - ./valkey-cli --ldb --eval /tmp/script.lua - -Note that with the `--eval` option of `valkey-cli` you can pass key names and arguments to the script, separated by a comma, like in the following example: - -``` -./valkey-cli --ldb --eval /tmp/script.lua mykey somekey , arg1 arg2 -``` - -You'll enter a special mode where `valkey-cli` no longer accepts its normal -commands, but instead prints a help screen and passes the unmodified debugging -commands directly to Valkey. - -The only commands which are not passed to the Valkey debugger are: - -* `quit` -- this will terminate the debugging session. -It's like removing all the breakpoints and using the `continue` debugging command. -Moreover the command will exit from `valkey-cli`. -* `restart` -- the debugging session will restart from scratch, **reloading the new version of the script from the file**. -So a normal debugging cycle involves modifying the script after some debugging, and calling `restart` in order to start debugging again with the new script changes. -* `help` -- this command is passed to the Valkey Lua debugger, that will print a list of commands like the following: - -``` -lua debugger> help -Valkey Lua debugger help: -[h]elp Show this help. -[s]tep Run current line and stop again. -[n]ext Alias for step. -[c]ontinue Run till next breakpoint. -[l]ist List source code around current line. -[l]ist [line] List source code around [line]. - line = 0 means: current position. -[l]ist [line] [ctx] In this form [ctx] specifies how many lines - to show before/after [line]. -[w]hole List all source code. Alias for 'list 1 1000000'. -[p]rint Show all the local variables. -[p]rint Show the value of the specified variable. - Can also show global vars KEYS and ARGV. -[b]reak Show all breakpoints. -[b]reak Add a breakpoint to the specified line. -[b]reak - Remove breakpoint from the specified line. -[b]reak 0 Remove all breakpoints. -[t]race Show a backtrace. -[e]val Execute some Lua code (in a different callframe). -[r]edis Execute a Valkey command. -[m]axlen [len] Trim logged Valkey replies and Lua var dumps to len. - Specifying zero as means unlimited. -[a]bort Stop the execution of the script. In sync - mode dataset changes will be retained. - -Debugger functions you can call from Lua scripts: -server.debug() Produce logs in the debugger console. -server.breakpoint() Stop execution as if there was a breakpoint in the - next line of code. -``` - -Note that when you start the debugger it will start in **stepping mode**. -It will stop at the first line of the script that actually does something before executing it. - -From this point you usually call `step` in order to execute the line and go to the next line. -While you step Valkey will show all the commands executed by the server like in the following example: - -``` -* Stopped at 1, stop reason = step over --> 1 server.call('ping') -lua debugger> step - ping - "+PONG" -* Stopped at 2, stop reason = step over -``` - -The `` and `` lines show the command executed by the line just -executed, and the reply from the server. Note that this happens only in stepping mode. -If you use `continue` in order to execute the script till the next breakpoint, commands will not be dumped on the screen to prevent too much output. - -## Termination of the debugging session - -When the scripts terminates naturally, the debugging session ends and -`valkey-cli` returns in its normal non-debugging mode. You can restart the -session using the `restart` command as usual. - -Another way to stop a debugging session is just interrupting `valkey-cli` -manually by pressing `Ctrl+C`. Note that also any event breaking the -connection between `valkey-cli` and the `valkey-server` will interrupt the -debugging session. - -All the forked debugging sessions are terminated when the server is shut -down. - -## Abbreviating debugging commands - -Debugging can be a very repetitive task. For this reason every Valkey -debugger command starts with a different character, and you can use the single -initial character in order to refer to the command. - -So for example instead of typing `step` you can just type `s`. - -## Breakpoints - -Adding and removing breakpoints is trivial as described in the online help. -Just use `b 1 2 3 4` to add a breakpoint in line 1, 2, 3, 4. -The command `b 0` removes all the breakpoints. Selected breakpoints can be -removed using as argument the line where the breakpoint we want to remove is, but prefixed by a minus sign. -So for example `b -3` removes the breakpoint from line 3. - -Note that adding breakpoints to lines that Lua never executes, like declaration of local variables or comments, will not work. -The breakpoint will be added but since this part of the script will never be executed, the program will never stop. - -## Dynamic breakpoints - -Using the `breakpoint` command it is possible to add breakpoints into specific -lines. However sometimes we want to stop the execution of the program only -when something special happens. In order to do so, you can use the -`server.breakpoint()` function inside your Lua script. When called it simulates -a breakpoint in the next line that will be executed. - -``` -if counter > 10 then server.breakpoint() end -``` - -This feature is extremely useful when debugging, so that we can avoid -continuing the script execution manually multiple times until a given condition -is encountered. - -## Synchronous mode - -As explained previously, but default LDB uses forked sessions with rollback -of all the data changes operated by the script while it has being debugged. -Determinism is usually a good thing to have during debugging, so that successive -debugging sessions can be started without having to reset the database content -to its original state. - -However for tracking certain bugs, you may want to retain the changes performed -to the key space by each debugging session. When this is a good idea you -should start the debugger using a special option, `ldb-sync-mode`, in `valkey-cli`. - -``` -./valkey-cli --ldb-sync-mode --eval /tmp/script.lua -``` - -> Note: Valkey server will be unreachable during the debugging session in this mode, so use with care. - -In this special mode, the `abort` command can stop the script half-way taking the changes operated to the dataset. -Note that this is different compared to ending the debugging session normally. -If you just interrupt `valkey-cli` the script will be fully executed and then the session terminated. -Instead with `abort` you can interrupt the script execution in the middle and start a new debugging session if needed. - -## Logging from scripts - -The `server.debug()` command is a powerful debugging facility that can be -called inside the Valkey Lua script in order to log things into the debug -console: - -``` -lua debugger> list --> 1 local a = {1,2,3} - 2 local b = false - 3 server.debug(a,b) -lua debugger> continue - line 3: {1; 2; 3}, false -``` - -If the script is executed outside of a debugging session, `server.debug()` has no effects at all. -Note that the function accepts multiple arguments, that are separated by a comma and a space in the output. - -Tables and nested tables are displayed correctly in order to make values simple to observe for the programmer debugging the script. - -## Inspecting the program state with `print` and `eval` - -While the `server.debug()` function can be used in order to print values -directly from within the Lua script, often it is useful to observe the local -variables of a program while stepping or when stopped into a breakpoint. - -The `print` command does just that, and performs lookup in the call frames -starting from the current one back to the previous ones, up to top-level. -This means that even if we are into a nested function inside a Lua script, -we can still use `print foo` to look at the value of `foo` in the context -of the calling function. When called without a variable name, `print` will -print all variables and their respective values. - -The `eval` command executes small pieces of Lua scripts **outside the context of the current call frame** (evaluating inside the context of the current call frame is not possible with the current Lua internals). -However you can use this command in order to test Lua functions. - -``` -lua debugger> e server.sha1hex('foo') - "0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33" -``` - -## Debugging clients - -LDB uses the client-server model where the Valkey server acts as a debugging server that communicates using [RESP](protocol.md). While `valkey-cli` is the default debug client, any [client](../clients/) can be used for debugging as long as it meets one of the following conditions: - -1. The client provides a native interface for setting the debug mode and controlling the debug session. -2. The client provides an interface for sending arbitrary commands over RESP. -3. The client allows sending raw messages to the Valkey server. diff --git a/topics/lists.md b/topics/lists.md deleted file mode 100644 index e2e094dc..00000000 --- a/topics/lists.md +++ /dev/null @@ -1,408 +0,0 @@ ---- -title: "Lists" -description: > - Introduction to Lists ---- - -Lists are linked lists of string values. -Lists are frequently used to: - -* Implement stacks and queues. -* Build queue management for background worker systems. - -## Basic commands - -* `LPUSH` adds a new element to the head of a list; `RPUSH` adds to the tail. -* `LPOP` removes and returns an element from the head of a list; `RPOP` does the same but from the tails of a list. -* `LLEN` returns the length of a list. -* `LMOVE` atomically moves elements from one list to another. -* `LTRIM` reduces a list to the specified range of elements. - -### Blocking commands - -Lists support several blocking commands. -For example: - -* `BLPOP` removes and returns an element from the head of a list. - If the list is empty, the command blocks until an element becomes available or until the specified timeout is reached. -* `BLMOVE` atomically moves elements from a source list to a target list. - If the source list is empty, the command will block until a new element becomes available. - -See the [complete series of list commands](../commands/#list). - -## Examples - -* Treat a list like a queue (first in, first out): -``` -127.0.0.1:6379> LPUSH bikes:repairs bike:1 -(integer) 1 -127.0.0.1:6379> LPUSH bikes:repairs bike:2 -(integer) 2 -127.0.0.1:6379> RPOP bikes:repairs -"bike:1" -127.0.0.1:6379> RPOP bikes:repairs -"bike:2" -``` - -* Treat a list like a stack (first in, last out): -``` -127.0.0.1:6379> LPUSH bikes:repairs bike:1 -(integer) 1 -127.0.0.1:6379> LPUSH bikes:repairs bike:2 -(integer) 2 -127.0.0.1:6379> LPOP bikes:repairs -"bike:2" -127.0.0.1:6379> LPOP bikes:repairs -"bike:1" -``` - -* Check the length of a list: -``` -127.0.0.1:6379> LLEN bikes:repairs -(integer) 0 -``` - -* Atomically pop an element from one list and push to another: -``` -127.0.0.1:6379> LPUSH bikes:repairs bike:1 -(integer) 1 -127.0.0.1:6379> LPUSH bikes:repairs bike:2 -(integer) 2 -127.0.0.1:6379> LMOVE bikes:repairs bikes:finished LEFT LEFT -"bike:2" -127.0.0.1:6379> LRANGE bikes:repairs 0 -1 -1) "bike:1" -127.0.0.1:6379> LRANGE bikes:finished 0 -1 -1) "bike:2" -``` - -* To limit the length of a list you can call `LTRIM`: -``` -127.0.0.1:6379> RPUSH bikes:repairs bike:1 bike:2 bike:3 bike:4 bike:5 -(integer) 5 -127.0.0.1:6379> LTRIM bikes:repairs 0 2 -OK -127.0.0.1:6379> LRANGE bikes:repairs 0 -1 -1) "bike:1" -2) "bike:2" -3) "bike:3" -``` - -### What are Lists? -To explain the List data type it's better to start with a little bit of theory, -as the term *List* is often used in an improper way by information technology -folks. For instance "Python Lists" are not what the name may suggest (Linked -Lists), but rather Arrays (the same data type is called Array in -Ruby actually). - -From a very general point of view a List is just a sequence of ordered -elements: 10,20,1,2,3 is a list. But the properties of a List implemented using -an Array are very different from the properties of a List implemented using a -*Linked List*. - -Lists are implemented via Linked Lists. This means that even if you have -millions of elements inside a list, the operation of adding a new element in -the head or in the tail of the list is performed *in constant time*. The speed of adding a -new element with the `LPUSH` command to the head of a list with ten -elements is the same as adding an element to the head of list with 10 -million elements. - -What's the downside? Accessing an element *by index* is very fast in lists -implemented with an Array (constant time indexed access) and not so fast in -lists implemented by linked lists (where the operation requires an amount of -work proportional to the index of the accessed element). - -Lists are implemented with linked lists because for a database system it -is crucial to be able to add elements to a very long list in a very fast way. -Another strong advantage, as you'll see in a moment, is that Lists can be -taken at constant length in constant time. - -When fast access to the middle of a large collection of elements is important, -there is a different data structure that can be used, called sorted sets. -Sorted sets are covered in the [Sorted sets](sorted-sets.md) tutorial page. - -### First steps with Lists - -The `LPUSH` command adds a new element into a list, on the -left (at the head), while the `RPUSH` command adds a new -element into a list, on the right (at the tail). Finally the -`LRANGE` command extracts ranges of elements from lists: - -``` -127.0.0.1:6379> RPUSH bikes:repairs bike:1 -(integer) 1 -127.0.0.1:6379> RPUSH bikes:repairs bike:2 -(integer) 2 -127.0.0.1:6379> LPUSH bikes:repairs bike:important_bike -(integer) 3 -127.0.0.1:6379> LRANGE bikes:repairs 0 -1 -1) "bike:important_bike" -2) "bike:1" -3) "bike:2" -``` - -Note that `LRANGE` takes two indexes, the first and the last -element of the range to return. Both the indexes can be negative, telling Valkey -to start counting from the end: so -1 is the last element, -2 is the -penultimate element of the list, and so forth. - -As you can see `RPUSH` appended the elements on the right of the list, while -the final `LPUSH` appended the element on the left. - -Both commands are *variadic commands*, meaning that you are free to push -multiple elements into a list in a single call: - -``` -127.0.0.1:6379> RPUSH bikes:repairs bike:1 bike:2 bike:3 -(integer) 3 -127.0.0.1:6379> LPUSH bikes:repairs bike:important_bike bike:very_important_bike -127.0.0.1:6379> LRANGE bikes:repairs 0 -1 -1) "bike:very_important_bike" -2) "bike:important_bike" -3) "bike:1" -4) "bike:2" -5) "bike:3" -``` - -An important operation defined on Lists is the ability to *pop elements*. -Popping elements is the operation of both retrieving the element from the list, -and eliminating it from the list, at the same time. You can pop elements -from left and right, similarly to how you can push elements in both sides -of the list. We'll add three elements and pop three elements, so at the end of this -sequence of commands the list is empty and there are no more elements to -pop: - -``` -127.0.0.1:6379> RPUSH bikes:repairs bike:1 bike:2 bike:3 -(integer) 3 -127.0.0.1:6379> RPOP bikes:repairs -"bike:3" -127.0.0.1:6379> LPOP bikes:repairs -"bike:1" -127.0.0.1:6379> RPOP bikes:repairs -"bike:2" -127.0.0.1:6379> RPOP bikes:repairs -(nil) -``` - -Valkey returned a NULL value to signal that there are no elements in the -list. - -### Common use cases for lists - -Lists are useful for a number of tasks, two very representative use cases -are the following: - -* Remember the latest updates posted by users into a social network. -* Communication between processes, using a consumer-producer pattern where the producer pushes items into a list, and a consumer (usually a *worker*) consumes those items and executes actions. Valkey has special list commands to make this use case both more reliable and efficient. - -For example both the popular Ruby libraries [resque](https://github.com/resque/resque) and -[sidekiq](https://github.com/mperham/sidekiq) use Lists under the hood in order to -implement background jobs. - -The popular Twitter social network [takes the latest tweets](https://www.infoq.com/presentations/Real-Time-Delivery-Twitter) -posted by users into Lists. - -To describe a common use case step by step, imagine your home page shows the latest -photos published in a photo sharing social network and you want to speedup access. - -* Every time a user posts a new photo, we add its ID into a list with `LPUSH`. -* When users visit the home page, we use `LRANGE 0 9` in order to get the latest 10 posted items. - -### Capped lists - -In many use cases we just want to use lists to store the *latest items*, -whatever they are: social network updates, logs, or anything else. - -Valkey allows us to use lists as a capped collection, only remembering the latest -N items and discarding all the oldest items using the `LTRIM` command. - -The `LTRIM` command is similar to `LRANGE`, but **instead of displaying the -specified range of elements** it sets this range as the new list value. All -the elements outside the given range are removed. - -For example, if you're adding bikes on the end of a list of repairs, but only -want to worry about the 3 that have been on the list the longest: - -``` -127.0.0.1:6379> RPUSH bikes:repairs bike:1 bike:2 bike:3 bike:4 bike:5 -(integer) 5 -127.0.0.1:6379> LTRIM bikes:repairs 0 2 -OK -127.0.0.1:6379> LRANGE bikes:repairs 0 -1 -1) "bike:1" -2) "bike:2" -3) "bike:3" -``` - -The above `LTRIM` command tells Valkey to keep just list elements from index -0 to 2, everything else will be discarded. This allows for a very simple but -useful pattern: doing a List push operation + a List trim operation together -to add a new element and discard elements exceeding a limit. Using -`LTRIM` with negative indexes can then be used to keep only the 3 most recently added: - -``` -127.0.0.1:6379> RPUSH bikes:repairs bike:1 bike:2 bike:3 bike:4 bike:5 -(integer) 5 -127.0.0.1:6379> LTRIM bikes:repairs -3 -1 -OK -127.0.0.1:6379> LRANGE bikes:repairs 0 -1 -1) "bike:3" -2) "bike:4" -3) "bike:5" -``` - -The above combination adds new elements and keeps only the 3 -newest elements into the list. With `LRANGE` you can access the top items -without any need to remember very old data. - -Note: while `LRANGE` is technically an O(N) command, accessing small ranges -towards the head or the tail of the list is a constant time operation. - -Blocking operations on lists ---- - -Lists have a special feature that make them suitable to implement queues, -and in general as a building block for inter process communication systems: -blocking operations. - -Imagine you want to push items into a list with one process, and use -a different process in order to actually do some kind of work with those -items. This is the usual producer / consumer setup, and can be implemented -in the following simple way: - -* To push items into the list, producers call `LPUSH`. -* To extract / process items from the list, consumers call `RPOP`. - -However it is possible that sometimes the list is empty and there is nothing -to process, so `RPOP` just returns NULL. In this case a consumer is forced to wait -some time and retry again with `RPOP`. This is called *polling*, and is not -a good idea in this context because it has several drawbacks: - -1. Forces Valkey and clients to process useless commands (all the requests when the list is empty will get no actual work done, they'll just return NULL). -2. Adds a delay to the processing of items, since after a worker receives a NULL, it waits some time. To make the delay smaller, we could wait less between calls to `RPOP`, with the effect of amplifying problem number 1, i.e. more useless calls to Valkey. - -So Valkey implements commands called `BRPOP` and `BLPOP` which are versions -of `RPOP` and `LPOP` able to block if the list is empty: they'll return to -the caller only when a new element is added to the list, or when a user-specified -timeout is reached. - -This is an example of a `BRPOP` call we could use in the worker: - -``` -127.0.0.1:6379> RPUSH bikes:repairs bike:1 bike:2 -(integer) 2 -127.0.0.1:6379> BRPOP bikes:repairs 1 -1) "bikes:repairs" -2) "bike:2" -127.0.0.1:6379> BRPOP bikes:repairs 1 -1) "bikes:repairs" -2) "bike:1" -127.0.0.1:6379> BRPOP bikes:repairs 1 -(nil) -(2.01s) -``` - -It means: "wait for elements in the list `bikes:repairs`, but return if after 1 second -no element is available". - -Note that you can use 0 as timeout to wait for elements forever, and you can -also specify multiple lists and not just one, in order to wait on multiple -lists at the same time, and get notified when the first list receives an -element. - -A few things to note about `BRPOP`: - -1. Clients are served in an ordered way: the first client that blocked waiting for a list, is served first when an element is pushed by some other client, and so forth. -2. The return value is different compared to `RPOP`: it is a two-element array since it also includes the name of the key, because `BRPOP` and `BLPOP` are able to block waiting for elements from multiple lists. -3. If the timeout is reached, NULL is returned. - -There are more things you should know about lists and blocking ops. We -suggest that you read more on the following: - -* It is possible to build safer queues or rotating queues using `LMOVE`. -* There is also a blocking variant of the command, called `BLMOVE`. - -## Automatic creation and removal of keys - -So far in our examples we never had to create empty lists before pushing -elements, or removing empty lists when they no longer have elements inside. -It is Valkey' responsibility to delete keys when lists are left empty, or to create -an empty list if the key does not exist and we are trying to add elements -to it, for example, with `LPUSH`. - -This is not specific to lists, it applies to all the Valkey data types -composed of multiple elements -- Streams, Sets, Sorted Sets and Hashes. - -Basically we can summarize the behavior with three rules: - -1. When we add an element to an aggregate data type, if the target key does not exist, an empty aggregate data type is created before adding the element. -2. When we remove elements from an aggregate data type, if the value remains empty, the key is automatically destroyed. The Stream data type is the only exception to this rule. -3. Calling a read-only command such as `LLEN` (which returns the length of the list), or a write command removing elements, with an empty key, always produces the same result as if the key is holding an empty aggregate type of the type the command expects to find. - -Examples of rule 1: - -``` -127.0.0.1:6379> DEL new_bikes -(integer) 0 -127.0.0.1:6379> LPUSH new_bikes bike:1 bike:2 bike:3 -(integer) 3 -``` - -However we can't perform operations against the wrong type if the key exists: - -``` -127.0.0.1:6379> SET new_bikes bike:1 -OK -127.0.0.1:6379> TYPE new_bikes -string -127.0.0.1:6379> LPUSH new_bikes bike:2 bike:3 -(error) WRONGTYPE Operation against a key holding the wrong kind of value -``` - -Example of rule 2: - -``` -127.0.0.1:6379> RPUSH bikes:repairs bike:1 bike:2 bike:3 -(integer) 3 -127.0.0.1:6379> EXISTS bikes:repairs -(integer) 1 -127.0.0.1:6379> LPOP bikes:repairs -"bike:1" -127.0.0.1:6379> LPOP bikes:repairs -"bike:2" -127.0.0.1:6379> LPOP bikes:repairs -"bike:3" -127.0.0.1:6379> EXISTS bikes:repairs -(integer) 0 -``` - -The key no longer exists after all the elements are popped. - -Example of rule 3: - -``` -127.0.0.1:6379> DEL bikes:repairs -(integer) 0 -127.0.0.1:6379> LLEN bikes:repairs -(integer) 0 -127.0.0.1:6379> LPOP bikes:repairs -(nil) -``` - - -## Limits - -The max length of a List is 2^32 - 1 (4,294,967,295) elements. - - -## Performance - -List operations that access its head or tail are O(1), which means they're highly efficient. -However, commands that manipulate elements within a list are usually O(n). -Examples of these include `LINDEX`, `LINSERT`, and `LSET`. -Exercise caution when running these commands, mainly when operating on large lists. - -## Alternatives - -Consider [Streams](streams-intro.md) as an alternative to lists when you need to store and process an indeterminate series of events. diff --git a/topics/lru-cache.md b/topics/lru-cache.md deleted file mode 100644 index 94808009..00000000 --- a/topics/lru-cache.md +++ /dev/null @@ -1,237 +0,0 @@ ---- -title: Key eviction -description: Overview of Valkey key eviction policies (LRU, LFU, etc.) ---- - -When Valkey is used as a cache, it is often convenient to let it automatically -evict old data as you add new data. This behavior is well known in the -developer community, since it is the default behavior for the popular -*memcached* system. - -This page covers the more general topic of the Valkey `maxmemory` directive used to limit the memory usage to a fixed amount. It also extensively covers the LRU eviction algorithm used by Valkey, which is actually an approximation of -the exact LRU. - -## `Maxmemory` configuration directive - -The `maxmemory` configuration directive configures Valkey -to use a specified amount of memory for the data set. You can -set the configuration directive using the `valkey.conf` file, or later using -the `CONFIG SET` command at runtime. - -For example, to configure a memory limit of 100 megabytes, you can use the -following directive inside the `valkey.conf` file: - - maxmemory 100mb - -Setting `maxmemory` to zero results into no memory limits. This is the -default behavior for 64 bit systems, while 32 bit systems use an implicit -memory limit of 3GB. -When the specified amount of memory is reached, how **eviction policies** are configured determines the default behavior. -Valkey can return errors for commands that could result in more memory -being used, or it can evict some old data to return back to the -specified limit every time new data is added. - -### Considerations for `maxmemory` when using replication - -If you have set up replication, Valkey needs some RAM as a buffer to send data to the replicas and AOF files. This memory is not included in the used memory count that is compared against the `maxmemory` to trigger eviction. - -The reason for that is that the key eviction process itself generates some changes that need to be added to the replication and AOF buffers. If these buffers were counted for the key eviction, this would result in a loop where a freed memory would immediately be used up by these updates causing more keys to be deleted repeatedly until the database is empty. - -For Valkey with replication configured, it's recommended to set the `maxmemory` value lower than for a single instance without replication. This way you ensure there's enough memory for AOF and replication buffers, and other processes. - -You can estimate how much memory is used by the replication and AOF buffers using the `mem_not_counted_for_evict` value of the INFO memory command output. - -## Eviction policies - -The exact behavior Valkey follows when the `maxmemory` limit is reached is -configured using the `maxmemory-policy` configuration directive. - -The following policies are available: - -* **noeviction**: New values aren't saved when memory limit is reached. When a database uses replication, this applies to the primary database -* **allkeys-lru**: Keeps most recently used keys; removes least recently used (LRU) keys -* **allkeys-lfu**: Keeps frequently used keys; removes least frequently used (LFU) keys -* **volatile-lru**: Removes least recently used keys with a time-to-live (TTL) set. -* **volatile-lfu**: Removes least frequently used keys with a TTL set. -* **allkeys-random**: Randomly removes keys to make space for the new data added. -* **volatile-random**: Randomly removes keys with a TTL set. -* **volatile-ttl**: Removes keys with a TTL set, the keys with the shortest remaining time-to-live value first. - -The policies **volatile-lru**, **volatile-lfu**, **volatile-random**, and **volatile-ttl** behave like **noeviction** if there are no keys to evict matching the prerequisites. - -**LRU**, **LFU** and **volatile-ttl** are implemented using approximated randomized algorithms. - -Picking the right eviction policy is important depending on the access pattern -of your application, however you can reconfigure the policy at runtime while -the application is running, and monitor the number of cache misses and hits -using the Valkey `INFO` output to tune your setup. - -In general as a rule of thumb: - -* Use the **allkeys-lru** policy when you expect a power-law distribution in the popularity of your requests. That is, you expect a subset of elements will be accessed far more often than the rest. **This is a good pick if you are unsure**. - -* Use the **allkeys-random** if you have a cyclic access where all the keys are scanned continuously, or when you expect the distribution to be uniform. - -* Use the **volatile-ttl** if you want to be able to provide hints to Valkey about what are good candidate for expiration by using different TTL values when you create your cache objects. - -The **volatile-lru** and **volatile-random** policies are mainly useful when you want to use a single instance for both caching and to have a set of persistent keys. However it is usually a better idea to run two Valkey instances to solve such a problem. - -It is also worth noting that setting a TTL value to a key costs memory, so using a policy like **allkeys-lru** is more memory efficient since there is no need for a TTL configuration for the key to be evicted under memory pressure. - -## How the eviction process works - -It is important to understand that the eviction process works like this: - -* A client runs a new command, resulting in more data added. -* Valkey checks the memory usage, and if it is greater than the `maxmemory` limit , it evicts keys according to the policy. -* A new command is executed, and so forth. - -So we continuously cross the boundaries of the memory limit, by going over it, and then by evicting keys to return back under the limits. - -If a command results in a lot of memory being used (like a big set intersection stored into a new key) for some time, the memory limit can be surpassed by a noticeable amount. - -## Monitor eviction - -To monitor the point when Valkey starts to evict data, use the `INFO MEMORY` command. The following fields provide the information about the memory usage and the condition to trigger key eviction: - -* `used_memory`: The total number of bytes that the server allocated for storing data. It is the sum of the `used_memory_overhead` and the `used_memory_dataset` outputs. -* `mem_not_counted_for_evict`: The amount of memory not counted for eviction. This includes the replication buffer and AOF buffer. - -Thus, the memory usage to trigger eviction is calculated as follows: - -``` -used_memory - mem_not_counted_for_evict > maxmemory -``` - -Let's see how this works in practice. - -Consider the following INFO memory output: - -``` -# Memory -used_memory:12498952 -... -maxmemory:10737418240 -... -mem_not_counted_for_evict:12336 -... -``` - -In this example, Valkey will not start data eviction because the actual memory usage is `12498952 - 12336 = 12486616` which is considerably less than `maxmemory`. - -The following example shows that we're nearing eviction: - -``` -# Memory -used_memory:12498952 -... -maxmemory:12500000 -... -mem_not_counted_for_evict:12336 -``` - -Once eviction happens, additional information is available through the `INFO STATS` metrics. The `total_eviction_exceeded_time` metric shows the total time in milliseconds that `used_memory` exceeded `maxmemory`. - - -## Approximated LRU algorithm - -Valkey LRU algorithm is not an exact implementation. This means that Valkey is -not able to pick the *best candidate* for eviction, that is, the key that -was accessed the furthest in the past. Instead it will try to run an approximation -of the LRU algorithm, by sampling a small number of keys, and evicting the -one that is the best (with the oldest access time) among the sampled keys, while -also managing a pool of good candidates for eviction. -This algorithm consumes less memory than an exact LRU algorithm. - -What is important about the Valkey LRU algorithm is that you **are able to tune** the precision of the algorithm by changing the number of samples to check for every eviction. This parameter is controlled by the following configuration directive: - - maxmemory-samples 5 - -The reason Valkey does not use a true LRU implementation is because it -costs more memory. However, the approximation is virtually equivalent for an -application using Valkey. This figure compares -the LRU approximation used by Valkey with true LRU. - -![LRU comparison](lru_comparison.png) - -The test to generate the above graphs filled a server with a given number of keys. The keys were accessed from the first to the last. The first keys are the best candidates for eviction using an LRU algorithm. Later more 50% of keys are added, in order to force half of the old keys to be evicted. - -You can see three kind of dots in the graphs, forming three distinct bands. - -* The light gray band are objects that were evicted. -* The gray band are objects that were not evicted. -* The green band are objects that were added. - -In a theoretical LRU implementation we expect that, among the old keys, the first half will be evicted. -The Valkey LRU algorithm will instead only *probabilistically* evicts the older keys. - -As you can see, Redis OSS 3.0 does a reasonable job with 5 samples. -Using a sample size of 10, the approximation is very close to an exact LRU implementation. -(The LRU algorithm hasn't changed considerably since this test was performed, so the performance of Valkey is similar in this regard.) - -Note that LRU is just a model to predict how likely a given key will be accessed in the future. Moreover, if your data access pattern closely -resembles the power law; most of the accesses will be in the set of keys -the LRU approximated algorithm can handle well. - -In simulations we found that using a power law access pattern, the difference between true LRU and Valkey approximation were minimal or non-existent. - -However you can raise the sample size to 10 at the cost of some additional CPU -usage to closely approximate true LRU, and check if this makes a -difference in your cache misses rate. - -To experiment in production with different values for the sample size by using -the `CONFIG SET maxmemory-samples ` command, is very simple. - -## The LFU mode - -The [Least Frequently Used eviction mode](https://web.archive.org/web/20241019222228/http://antirez.com/news/109) is available as an alternative to LRU. -This mode may work better (provide a better -hits/misses ratio) in certain cases. In LFU mode, Valkey will try to track -the frequency of access of items, so the ones used rarely are evicted. This means -the keys used often have a higher chance of remaining in memory. - -To configure the LFU mode, the following policies are available: - -* `volatile-lfu` Evict using approximated LFU among the keys with a time-to-live (TTL) set. -* `allkeys-lfu` Evict any key using approximated LFU. - -LFU is approximated like LRU: it uses a probabilistic counter, called a [Morris counter](https://en.wikipedia.org/wiki/Approximate_counting_algorithm) to estimate the object access frequency using just a few bits per object, combined with a decay period so that the counter is reduced over time. At some point we no longer want to consider keys as frequently accessed, even if they were in the past, so that the algorithm can adapt to a shift in the access pattern. - -That information is sampled similarly to what happens for LRU (as explained in the previous section of this documentation) to select a candidate for eviction. - -However unlike LRU, LFU has certain tunable parameters: for example, how fast -should a frequent item lower in rank if it gets no longer accessed? It is also possible to tune the Morris counters range to better adapt the algorithm to specific use cases. - -By default Valkey is configured to: - -* Saturate the counter at, around, one million requests. -* Decay the counter every one minute. - -Those should be reasonable values and were tested experimentally, but the user may want to play with these configuration settings to pick optimal values. - -Instructions about how to tune these parameters can be found inside the example `valkey.conf` file in the source distribution. Briefly, they are: - -``` -lfu-log-factor 10 -lfu-decay-time 1 -``` - -The decay time is the obvious one, it is the amount of minutes a counter should be decayed, when sampled and found to be older than that value. A special value of `0` means: we will never decay the counter. - -The counter *logarithm factor* changes how many hits are needed to saturate the frequency counter, which is just in the range 0-255. The higher the factor, the more accesses are needed to reach the maximum. The lower the factor, the better is the resolution of the counter for low accesses, according to the following table: - -``` -+--------+------------+------------+------------+------------+------------+ -| factor | 100 hits | 1000 hits | 100K hits | 1M hits | 10M hits | -+--------+------------+------------+------------+------------+------------+ -| 0 | 104 | 255 | 255 | 255 | 255 | -+--------+------------+------------+------------+------------+------------+ -| 1 | 18 | 49 | 255 | 255 | 255 | -+--------+------------+------------+------------+------------+------------+ -| 10 | 10 | 18 | 142 | 255 | 255 | -+--------+------------+------------+------------+------------+------------+ -| 100 | 8 | 11 | 49 | 143 | 255 | -+--------+------------+------------+------------+------------+------------+ -``` - -So basically the factor is a trade off between better distinguishing items with low accesses VS distinguishing items with high accesses. More information is available in the example `valkey.conf` file. diff --git a/topics/lru_comparison.png b/topics/lru_comparison.png deleted file mode 100644 index 8b78b4f9..00000000 Binary files a/topics/lru_comparison.png and /dev/null differ diff --git a/topics/lua-api.md b/topics/lua-api.md deleted file mode 100644 index dd54e96e..00000000 --- a/topics/lua-api.md +++ /dev/null @@ -1,872 +0,0 @@ ---- -title: "Lua API reference" -description: > - Executing Lua in Valkey ---- - -Valkey includes an embedded [Lua 5.1](https://www.lua.org/) interpreter. -The interpreter runs user-defined [ephemeral scripts](eval-intro.md) and [functions](functions-intro.md). Scripts run in a sandboxed context and can only access specific Lua packages. This page describes the packages and APIs available inside the execution's context. - -## Sandbox context - -The sandboxed Lua context attempts to prevent accidental misuse and reduce potential threats from the server's environment. - -Scripts should never try to access the Valkey server's underlying host systems. -That includes the file system, network, and any other attempt to perform a system call other than those supported by the API. - -Scripts should operate solely on data stored in Valkey and data provided as arguments to their execution. - -### Global variables and functions - -The sandboxed Lua execution context blocks the declaration of global variables and functions. -The blocking of global variables is in place to ensure that scripts and functions don't attempt to maintain any runtime context other than the data stored in Valkey. -In the (somewhat uncommon) use case that a context needs to be maintain between executions, -you should store the context in Valkey' keyspace. - -Valkey will return an error when trying to execute the following snippet: - -```lua -my_global_variable = 'some value' -``` - -And similarly for the following global function declaration: - -```lua -function my_global_function() - -- Do something amazing -end -``` - -You'll also get a similar error when your script attempts to access any global variables that are undefined in the runtime's context: - -```lua --- The following will surely raise an error -return an_undefined_global_variable -``` - -Instead, all variable and function definitions are required to be declared as local. -To do so, you'll need to prepend the [`local`](https://www.lua.org/manual/5.1/manual.html#2.4.7) keyword to your declarations. -For example, the following snippet will be considered perfectly valid by Valkey: - -```lua -local my_local_variable = 'some value' - -local function my_local_function() - -- Do something else, but equally amazing -end -``` - -**Note:** -the sandbox attempts to prevent the use of globals. -Using Lua's debugging functionality or other approaches such as altering the meta table used for implementing the globals' protection to circumvent the sandbox isn't hard. -However, it is difficult to circumvent the protection by accident. -If the user messes with the Lua global state, the consistency of AOF and replication can't be guaranteed. -In other words, just don't do it. - -### Imported Lua modules - -Using imported Lua modules is not supported inside the sandboxed execution context. -The sandboxed execution context prevents the loading modules by disabling Lua's [`require` function](https://www.lua.org/pil/8.1.html). - -The only libraries that Valkey ships with and that you can use in scripts are listed under the [Runtime libraries](#runtime-libraries) section. - -## Runtime globals - -While the sandbox prevents users from declaring globals, the execution context is pre-populated with several of these. - -For some of them, a "since version" is specified. -The ones without "since version" specified are available in all maintained versions. - -### The `KEYS` global variable - -* Available in scripts: yes -* Available in functions: no - -**Important:** -to ensure the correct execution of scripts, both in standalone and clustered deployments, all names of keys that a function accesses must be explicitly provided as input key arguments. -The script **should only** access keys whose names are given as input arguments. -Scripts **should never** access keys with programmatically-generated names or based on the contents of data structures stored in the database. - -The `KEYS` global variable is available only for [ephemeral scripts](eval-intro.md). -It is pre-populated with all key name input arguments. - -### The `ARGV` global variable - -* Available in scripts: yes -* Available in functions: no - -The `ARGV` global variable is available only in [ephemeral scripts](eval-intro.md). -It is pre-populated with all regular input arguments. - -### The `server` singleton - -* Since version: 7.2.5 -* Available in scripts: yes -* Available in functions: yes - -The `server` singleton is an object instance that's accessible from all scripts. -It provides the API to interact with Valkey from scripts. -Following is the API provided by the `server` object instance. - -**Note:** -For compatibility with Redis, Valkey also exposes a `redis` top-level object, that exposes the exact same set of APIs as the `server` object. -Valkey does not intend to drop compatibility for this `redis` API, but it is recommended to use the `server` object for newly developed scripts. - -## `server` object fields (functions and variables) - -### `server.call(command [,arg...])` - -* Available in scripts: yes -* Available in functions: yes - -The `server.call()` function calls a given Valkey command and returns its reply. -Its inputs are the command and arguments, and once called, it executes the command in Valkey and returns the reply. - -For example, we can call the `ECHO` command from a script and return its reply like so: - -```lua -return server.call('ECHO', 'Echo, echo... eco... o...') -``` - -If and when `server.call()` triggers a runtime exception, the raw exception is raised back to the user as an error, automatically. -Therefore, attempting to execute the following ephemeral script will fail and generate a runtime exception because `ECHO` accepts exactly one argument: - -```lua -127.0.0.1:6379> EVAL "return server.call('ECHO', 'Echo,', 'echo... ', 'eco... ', 'o...')" 0 -(error) ERR Wrong number of args calling Valkey command from script script: b0345693f4b77517a711221050e76d24ae60b7f7, on @user_script:1. -``` - -Note that the call can fail due to various reasons, see [Execution under low memory conditions](eval-intro.md#execution-under-low-memory-conditions) and [Script flags](#script_flags) - -To handle Valkey runtime errors use `server.pcall()` instead. - -### `server.pcall(command [,arg...])` - -* Available in scripts: yes -* Available in functions: yes - -This function enables handling runtime errors raised by the Valkey server. -The `server.pcall()` function behaves exactly like [`server.call()`](#server.call), except that it: - -* Always returns a reply. -* Never throws a runtime exception, and returns in its stead a [`server.error_reply`](#server.error_reply) in case that a runtime exception is thrown by the server. - -The following demonstrates how to use `server.pcall()` to intercept and handle runtime exceptions from within the context of an ephemeral script. - -```lua -local reply = server.pcall('ECHO', unpack(ARGV)) -if reply['err'] ~= nil then - -- Handle the error sometime, but for now just log it - server.log(server.LOG_WARNING, reply['err']) - reply['err'] = 'ERR Something is wrong, but no worries, everything is under control' -end -return reply -``` - -Evaluating this script with more than one argument will return: - -``` -127.0.0.1:6379> EVAL "..." 0 hello world -(error) ERR Something is wrong, but no worries, everything is under control -``` - -### `server.error_reply(x)` - -* Available in scripts: yes -* Available in functions: yes - -This is a helper function that returns an [error reply](protocol.md#simple-errors). -The helper accepts a single string argument and returns a Lua table with the `err` field set to that string. - -The outcome of the following code is that `error1` and `error2` are identical for all intents and purposes: - -```lua -local text = 'ERR My very special error' -local reply1 = { err = text } -local reply2 = server.error_reply(text) -``` - -Therefore, both forms are valid as means for returning an error reply from scripts: - -``` -127.0.0.1:6379> EVAL "return { err = 'ERR My very special table error' }" 0 -(error) ERR My very special table error -127.0.0.1:6379> EVAL "return server.error_reply('ERR My very special reply error')" 0 -(error) ERR My very special reply error -``` - -For returning Valkey status replies refer to [`server.status_reply()`](#server.status_reply). -Refer to the [Data type conversion](#data-type-conversion) for returning other response types. - -**Note:** -By convention, Valkey uses the first word of an error string as a unique error code for specific errors or `ERR` for general-purpose errors. -Scripts are advised to follow this convention, as shown in the example above, but this is not mandatory. - -### `server.status_reply(x)` - -* Available in scripts: yes -* Available in functions: yes - -This is a helper function that returns a [simple string reply](protocol.md#simple-strings). -"OK" is an example of a standard Valkey status reply. -The Lua API represents status replies as tables with a single field, `ok`, set with a simple status string. - -The outcome of the following code is that `status1` and `status2` are identical for all intents and purposes: - -```lua -local text = 'Frosty' -local status1 = { ok = text } -local status2 = server.status_reply(text) -``` - -Therefore, both forms are valid as means for returning status replies from scripts: - -``` -127.0.0.1:6379> EVAL "return { ok = 'TICK' }" 0 -TICK -127.0.0.1:6379> EVAL "return server.status_reply('TOCK')" 0 -TOCK -``` - -For returning Valkey error replies refer to [`server.error_reply()`](#server.error_reply). -Refer to the [Data type conversion](#data-type-conversion) for returning other response types. - -### `server.sha1hex(x)` - -* Available in scripts: yes -* Available in functions: yes - -This function returns the SHA1 hexadecimal digest of its single string argument. - -You can, for example, obtain the empty string's SHA1 digest: - -``` -127.0.0.1:6379> EVAL "return server.sha1hex('')" 0 -"da39a3ee5e6b4b0d3255bfef95601890afd80709" -``` - -### `server.log(level, message)` - -* Available in scripts: yes -* Available in functions: yes - -This function writes to the Valkey server log. - -It expects two input arguments: the log level and a message. -The message is a string to write to the log file. -Log level can be on of these: - -* `server.LOG_DEBUG` -* `server.LOG_VERBOSE` -* `server.LOG_NOTICE` -* `server.LOG_WARNING` - -These levels map to the server's log levels. -The log only records messages equal or greater in level than the server's `loglevel` configuration directive. - -The following snippet: - -```lua -server.log(server.LOG_WARNING, 'Something is terribly wrong') -``` - -will produce a line similar to the following in your server's log: - -``` -[32343] 22 Mar 15:21:39 # Something is terribly wrong -``` - -### `server.setresp(x)` - -* Available in scripts: yes -* Available in functions: yes - -This function allows the executing script to switch between [RESP](protocol.md) protocol versions for the replies returned by [`server.call()`](#server.call) and [`server.pcall()`](#server.pcall). -It expects a single numerical argument as the protocol's version. -The default protocol version is _2_, but it can be switched to version _3_. - -Here's an example of switching to RESP3 replies: - -```lua -server.setresp(3) -``` - -Please refer to the [Data type conversion](#data-type-conversion) for more information about type conversions. - -### `server.set_repl(x)` - -* Available in scripts: yes -* Available in functions: no - -**Note:** -Prior to Redis OSS 7.0, scripts were replicated verbatim by default. -Since Redis OSS 7.0 (and Valkey), script effects replication is the only replication mode available. - -The `server.set_repl()` function instructs the server how to treat subsequent write commands in terms of replication. -It accepts a single input argument that only be one of the following: - -* `server.REPL_ALL`: replicates the effects to the AOF and replicas. -* `server.REPL_AOF`: replicates the effects to the AOF alone. -* `server.REPL_REPLICA`: replicates the effects to the replicas alone. -* `server.REPL_SLAVE`: same as `REPL_REPLICA`, maintained for backward compatibility. -* `server.REPL_NONE`: disables effect replication entirely. - -By default, the scripting engine is initialized to the `server.REPL_ALL` setting when a script begins its execution. -You can call the `server.set_repl()` function at any time during the script's execution to switch between the different replication modes. - -A simple example follows: - -```lua -server.replicate_commands() -- Enable effects replication in versions lower than Redis OSS v7.0 -server.call('SET', KEYS[1], ARGV[1]) -server.set_repl(server.REPL_NONE) -server.call('SET', KEYS[2], ARGV[2]) -server.set_repl(server.REPL_ALL) -server.call('SET', KEYS[3], ARGV[3]) -``` - -If you run this script by calling `EVAL "..." 3 A B C 1 2 3`, the result will be that only the keys _A_ and _C_ are created on the replicas and AOF. - -### `server.replicate_commands()` - -* Until version: 7.0.0 -* Available in scripts: yes -* Available in functions: no - -This function switches the script's replication mode from verbatim replication to effects replication. -You can use it to override the default verbatim script replication mode used by Redis OSS until version 7.0. - -**Note:** -Verbatim script replication is no longer supported. -The only script replication mode supported is script effects' replication. -For more information, please refer to [Script replication](eval-intro.md#script-replication) - -### `server.breakpoint()` - -* Available in scripts: yes -* Available in functions: no - -This function triggers a breakpoint when using the [Valkey Lua debugger](ldb.md). - -### `server.debug(x)` - -* Available in scripts: yes -* Available in functions: no - -This function prints its argument in the [Valkey Lua debugger](ldb.md) console. - -### `server.acl_check_cmd(command [,arg...])` - -* Since version: 7.0.0 -* Available in scripts: yes -* Available in functions: yes - -This function is used for checking if the current user running the script has [ACL](acl.md) permissions to execute the given command with the given arguments. - -The return value is a boolean `true` in case the current user has permissions to execute the command (via a call to [server.call](#server.call) or [server.pcall](#server.pcall)) or `false` in case they don't. - -The function will raise an error if the passed command or its arguments are invalid. - -### `server.register_function` - -* Since version: 7.0.0 -* Available in scripts: no -* Available in functions: yes - -This function is only available from the context of the `FUNCTION LOAD` command. -When called, it registers a function to the loaded library. -The function can be called either with positional or named arguments. - -#### positional arguments: `server.register_function(name, callback)` - -The first argument to `server.register_function` is a Lua string representing the function name. -The second argument to `server.register_function` is a Lua function. - -Usage example: - -``` -127.0.0.1:6379> FUNCTION LOAD "#!lua name=mylib\n server.register_function('noop', function() end)" -``` - -#### Named arguments: `server.register_function{function_name=name, callback=callback, flags={flag1, flag2, ..}, description=description}` - -The named arguments variant accepts the following arguments: - -* _function\_name_: the function's name. -* _callback_: the function's callback. -* _flags_: an array of strings, each a function flag (optional). -* _description_: function's description (optional). - -Both _function\_name_ and _callback_ are mandatory. - -Usage example: - -``` -127.0.0.1:6379> FUNCTION LOAD "#!lua name=mylib\n server.register_function{function_name='noop', callback=function() end, flags={ 'no-writes' }, description='Does nothing'}" -``` - -#### Script flags - -**Important:** -Use script flags with care, which may negatively impact if misused. -Note that the default for Eval scripts are different than the default for functions that are mentioned below, see [Eval Flags](eval-intro.md#eval-flags) - -When you register a function or load an Eval script, the server does not know how it accesses the database. -By default, Valkey assumes that all scripts read and write data. -This results in the following behavior: - -1. They can read and write data. -1. They can run in cluster mode, and are not able to run commands accessing keys of different hash slots. -1. Execution against a stale replica is denied to avoid inconsistent reads. -1. Execution under low memory is denied to avoid exceeding the configured threshold. - -You can use the following flags and instruct the server to treat the scripts' execution differently: - -* `no-writes`: this flag indicates that the script only reads data but never writes. - - By default, Valkey will deny the execution of flagged scripts (Functions and Eval scripts with [shebang](eval-intro.md#eval-flags)) against read-only replicas, as they may attempt to perform writes. - Similarly, the server will not allow calling scripts with `FCALL_RO` / `EVAL_RO`. - Lastly, when data persistence is at risk due to a disk error, execution is blocked as well. - - Using this flag allows executing the script: - 1. With `FCALL_RO` / `EVAL_RO` - 2. On read-only replicas. - 3. Even if there's a disk error (Valkey is unable to persist so it rejects writes). - 4. When over the memory limit since it implies the script doesn't increase memory consumption (see `allow-oom` below) - - However, note that the server will return an error if the script attempts to call a write command. - Also note that currently `PUBLISH`, `SPUBLISH` and `PFCOUNT` are also considered write commands in scripts, because they could attempt to propagate commands to replicas and AOF file. - - For more information please refer to [Read-only scripts](programmability.md#read-only-scripts) - -* `allow-oom`: use this flag to allow a script to execute when the server is out of memory (OOM). - - Unless used, Valkey will deny the execution of flagged scripts (Functions and Eval scripts with [shebang](eval-intro.md#eval-flags)) when in an OOM state. - Furthermore, when you use this flag, the script can call any Valkey command, including commands that aren't usually allowed in this state. - Specifying `no-writes` or using `FCALL_RO` / `EVAL_RO` also implies the script can run in OOM state (without specifying `allow-oom`) - -* `allow-stale`: a flag that enables running the flagged scripts (Functions and Eval scripts with [shebang](eval-intro.md#eval-flags)) against a stale replica when the `replica-serve-stale-data` config is set to `no` . - - Valkey can be set to prevent data consistency problems from using old data by having stale replicas return a runtime error. - For scripts that do not access the data, this flag can be set to allow stale Valkey replicas to run the script. - Note however that the script will still be unable to execute any command that accesses stale data. - -* `no-cluster`: the flag causes the script to return an error in Valkey cluster mode. - - Valkey allows scripts to be executed both in standalone and cluster modes. - Setting this flag prevents executing the script against nodes in the cluster. - -* `allow-cross-slot-keys`: The flag that allows a script to access keys from multiple slots. - - Valkey typically prevents any single command from accessing keys that hash to multiple slots. - This flag allows scripts to break this rule and access keys within the script that access multiple slots. - Declared keys to the script are still always required to hash to a single slot. - Accessing keys from multiple slots is discouraged as applications should be designed to only access keys from a single slot at a time, allowing slots to move between Valkey servers. - - This flag has no effect when cluster mode is disabled. - -Please refer to [Function Flags](functions-intro.md#function-flags) and [Eval Flags](eval-intro.md#eval-flags) for a detailed example. - -### `server.SERVER_VERSION` - -* Since version: 7.2.5 -* Available in scripts: yes -* Available in functions: yes - -Returns the current Valkey server version as a Lua string. -The reply's format is `MM.mm.PP`, where: - -* **MM:** is the major version. -* **mm:** is the minor version. -* **PP:** is the patch level. - -### `server.REDIS_VERSION` - -* Since version: 7.0.0 -* Available in scripts: yes -* Available in functions: yes - -Returns the current Redis compatibility version as a Lua string. -The reply's format is `MM.mm.PP`, where: - -* **MM:** is the major version. -* **mm:** is the minor version. -* **PP:** is the patch level. - -### `server.SERVER_VERSION_NUM` - -* Since version: 7.2.5 -* Available in scripts: yes -* Available in functions: yes - -Returns the current Valkey server version as a number. -The reply is a hexadecimal value structured as `0x00MMmmPP`, where: - -* **MM:** is the major version. -* **mm:** is the minor version. -* **PP:** is the patch level. - -### `server.REDIS_VERSION_NUM` - -* Since version: 7.0.0 -* Available in scripts: yes -* Available in functions: yes - -Returns the current Redis compatibility version as a number. -The reply is a hexadecimal value structured as `0x00MMmmPP`, where: - -* **MM:** is the major version. -* **mm:** is the minor version. -* **PP:** is the patch level. - -## Data type conversion - -Unless a runtime exception is raised, `server.call()` and `server.pcall()` return the reply from the executed command to the Lua script. -Valkey's replies from these functions are converted automatically into Lua's native data types. - -Similarly, when a Lua script returns a reply with the `return` keyword, -that reply is automatically converted to RESP protocol. - -Put differently: There's a one-to-one mapping between Valkey's replies and Lua's data types and a one-to-one mapping between Lua's data types and the [RESP Protocol](protocol.md) data types. -The underlying design is such that if a RESP type is converted into a Lua type and converted back into a RESP type, the result is the same as the initial value. - -Type conversion from Valkey replies (i.e. the replies from `server.call()` and `server.pcall()`) to Lua data types depends on the RESP protocol version used by the script. -The default protocol version during script executions is RESP2. -The script may switch the replies' protocol versions by calling the `server.setresp()` function. - -Type conversion from a script's returned Lua data type depends on the user's choice of protocol (see the `HELLO` command). - -The following sections describe the type conversion rules between Lua and Valkey per the protocol's version. - -### RESP2 to Lua type conversion - -The following type conversion rules apply to the execution's context by default as well as after calling `server.setresp(2)`: - -* [RESP2 integer reply](protocol.md#integers) -> Lua number -* [RESP2 bulk string reply](protocol.md#bulk-strings) -> Lua string -* [RESP2 array reply](protocol.md#arrays) -> Lua table (may have other Valkey data types nested) -* [RESP2 status reply](protocol.md#simple-strings) -> Lua table with a single _ok_ field containing the status string -* [RESP2 error reply](protocol.md#simple-errors) -> Lua table with a single _err_ field containing the error string -* [RESP2 null bulk reply and null multi bulk reply](protocol.md#nulls) -> Lua false boolean type - -## Lua to RESP2 type conversion - -The following type conversion rules apply by default as well as after the user had called `HELLO 2`: - -* Lua number -> [RESP2 integer reply](protocol.md#integers) (the number is converted into an integer) -* Lua string -> [RESP bulk string reply](protocol.md#bulk-strings) -* Lua table (indexed, non-associative array) -> [RESP2 array reply](protocol.md#arrays) (truncated at the first Lua `nil` value encountered in the table, if any) -* Lua table with a single _ok_ field -> [RESP2 status reply](protocol.md#simple-strings) -* Lua table with a single _err_ field -> [RESP2 error reply](protocol.md#simple-errors) -* Lua boolean false -> [RESP2 null bulk reply](protocol.md#nulls) - -There is an additional Lua-to-Valkey conversion rule that has no corresponding Valkey-to-Lua conversion rule: - -* Lua Boolean `true` -> [RESP2 integer reply](protocol.md#integers) with value of 1. - -There are three additional rules to note about converting Lua to Valkey data types: - -* Lua has a single numerical type, Lua numbers. - There is no distinction between integers and floats. - So we always convert Lua numbers into integer replies, removing the decimal part of the number, if any. - **If you want to return a Lua float, it should be returned as a string**, - exactly like Valkey itself does (see, for instance, the `ZSCORE` command). -* There's [no simple way to have nils inside Lua arrays](https://www.lua.org/pil/19.1.html) due - to Lua's table semantics. - Therefore, when Valkey converts a Lua array to RESP, the conversion stops when it encounters a Lua `nil` value. -* When a Lua table is an associative array that contains keys and their respective values, the converted Valkey reply will **not** include them. - -Lua to RESP2 type conversion examples: - -``` -127.0.0.1:6379> EVAL "return 10" 0 -(integer) 10 - -127.0.0.1:6379> EVAL "return { 1, 2, { 3, 'Hello World!' } }" 0 -1) (integer) 1 -2) (integer) 2 -3) 1) (integer) 3 - 1) "Hello World!" - -127.0.0.1:6379> EVAL "return server.call('get','foo')" 0 -"bar" -``` - -The last example demonstrates receiving and returning the exact return value of `server.call()` (or `server.pcall()`) in Lua as it would be returned if the command had been called directly. - -The following example shows how floats and arrays that cont nils and keys are handled: - -``` -127.0.0.1:6379> EVAL "return { 1, 2, 3.3333, somekey = 'somevalue', 'foo', nil , 'bar' }" 0 -1) (integer) 1 -2) (integer) 2 -3) (integer) 3 -4) "foo" -``` - -As you can see, the float value of _3.333_ gets converted to an integer _3_, the _somekey_ key and its value are omitted, and the string "bar" isn't returned as there is a `nil` value that precedes it. - -### RESP3 to Lua type conversion - -RESP3 is a newer version of the [protocol](protocol.md) used by Valkey. -It is available as an opt-in choice. - -An executing script may call the [`server.setresp`](#server.setresp) function during its execution and switch the protocol version that's used for returning replies from Valkey's commands (that can be invoked via [`server.call()`](#server.call) or [`server.pcall()`](#server.pcall)). - -Once Valkey's replies are in RESP3 protocol, all of the [RESP2 to Lua conversion](#resp2-to-lua-type-conversion) rules apply, with the following additions: - -* [Map reply](protocol.md#maps) -> Lua table with a single _map_ field containing a Lua table representing the fields and values of the map. -* [Set reply](protocol.md#sets) -> Lua table with a single _set_ field containing a Lua table representing the elements of the set as fields, each with the Lua Boolean value of `true`. -* [Null](protocol.md#nulls) -> Lua `nil`. -* [True reply](protocol.md#booleans) -> Lua true boolean value. -* [False reply](protocol.md#booleans) -> Lua false boolean value. -* [Double reply](protocol.md#doubles) -> Lua table with a single `double` field containing a Lua number representing the double value. -* [Big number reply](protocol.md#big-numbers) -> Lua table with a single `big_number` field containing a Lua string representing the big number value (since Redis OSS 7.0). -* [Verbatim string reply](protocol.md#verbatim-strings) -> Lua table with a single `verbatim_string` field containing a Lua table with two fields, `string` and `format`, representing the verbatim string and its format, respectively (since Redis OSS 7.0). - -### Lua to RESP3 type conversion - -Regardless of the script's choice of protocol version set for replies with the [`server.setresp()` function] when it calls `server.call()` or `server.pcall()`, the user may opt-in to using RESP3 (with the `HELLO 3` command) for the connection. -Although the default protocol for incoming client connections is RESP2, the script should honor the user's preference and return adequately-typed RESP3 replies, so the following rules apply on top of those specified in the [Lua to RESP2 type conversion](#lua-to-resp2-type-conversion) section when that is the case. - -* Lua Boolean -> [RESP3 Boolean reply](protocol.md#booleans) (note that this is a change compared to the RESP2, in which returning a Boolean Lua `true` returned the number 1 to the Valkey client, and returning a `false` used to return a `null`. -* Lua table with a single `map` field set to an associative Lua table -> [RESP3 map reply](protocol.md#maps). -* Lua table with a single `set` field set to an associative Lua table -> [RESP3 set reply](protocol.md#sets). Values can be set to anything and are discarded anyway. -* Lua table with a single `double` field to an associative Lua table -> [RESP3 double reply](protocol.md#doubles). -* Lua nil -> [RESP3 null](protocol.md#nulls). - -However, if the connection is set use the RESP2 protocol, and even if the script replies with RESP3-typed responses, Valkey will automatically perform a RESP3 to RESP2 conversion of the reply as is the case for regular commands. -That means, for example, that returning the RESP3 map type to a RESP2 connection will result in the reply being converted to a flat RESP2 array that consists of alternating field names and their values, rather than a RESP3 map. - -## Additional notes about scripting - -### Using `SELECT` inside scripts - -You can call the `SELECT` command from your Lua scripts, like you can with any normal client connection. -The database selected by the Lua script only affects the execution context of the script, and does not modify the database that's selected by the client calling the script. - -## Runtime libraries - -The Valkey Lua runtime context always comes with several pre-imported libraries. - -The following [standard Lua libraries](https://www.lua.org/manual/5.1/manual.html#5) are available to use: - -* The [_String Manipulation (string)_ library](https://www.lua.org/manual/5.1/manual.html#5.4) -* The [_Table Manipulation (table)_ library](https://www.lua.org/manual/5.1/manual.html#5.5) -* The [_Mathematical Functions (math)_ library](https://www.lua.org/manual/5.1/manual.html#5.6) -* The [_Operating System Facilities (os)_ library](#os-library) - -In addition, the following external libraries are loaded and accessible to scripts: - -* The [_struct_ library](#struct-library) -* The [_cjson_ library](#cjson-library) -* The [_cmsgpack_ library](#cmsgpack-library) -* The [_bitop_ library](#bitop-library) - -### _os_ library - -* Since version: 8.0.0 -* Available in scripts: yes -* Available in functions: yes - -_os_ provides a set of functions for dealing with date, time, and system commands. -More details can be found in the [Operating System Facilities](https://www.lua.org/manual/5.1/manual.html#5.8). -Note that for sandbox security, currently only the following os functions is exposed: - -* `os.clock()` - -### _struct_ library - -* Available in scripts: yes -* Available in functions: yes - -_struct_ is a library for packing and unpacking C-like structures in Lua. -It provides the following functions: - -* [`struct.pack()`](#struct.pack) -* [`struct.unpack()`](#struct.unpack) -* [`struct.size()`](#struct.size) - -All of _struct_'s functions expect their first argument to be a [format string](#struct-formats). - -#### _struct_ formats - -The following are valid format strings for _struct_'s functions: - -* `>`: big endian -* `<`: little endian -* `![num]`: alignment -* `x`: padding -* `b/B`: signed/unsigned byte -* `h/H`: signed/unsigned short -* `l/L`: signed/unsigned long -* `T`: size_t -* `i/In`: signed/unsigned integer with size _n_ (defaults to the size of int) -* `cn`: sequence of _n_ chars (from/to a string); when packing, n == 0 means the - whole string; when unpacking, n == 0 means use the previously read number as - the string's length. -* `s`: zero-terminated string -* `f`: float -* `d`: double -* ` ` (space): ignored - -#### `struct.pack(x)` - -This function returns a struct-encoded string from values. -It accepts a [_struct_ format string](#struct-formats) as its first argument, followed by the values that are to be encoded. - -Usage example: - -``` -127.0.0.1:6379> EVAL "return struct.pack('HH', 1, 2)" 0 -"\x01\x00\x02\x00" -``` - -#### `struct.unpack(x)` - -This function returns the decoded values from a struct. -It accepts a [_struct_ format string](#struct-formats) as its first argument, followed by encoded struct's string. - -Usage example: - -``` -127.0.0.1:6379> EVAL "return { struct.unpack('HH', ARGV[1]) }" 0 "\x01\x00\x02\x00" -1) (integer) 1 -2) (integer) 2 -3) (integer) 5 -``` - -#### `struct.size(x)` - -This function returns the size, in bytes, of a struct. -It accepts a [_struct_ format string](#struct-formats) as its only argument. - -Usage example: - -``` -127.0.0.1:6379> EVAL "return struct.size('HH')" 0 -(integer) 4 -``` - -### _cjson_ library - -* Available in scripts: yes -* Available in functions: yes - -The _cjson_ library provides fast [JSON](https://json.org) encoding and decoding from Lua. -It provides these functions. - -#### `cjson.encode(x)` - -This function returns a JSON-encoded string for the Lua data type provided as its argument. - -Usage example: - -``` -127.0.0.1:6379> EVAL "return cjson.encode({ ['foo'] = 'bar' })" 0 -"{\"foo\":\"bar\"}" -``` - -#### `cjson.decode(x)` - -This function returns a Lua data type from the JSON-encoded string provided as its argument. - -Usage example: - -``` -127.0.0.1:6379> EVAL "return cjson.decode(ARGV[1])['foo']" 0 '{"foo":"bar"}' -"bar" -``` - -### _cmsgpack_ library - -* Available in scripts: yes -* Available in functions: yes - -The _cmsgpack_ library provides fast [MessagePack](https://msgpack.org/index.html) encoding and decoding from Lua. -It provides these functions. - -#### `cmsgpack.pack(x)` - -This function returns the packed string encoding of the Lua data type it is given as an argument. - -Usage example: - -``` -127.0.0.1:6379> EVAL "return cmsgpack.pack({'foo', 'bar', 'baz'})" 0 -"\x93\xa3foo\xa3bar\xa3baz" -``` - -#### `cmsgpack.unpack(x)` - -This function returns the unpacked values from decoding its input string argument. - -Usage example: - -``` -127.0.0.1:6379> EVAL "return cmsgpack.unpack(ARGV[1])" 0 "\x93\xa3foo\xa3bar\xa3baz" -1) "foo" -2) "bar" -3) "baz" -``` - -### _bit_ library - -* Available in scripts: yes -* Available in functions: yes - -The _bit_ library provides bitwise operations on numbers. -Its documentation resides at [Lua BitOp documentation](https://bitop.luajit.org/api.html) -It provides the following functions. - -#### `bit.tobit(x)` - -Normalizes a number to the numeric range for bit operations and returns it. - -Usage example: - -``` -127.0.0.1:6379> EVAL 'return bit.tobit(1)' 0 -(integer) 1 -``` - -#### `bit.tohex(x [,n])` - -Converts its first argument to a hex string. The number of hex digits is given by the absolute value of the optional second argument. - -Usage example: - -``` -127.0.0.1:6379> EVAL 'return bit.tohex(422342)' 0 -"000671c6" -``` - -#### `bit.bnot(x)` - -Returns the bitwise **not** of its argument. - -#### `bit.bnot(x)` `bit.bor(x1 [,x2...])`, `bit.band(x1 [,x2...])` and `bit.bxor(x1 [,x2...])` - -Returns either the bitwise **or**, bitwise **and**, or bitwise **xor** of all of its arguments. -Note that more than two arguments are allowed. - -Usage example: - -``` -127.0.0.1:6379> EVAL 'return bit.bor(1,2,4,8,16,32,64,128)' 0 -(integer) 255 -``` - -#### `bit.lshift(x, n)`, `bit.rshift(x, n)` and `bit.arshift(x, n)` - -Returns either the bitwise logical **left-shift**, bitwise logical **right-shift**, or bitwise **arithmetic right-shift** of its first argument by the number of bits given by the second argument. - -#### `bit.rol(x, n)` and `bit.ror(x, n)` - -Returns either the bitwise **left rotation**, or bitwise **right rotation** of its first argument by the number of bits given by the second argument. -Bits shifted out on one side are shifted back in on the other side. - -#### `bit.bswap(x)` - -Swaps the bytes of its argument and returns it. -This can be used to convert little-endian 32-bit numbers to big-endian 32-bit numbers and vice versa. diff --git a/topics/mass-insertion.md b/topics/mass-insertion.md deleted file mode 100644 index 0c1bef7a..00000000 --- a/topics/mass-insertion.md +++ /dev/null @@ -1,147 +0,0 @@ ---- -title: "Bulk loading" -description: > - Writing data in bulk using the RESP protocol ---- - -Bulk loading is the process of loading Valkey with a large amount of pre-existing data. Ideally, you want to perform this operation quickly and efficiently. This document describes some strategies for bulk loading data in Valkey. - -## Bulk loading using the RESP protocol - -Using a normal Valkey client to perform bulk loading is not a good idea -for a few reasons: the naive approach of sending one command after the other -is slow because you have to pay for the round trip time for every command. -It is possible to use pipelining, but for bulk loading of many records -you need to write new commands while you read replies at the same time to -make sure you are inserting as fast as possible. - -Only a small percentage of clients support non-blocking I/O, and not all the -clients are able to parse the replies in an efficient way in order to maximize -throughput. For all of these reasons the preferred way to mass import data into -Valkey is to generate a text file containing the Valkey protocol, in raw format, -in order to call the commands needed to insert the required data. - -For instance if I need to generate a large data set where there are billions -of keys in the form: `keyN -> ValueN' I will create a file containing the -following commands in the Valkey protocol format: - - SET Key0 Value0 - SET Key1 Value1 - ... - SET KeyN ValueN - -Once this file is created, the remaining action is to feed it to Valkey -as fast as possible. In the past the way to do this was to use the -`netcat` with the following command: - - (cat data.txt; sleep 10) | nc localhost 6379 > /dev/null - -However this is not a very reliable way to perform mass import because netcat -does not really know when all the data was transferred and can't check for -errors. The `valkey-cli` utility -supports a **pipe mode** that was designed to perform -bulk loading. - -Using the pipe mode the command to run looks like the following: - - cat data.txt | valkey-cli --pipe - -That will produce an output similar to this: - - All data transferred. Waiting for the last reply... - Last reply received from server. - errors: 0, replies: 1000000 - -The valkey-cli utility will also make sure to only redirect errors received -from the Valkey instance to the standard output. - -### Generating RESP protocol - -The RESP protocol is extremely simple to generate and parse, and is -[Documented here](protocol.md). However in order to generate protocol for -the goal of bulk loading you don't need to understand every detail of the -protocol, but just that every command is represented in the following way: - - * - $ - - - ... - - -Where `` means "\r" (or ASCII character 13) and `` means "\n" (or ASCII character 10). - -For instance the command **SET key value** is represented by the following protocol: - - *3 - $3 - SET - $3 - key - $5 - value - -Or represented as a quoted string: - - "*3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$5\r\nvalue\r\n" - -The file you need to generate for bulk loading is just composed of commands -represented in the above way, one after the other. - -The following Ruby function generates valid protocol: - -```ruby -def gen_redis_proto(*cmd) - proto = "" - proto << "*"+cmd.length.to_s+"\r\n" - cmd.each{|arg| - proto << "$"+arg.to_s.bytesize.to_s+"\r\n" - proto << arg.to_s+"\r\n" - } - proto -end - -puts gen_redis_proto("SET","mykey","Hello World!").inspect -``` - -Using the above function it is possible to easily generate the key value pairs -in the above example, with this program: - -```ruby -(0...1000).each{|n| - STDOUT.write(gen_redis_proto("SET","Key#{n}","Value#{n}")) -} -``` - -We can run the program directly in pipe to valkey-cli in order to perform our -first mass import session. - - $ ruby proto.rb | valkey-cli --pipe - All data transferred. Waiting for the last reply... - Last reply received from server. - errors: 0, replies: 1000 - -### How the pipe mode works under the hood - -The magic needed inside the pipe mode of valkey-cli is to be as fast as netcat -and still be able to understand when the last reply was sent by the server -at the same time. - -This is obtained in the following way: - -+ valkey-cli --pipe tries to send data as fast as possible to the server. -+ At the same time it reads data when available, trying to parse it. -+ Once there is no more data to read from stdin, it sends a special **ECHO** -command with a random 20 byte string: we are sure this is the latest command -sent, and we are sure we can match the reply checking if we receive the same -20 bytes as a bulk reply. -+ Once this special final command is sent, the code receiving replies starts -to match replies with these 20 bytes. When the matching reply is reached it -can exit with success. - -Using this trick we don't need to parse the protocol we send to the server -in order to understand how many commands we are sending, but just the replies. - -However while parsing the replies we take a counter of all the replies parsed -so that at the end we are able to tell the user the amount of commands -transferred to the server by the mass insert session. diff --git a/topics/memory-optimization.md b/topics/memory-optimization.md deleted file mode 100644 index c18ee4ec..00000000 --- a/topics/memory-optimization.md +++ /dev/null @@ -1,187 +0,0 @@ ---- -title: Memory optimization -description: Strategies for optimizing memory usage in Valkey ---- - -## Special encoding of small aggregate data types - -Many data types are optimized to use less space up to a certain size. -Hashes, Lists, Sets composed of just integers, and Sorted Sets, when smaller than a given number of elements, and up to a maximum element size, are encoded in a very memory-efficient way that uses *up to 10 times less memory* (with 5 times less memory used being the average saving). - -This is completely transparent from the point of view of the user and API. -Since this is a CPU / memory tradeoff it is possible to tune the maximum -number of elements and maximum element size for special encoded types -using the following valkey.conf directives (defaults for Valkey 7.2 are shown): - -``` -hash-max-listpack-entries 512 -hash-max-listpack-value 64 -zset-max-listpack-entries 128 -zset-max-listpack-value 64 -set-max-intset-entries 512 -set-max-listpack-entries 128 -set-max-listpack-value 64 -``` - -If a specially encoded value overflows the configured max size, -Valkey will automatically convert it into normal encoding. -This operation is very fast for small values, -but if you change the setting in order to use specially encoded values -for much larger aggregate types the suggestion is to run some -benchmarks and tests to check the conversion time. - -## Using 32-bit instances - - -When Valkey is compiled as a 32-bit target, it uses a lot less memory per key, since pointers are small, -but such an instance will be limited to 4 GB of maximum memory usage. -To compile Valkey as 32-bit binary use *make 32bit*. -RDB and AOF files are compatible between 32-bit and 64-bit instances -(and between little and big endian of course) so you can switch from 32 to 64-bit, or the contrary, without problems. - -## Bit and byte level operations - -Valkey has bit and byte level operations: `GETRANGE`, `SETRANGE`, `GETBIT` and `SETBIT`. -Using these commands you can treat the String type as a random access array. -For instance, if you have an application where users are identified by a unique progressive integer number, -you can use a bitmap to save information about the subscription of users in a mailing list, -setting the bit for subscribed and clearing it for unsubscribed, or the other way around. -With 100 million users this data will take just 12 megabytes of RAM in a Valkey instance. -You can do the same using `GETRANGE` and `SETRANGE` to store one byte of information for each user. -This is just an example but it is possible to model several problems in very little space with these new primitives. - -## Use hashes when possible - - -Small hashes are encoded in a very small space, so you should try representing your data using hashes whenever possible. -For instance, if you have objects representing users in a web application, -instead of using different keys for name, surname, email, password, use a single hash with all the required fields. - -If you want to know more about this, read the next section. - -## Using hashes to abstract a very memory-efficient plain key-value store on top of Valkey - -I understand the title of this section is a bit scary, but I'm going to explain in detail what this is about. - -Basically it is possible to model a plain key-value store using Valkey -where values can just be just strings, which is not just more memory efficient -than Valkey plain keys but also much more memory efficient than memcached. - -Let's start with some facts: a few keys use a lot more memory than a single key -containing a hash with a few fields. How is this possible? We use a trick. -In theory to guarantee that we perform lookups in constant time -(also known as O(1) in big O notation) there is the need to use a data structure -with a constant time complexity in the average case, like a hash table. - -But many times hashes contain just a few fields. When hashes are small we can -instead just encode them in an O(N) data structure, like a linear -array with length-prefixed key-value pairs. Since we do this only when N -is small, the amortized time for `HGET` and `HSET` commands is still O(1): the -hash will be converted into a real hash table as soon as the number of elements -it contains grows too large (you can configure the limit in valkey.conf). - -This does not only work well from the point of view of time complexity, but -also from the point of view of constant times since a linear array of key-value pairs happens to play very well with the CPU cache (it has a better -cache locality than a hash table). - -However since hash fields and values are not (always) represented as full-featured Valkey objects, hash fields can't have an associated time to live -(expire) like a real key, and can only contain a string. But we are okay with -this, this was the intention anyway when the hash data type API was -designed (we trust simplicity more than features, so nested data structures -are not allowed, as expires of single fields are not allowed). - -So hashes are memory efficient. This is useful when using hashes -to represent objects or to model other problems when there are group of -related fields. But what about if we have a plain key value business? - -Imagine we want to use Valkey as a cache for many small objects, which can be JSON encoded objects, small HTML fragments, simple key -> boolean values -and so forth. Basically, anything is a string -> string map with small keys -and values. - -Now let's assume the objects we want to cache are numbered, like: - - * object:102393 - * object:1234 - * object:5 - -This is what we can do. Every time we perform a -SET operation to set a new value, we actually split the key into two parts, -one part used as a key, and the other part used as the field name for the hash. For instance, the -object named "object:1234" is actually split into: - -* a Key named object:12 -* a Field named 34 - -So we use all the characters but the last two for the key, and the final -two characters for the hash field name. To set our key we use the following -command: - -``` -HSET object:12 34 somevalue -``` - -As you can see every hash will end up containing 100 fields, which is an optimal compromise between CPU and memory saved. - -There is another important thing to note, with this schema -every hash will have more or -less 100 fields regardless of the number of objects we cached. This is because our objects will always end with a number and not a random string. In some way, the final number can be considered as a form of implicit pre-sharding. - -What about small numbers? Like object:2? We handle this case using just -"object:" as a key name, and the whole number as the hash field name. -So object:2 and object:10 will both end inside the key "object:", but one -as field name "2" and one as "10". - -Every time a hash exceeds the number of elements or element size specified -it will be converted into a real hash table, and the memory saving will be lost. - -You may ask, why don't you do this implicitly in the normal key space so that -I don't have to care? There are two reasons: one is that we tend to make -tradeoffs explicit, and this is a clear tradeoff between many things: CPU, -memory, and max element size. The second is that the top-level key space must -support a lot of interesting things like expires, LRU data, and so -forth so it is not practical to do this in a general way. - -But the Valkey Way is that the user must understand how things work so that he can pick the best compromise and to understand how the system will -behave exactly. - -## Memory allocation - -To store user keys, Valkey allocates at most as much memory as the `maxmemory` -setting enables (however there are small extra allocations possible). - -The exact value can be set in the configuration file or set later via -`CONFIG SET` (for more info, see [Using memory as an LRU cache](lru-cache.md)). -There are a few things that should be noted about how Valkey manages memory: - -* Valkey will not always free up (return) memory to the OS when keys are removed. -This is not something special about Valkey, but it is how most malloc() implementations work. -For example, if you fill an instance with 5GB worth of data, and then -remove the equivalent of 2GB of data, the Resident Set Size (also known as -the RSS, which is the number of memory pages consumed by the process) -will probably still be around 5GB, even if Valkey will claim that the user -memory is around 3GB. This happens because the underlying allocator can't easily release the memory. -For example, often most of the removed keys were allocated on the same pages as the other keys that still exist. -* The previous point means that you need to provision memory based on your -**peak memory usage**. If your workload from time to time requires 10GB, even if -most of the time 5GB could do, you need to provision for 10GB. -* However allocators are smart and are able to reuse free chunks of memory, -so after you free 2GB of your 5GB data set, when you start adding more keys -again, you'll see the RSS (Resident Set Size) stay steady and not grow -more, as you add up to 2GB of additional keys. The allocator is basically -trying to reuse the 2GB of memory previously (logically) freed. -* Because of all this, the fragmentation ratio is not reliable when you -had a memory usage that at the peak is much larger than the currently used memory. -The fragmentation is calculated as the physical memory actually used (the RSS -value) divided by the amount of memory currently in use (as the sum of all -the allocations performed by Valkey). Because the RSS reflects the peak memory, -when the (virtually) used memory is low since a lot of keys/values were freed, but the RSS is high, the ratio `RSS / mem_used` will be very high. - -If `maxmemory` is not set Valkey will keep allocating memory as it sees -fit and thus it can (gradually) eat up all your free memory. -Therefore it is generally advisable to configure some limits. You may also -want to set `maxmemory-policy` to `noeviction` (which is *not* the default -value in some older versions of Valkey). - -It makes Valkey return an out-of-memory error for write commands if and when it reaches the -limit - which in turn may result in errors in the application but will not render the -whole machine dead because of memory starvation. diff --git a/topics/migration.md b/topics/migration.md deleted file mode 100644 index cca3039f..00000000 --- a/topics/migration.md +++ /dev/null @@ -1,424 +0,0 @@ ---- -title: Migration from Redis to Valkey -description: How to migrate from Redis to Valkey and check Redis compatibility ---- - -This is a migration guide from Redis open source versions to Valkey. -You will learn how to migrate a standalone Redis server instance and a Redis Cluster. - -This guide provides migration steps for Redis server and Valkey deployed in Docker; however, they should also apply for other deployments. -Refer to [install Valkey](installation.md) for installation options. - -## Why to migrate to Valkey? - -Valkey is a vendor-neutral, open-source continuation of Redis OSS. -It keeps compatibility with Redis OSS 7.2 and earlier versions while adding Valkey-specific features and improvements in later releases. - -## Redis compatibility and migration options - -You can migrate a Redis server to Valkey. -Valkey is compatible with Redis OSS 7.2 and all earlier open-source Redis versions, as Valkey 7.2.4 is a fork of Redis OSS 7.2.4. -Migrating from one of these Redis versions to Valkey is effectively an upgrade. - -> NOTE: In this guide, whenever a reference to a `redis-cli` or `valkey-cli` command is provided, the reference will only point to the Valkey version of the documentation. - -Redis Community Edition (CE) version 7.4 and later produce data files that are not compatible with Valkey. -It may be possible to migrate the data to Valkey from proprietary Redis versions and other Redis-like software, but it requires another method and is not covered by this document. - -The following table provides migration options depending on the Redis version you run: - -| Redis source | Valkey target | Notes | -|-----------------------|---------------------|-------| -| OSS 2.x - 7.2.x | Valkey 7.2 or later | Uses compatible protocol, configuration, and RDB/AOF formats. | -| CE 7.4 and later | n/a | Data files are not compatible with Valkey. | - -Compatibility details: - -* Protocol: Valkey uses the RESP wire protocol and supports both RESP2 and RESP3. Existing Redis client libraries can connect to Valkey without code changes. -* Persistence: Valkey reads and writes RDB and AOF files compatible with Redis OSS 7.2. RDB files produced by Redis CE 7.4 and later are not compatible. -* Configuration: Valkey accepts Redis-style configuration files. Existing Redis OSS 7.2 configuration directives are supported, with additional Valkey-specific options for new features. -* CLI: `redis-cli` works with Valkey servers, and `valkey-cli` works with Redis OSS servers. -* INFO: Valkey reports `redis_version:7.2.4` in the [INFO](../commands/info.md) output for backward compatibility. Use `server_name` and `valkey_version` to detect the actual Valkey server and version. -* Lua scripting: Existing scripts that use the `redis` namespace continue to work. Valkey also supports the `server` namespace and `SERVER_NAME`, `SERVER_VERSION`, and `SERVER_VERSION_NUM` globals. -* Modules: Modules written for Redis OSS using the `RedisModule_` API work in Valkey. Valkey also provides the `ValkeyModule_` API and `valkeymodule.h` header for new modules. - -## Migrate a standalone instance - -To migrate a standalone Redis server to Valkey, you have the following options: - -* [Physical migration](#physical-migration) by copying the most recent on-disk snapshot from the Redis server to Valkey and starting Valkey server with it -* [Setting up replication](#replication) between Redis and Valkey -* [Migrating specific keys](#migrate-specific-keys) - -The example migration steps are provided for Redis 7.2.5 and Valkey version 7.2.6. - -Note that Redis and Valkey Docker containers are considered stand-alone servers, if they are not part of a cluster. - -### Physical migration - -This is the easiest and fastest migration method. You make a fresh snapshot of your Redis instance and copy it over to Valkey. Valkey reads the data from the snapshot on startup and restores its contents into memory. The tradeoffs for this method are: - -* The downtime to shutdown Redis and wait for Valkey to load the data. -* Potential risk of data loss on instances with heavy writes. To prevent it, you must disconnect all active connections before starting the migration. - -To perform a physical migration: - -1. Disconnect all active connections to the Redis instance. - -2. Connect to your Redis container using `redis-cli`, and check the number of keys, using the `INFO KEYSPACE` command. This will be used later to verify that the entire database has been successfully migrated. In this example, `keys=6286` indicates that there are 6,286 keys in the database. - - ``` - $ redis-cli -h 127.0.0.1 -p 6379 - redis 127.0.0.1:6379> INFO KEYSPACE - # Keyspace - db0:keys=6286,expires=0,avg_ttl=0 - ``` - -3. Check the configuration for the directory (`dir`) where Redis stores its database files and the name of the database file (`dbfilename`). In this example, Redis saves the backup into the `/data/dump.rdb` file - - > NOTE: If your Redis Docker container `/data` directory is mounted to a directory on your host, the RDB file is also written to that host directory. - - ``` - redis 127.0.0.1:6379> CONFIG GET dir dbfilename - 1) "dir" - 2) "/data" - 3) "dbfilename" - 4) "dump.rdb" - ``` -4. Create the backup file. Since all active connections have been disconnected for this example, the `redis-cli` [SAVE](../commands/save.md) command can be used to create the backup file. - - ``` - redis 127.0.0.1:6379> SAVE - OK - ``` - -5. Exit `redis-cli` by pressing `CTRL-D` or typing `exit`. -6. Create a directory on your host to which you will mount the `/data` directory of the Valkey container. -7. Copy the RDB file from Redis to Valkey, using one of the following: - - - If the Redis and Valkey containers are both mounted to a host directory: - - Copy the RDB file from the host directory mounted to the Redis container to the host directory being mounted to the Valkey container. - - - - If the Redis container is not mounted to a host directory but the Valkey container is: - - Use `docker cp` to copy the RDB file from within the Redis container to the host directory that will be mounted to your Valkey container. - - > NOTE: You may also want to copy the RDB file to a second location as a backup. - - ``` - docker cp redis-container-name:/dir-name/dbfilename /dbfilename - ``` - -8. Stop the Redis server. -9. Start Valkey: - > NOTE: If you enabled AOF in your Valkey configuration, disable it on the first start. Otherwise, the copied RDB file will not be imported into Valkey. - - Run the following command: - - ``` - docker run -d --name valkey-container-name -v : image-name - - ``` - -10. To verify that the data has been successfully migrated, determine the number of keys in the Valkey database. If the migration is successful, then the number of keys in the Valkey database match the number of keys in the Redis database that you obtained in step 2: - - ``` - $ docker exec -it somevalkey valkey-cli - valkey 127.0.0.1:6379> INFO KEYSPACE - # Keyspace - db0:keys=6286,expires=0,avg_ttl=0 - ``` - -11. To exit `valkey-cli`, press `Ctrl-D` or type `exit`. - -### Replication - -To minimize the downtime during migration, you can use replication. Both Redis and Valkey allow replaying data on another server to handle the workload. - -In this scenario we will configure Valkey to be the replica of Redis. For illustrative purposes, both Redis and Valkey are running in separate Docker containers connected to the same network. - -1. Retrieve the IP address of the Redis container. Replace the `myredis` placeholder with the name of your container. In this example, `172.17.0.2` is returned as the IP address of the `myredis` container. - - ``` - $ docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' myredis - 172.17.0.2 - ``` -2. Determine the port on which your Redis container is exposed. Note that for clarity, not all of the fields are shown in the response. In this example, the `myredis` container is exposed on port `6379`. - - ``` - docker container ls - CONTAINER ID ... PORTS NAMES - bffc575f261a ... 6379/tcp myvalkey - ab18318ce820 ... 6379/tcp myredis - ``` - -3. Connect to your Valkey container and start the `valkey-cli` to configure replication using the [REPLICAOF](../commands/replicaof.md) command. In this example, the Redis IP address is `172.17.0.2` and the port is `6379`. Replace with the IP address and port of your Redis container obtained in steps 1 and 2. - - ``` - docker exec -it myvalkey valkey-cli - valkey 127.0.0.1:6379> REPLICAOF 172.17.0.2 6379 - OK - ``` - -4. Check the replication status in Valkey using the `INFO REPLICATION` command. If `master_link_status:up` is present, then the Redis and Valkey servers are synchronized. [INFO Command](../commands/info.md) describes the different output fields. - - ``` - valkey 127.0.0.1:6379> INFO REPLICATION - # Replication - role:slave - master_host:172.17.0.2 - master_port:6379 - master_link_status:up - master_last_io_seconds_ago:4 - master_sync_in_progress:0 - .... - ``` - -5. Once Redis and Valkey are synchronized, verify that your applications connect to Valkey and shut down your Redis instance. - - > NOTE: Since the Redis 7.0 release, the `SHUTDOWN` command waits for a time period, set by the `shutdown-timeout` configuration variable, for any lagging replicas to sync. There may be potential data loss in the case where there are writes active on the Redis primary while it is syncing with the replica. - - You can shut down Redis in one of the following ways: - - * Using `redis-cli`: - - ``` - $ redis-cli SHUTDOWN - ``` - - - * If Redis was started directly in the foreground (using redis-server), you can simply stop it by pressing `Ctrl-C` in the terminal where it is running. - -9. In your Valkey container, stop the Valkey replication using the `REPLICAOF` command with `NO ONE` as the options: - - ``` - valkey 127.0.0.1:6379> REPLICAOF NO ONE - OK - ``` -10. You can verify that replication has stopped by running the `valkey-cli` command, `INFO REPLICATION`. If you see `role:master` and `connected_slaves:0`, then the Valkey container is now the master and is no longer connected to the Redis server. [INFO Command](../commands/info.md) describes the different output fields. - - ``` - 127.0.0.1:6379> INFO REPLICATION - # Replication - role:master - connected_slaves:0 - master_failover_state:no-failover - master_replid:8d48c4667129cdb5933f9a12a1d5e6a24899602b - master_replid2:602b7046ada6d2d6f0e89657e646d5932cc42791 - master_repl_offset:1336 - second_repl_offset:1337 - repl_backlog_active:1 - repl_backlog_size:1048576 - repl_backlog_first_byte_offset:1 - repl_backlog_histlen:1336 - ``` - -> NOTE: If not for backward compatibility, the Valkey project no longer uses the words "master" and "slave". Unfortunately, in this command these words are part of the protocol, so we’ll be able to remove such occurrences only when this API is naturally deprecated. - -### Migrate specific keys - -Both physical migration and replication migrate the entire keyspace over to Valkey. - -There may be cases when you need to migrate only a specific set of critical keys. -The `redis-cli` command, [MIGRATE](../commands/migrate.md) is used to migrate one or more keys. - -Requirements for this example: - -- The Redis and Valkey Docker containers are on the same network and can communicate with each other. - -- The Redis and Valkey containers are running without authentication. - -Perform the following steps: - -1. Determine the keys you wish to migrate. In this example, the `message` and `mydata` keys are being migrated from the `myredis` container, and the `redis-cli` is used to view their current values. - - ``` - $ docker exec -it myredis redis-cli - redis 127.0.0.1:6379> GET message - "Hello Valkey" - redis 127.0.0.1:6379> HGETALL mydata - 1) "name" - 2) "Alice" - 3) "age" - 4) "33" - 5) "country" - 6) "Brazil" - 7) "favorite food" - 8) "beans" - ``` - -2. Retrieve the IP address of your Valkey container. Replace `myvalkey` with the name of your Valkey container. - - ``` - $ docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' myvalkey - 172.21.0.3 - ``` - -3. Start the `valkey-cli` in your Valkey container and get the database number using the `INFO KEYSPACE` command. In this example, the database number is `0` (db0). - - ``` - valkey 127.0.0.1:6379> INFO KEYSPACE - # Keyspace - db0:keys=3,expires=0,avg_ttl=0 - ``` - > NOTE: If you haven't migrated or added any data to your Valkey database, then the `INFO KEYSPACE` command will not return any database number. You can use `0` for the `MIGRATE` command in step 4. - -4. From the Redis server, run the `MIGRATE` command: - ``` - MIGRATE valkey-ip valkey-port valkey-db-number timeout-value [COPY] [REPLACE] [AUTH password | AUTH2 username password] [KEYS key [key ...]] - ``` - For example, to migrate the `message` and `mydata` keys to the Valkey instance with the IP address 172.21.0.3 and port 6379, the command would look similar to: - - ``` - redis 127.0.0.1:6379> MIGRATE 172.21.0.3 6379 "" 0 10 COPY REPLACE KEYS message mydata - ``` - - where: - - `""` = Indicates that we are migrating multiple keys. You can use `key` name here if you are only migrating a single key. - - `0` = The database number. - - `10`= The maximum idle time, in milliseconds, allowed when communicating with the destination server. - - `COPY` = Do not remove the key from the Redis database. - - `REPLACE` = Replace existing key on the Valkey database. - - `KEYS` = We are migrating multiple keys, and it is followed by the key names. - - - -7. Exit `redis-cli` by pressing `Ctrl-D` or typing `exit`. - -4. Connect to Valkey and check the migrated keys. replace `myvalkey` with the name of your Valkey container. - - ``` - $ docker exec -it myvalkey valkey-cli - valkey 127.0.0.1:6379> GET message - "Hello Valkey" - valkey 127.0.0.1:6379> HGETALL mydata - 1) "name" - 2) "Alice" - 3) "age" - 4) "33" - 5) "country" - 6) "Brazil" - 7) "favorite food" - 8) "beans" - .... - ``` - -## Migrate a Cluster - -This section demonstrates how to migrate a cluster. The first step is to add the required number of Valkey nodes to the existing cluster as replicas. Once the new Valkey nodes replicate the data, one Valkey replica is promoted to be a new primary for each Redis primary. After the migration, the Redis nodes are removed from the cluster. - -> NOTE: You can also use data migration tools such as [RIOT](https://redis.github.io/riot/#_introduction), [RedisShake](https://github.com/tair-opensource/RedisShake), and [Redis-Migrate-Tool](https://github.com/vipshop/redis-migrate-tool) but that is beyond the scope of this document. - -Requirements for this example: - -- The Redis and Valkey cluster nodes are on the same network and can communicate with each other. - -For this scenario, there is a Redis Cluster consisting of 3 primary and 3 replica nodes up and running. - -To perform the migration: - -1. Use the `redis-cli` on one of the cluster nodes to check the current state of the cluster and to ensure all nodes are connected and active. In this cluster, there are three primary (master) and three replica (slave) nodes. - - ``` - $ redis-cli -h 127.0.0.1 -p 6379 -c CLUSTER NODES - 70beedebe43e422b275ee1a7bac0d3819dedca98 172.22.0.3:6379@16379 master - 0 1725450849000 1 connected 0-5460 - 8bbe836c59644f7395bbab09c6f8b36bc277e902 172.22.0.5:6379@16379 slave 58061fb2836bdb2f5a0973e1ccfd74a66166f329 0 1725450849510 3 connected - 65061b94da5b481dc35c2df7dae13c233d4b3ad2 172.22.0.4:6379@16379 master - 0 1725450848000 2 connected 5461-10922 - a242941d0e3edad27a954bc14ac3a3413f3040aa 172.22.0.7:6379@16379 slave 65061b94da5b481dc35c2df7dae13c233d4b3ad2 0 1725450849000 2 connected - 3499854656f085ebb77b5b921389a91b7ae9d703 172.22.0.6:6379@16379 slave 70beedebe43e422b275ee1a7bac0d3819dedca98 0 1725450849829 1 connected - 58061fb2836bdb2f5a0973e1ccfd74a66166f329 172.22.0.2:6379@16379 myself,master - 0 1725450846000 3 connected 10923-16383 - ``` - -2. Create a valkey.conf configuration file and specify the following parameters. Note that this configuration file enables clustering. [Valkey configuration file example](https://raw.githubusercontent.com/valkey-io/valkey/7.2/valkey.conf) provides a description of the various configuration arguments: - - ``` - # valkey.conf file - port 6379 - cluster-enabled yes - cluster-config-file nodes.conf - cluster-node-timeout 5000 - appendonly yes - ``` - -3. Start a Valkey instance with your custom configuration file. The following command starts Valkey in Docker: - - ``` - $ docker run -d -v myvalkey/conf:/usr/local/etc/valkey --name valkey-1 --net mynetwork valkey/valkey valkey-server /usr/local/etc/valkey/valkey.conf - ``` - - where: - * `myvalkey/conf` is a local directory containing your `valkey.conf` configuration file that is being mapped to the `/usr/local/etc/valkey` directory within the Docker Valkey container. - * `valkey-1` is the name of your container - * `mynetwork` is the name of the network where Redis cluster is running. - * `valkey/valkey` is the name of the Valkey image - -4. Retrieve the IP address of the Valkey instance; replacing `valkey-1` with the name of your container. - - ``` - $ docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' valkey-1 - ``` - -5. Add your new Valkey node to the Redis Cluster as a replica. Replace the `redis-1`, `valkey-node-ip`, and `existing-node-ip` placeholders with your values: - - ``` - $ docker exec -it redis-1 bash - $ redis-cli --cluster add-node valkey-node-ip:6379 existing-node-ip:6379 --cluster-replica - ``` - -6. Check the cluster status. The output of the `CLUSTER NODES` command is described in [CLUSTER NODES](../commands/cluster-nodes.md). - - ``` - $ redis-cli -c CLUSTER NODES - ``` - - In the output, you will see the newly added node as a replica (slave). For example, we have added a Valkey node with the IP address `172.22.0.8:6379`. The cluster nodes list now includes a new entry as follows: - - ``` - a98d5bac59672597b8509f24970e413002f896b6 172.22.0.8:6379@16379 slave 58061fb2836bdb2f5a0973e1ccfd74a66166f329 0 1725451086000 3 connected - ``` - -7. Verify that your newly added Valkey node is recognized as a replica by running the `INFO REPLICATION` command. The output displays information about the node's primary. - -8. Start the `valkey-cli` in your new Valkey container and enter the following command to promote it to be primary. [CLUSTER FAILOVER](../commands/cluster-failover.md) provides additional information. - - ``` - docker exec -it valkey-container-name valkey-cli - valkey 127.0.0.1:6379> CLUSTER FAILOVER - OK - ``` - -9. Use the `CLUSTER NODES` command to display the cluster state and verify that your new Valkey node is now a new primary. - -10. Repeat steps 3-9 to add 2 more Valkey nodes and replace the Redis primary nodes. -11. Repeat steps 3-7 to add 3 Valkey replica nodes. - - To add a replica to a specific primary, do the following: - - a. Filter primary nodes. Connect to any node in the Cluster and run the following command, replacing `valkey-1` with then name of your Valkey container: - - ``` - $ docker exec -it valkey-1 bash - $ valkey-cli -c cluster nodes | grep master - 70beedebe43e422b275ee1a7bac0d3819dedca98 172.22.0.3:6379@16379 master - 0 1725451135799 1 connected 0-5460 - 65061b94da5b481dc35c2df7dae13c233d4b3ad2 172.22.0.4:6379@16379 master - 0 1725451136000 2 connected 5461-10922 - 58061fb2836bdb2f5a0973e1ccfd74a66166f329 172.22.0.2:6379@16379 myself,master - 0 1725451136000 3 connected 10923-16383 - ``` - > NOTE: The node ID is the 40-character globally unique string that is generated when the node is created. In this example, `70beedebe43e422b275ee1a7bac0d3819dedca98` is the ID of the primary (master) node with the IP address `172.22.0.3:6379`. The ID of a node is required when adding a new Valkey replica to a specific primary in step b. - - b. Add a new node to a specific primary, replacing node-id with your node ID: - - ``` - $ valkey-cli --cluster add-node 172.22.0.10:6379 172.22.0.2:6379 --cluster-replica --cluster-master-id node-id - ``` - -12. Remove Redis nodes: - - ``` - redis-cli --cluster del-node 127.0.0.1:6379 node-id - ``` - - The first argument is just a random node in the cluster, the second argument is the ID of the node you want to remove. - -> NOTE: If not for backward compatibility, the Valkey project no longer uses the words "master" and "slave". Unfortunately, in the given commands these words are part of the protocol, so we'll be able to remove such occurrences only when this API is naturally deprecated. diff --git a/topics/modules-api-ref.md b/topics/modules-api-ref.md deleted file mode 100644 index 33a6d8b5..00000000 --- a/topics/modules-api-ref.md +++ /dev/null @@ -1,9023 +0,0 @@ ---- -title: "Modules API reference" -linkTitle: "API reference" -description: > - Reference for the Valkey Modules API ---- - - - -## Sections - -* [Heap allocation raw functions](#section-heap-allocation-raw-functions) -* [Commands API](#section-commands-api) -* [Module information and time measurement](#section-module-information-and-time-measurement) -* [Automatic memory management for modules](#section-automatic-memory-management-for-modules) -* [String objects APIs](#section-string-objects-apis) -* [Reply APIs](#section-reply-apis) -* [Commands replication API](#section-commands-replication-api) -* [DB and Key APIs – Generic API](#section-db-and-key-apis-generic-api) -* [Key API for String type](#section-key-api-for-string-type) -* [Key API for List type](#section-key-api-for-list-type) -* [Key API for Sorted Set type](#section-key-api-for-sorted-set-type) -* [Key API for Sorted Set iterator](#section-key-api-for-sorted-set-iterator) -* [Key API for Hash type](#section-key-api-for-hash-type) -* [Key API for Stream type](#section-key-api-for-stream-type) -* [Calling commands from modules](#section-calling-commands-from-modules) -* [Modules data types](#section-modules-data-types) -* [RDB loading and saving functions](#section-rdb-loading-and-saving-functions) -* [Key digest API (DEBUG DIGEST interface for modules types)](#section-key-digest-api-debug-digest-interface-for-modules-types) -* [AOF API for modules data types](#section-aof-api-for-modules-data-types) -* [IO context handling](#section-io-context-handling) -* [Logging](#section-logging) -* [Blocking clients from modules](#section-blocking-clients-from-modules) -* [Thread Safe Contexts](#section-thread-safe-contexts) -* [Module Keyspace Notifications API](#section-module-keyspace-notifications-api) -* [Modules Cluster API](#section-modules-cluster-api) -* [Modules Timers API](#section-modules-timers-api) -* [Modules EventLoop API](#section-modules-eventloop-api) -* [Modules ACL API](#section-modules-acl-api) -* [Modules Dictionary API](#section-modules-dictionary-api) -* [Modules Info fields](#section-modules-info-fields) -* [Modules utility APIs](#section-modules-utility-apis) -* [Modules API exporting / importing](#section-modules-api-exporting-importing) -* [Module Command Filter API](#section-module-command-filter-api) -* [Module Command Result Event](#section-module-command-result-event) -* [Scanning keyspace and hashes](#section-scanning-keyspace-and-hashes) -* [Module fork API](#section-module-fork-api) -* [Server hooks implementation](#section-server-hooks-implementation) -* [Module Configurations API](#section-module-configurations-api) -* [RDB load/save API](#section-rdb-load-save-api) -* [Scripting Engine API](#section-scripting-engine-api) -* [Key eviction API](#section-key-eviction-api) -* [Miscellaneous APIs](#section-miscellaneous-apis) -* [Defrag API](#section-defrag-api) -* [Function index](#section-function-index) - - - -## Heap allocation raw functions - -Memory allocated with these functions are taken into account by key -eviction algorithms and are reported in memory usage information. - - - -### `ValkeyModule_Alloc` - - void *ValkeyModule_Alloc(size_t bytes); - -**Available since:** 4.0.0 - -Use like `malloc()`. Memory allocated with this function is reported in -INFO memory, used for keys eviction according to maxmemory settings -and in general is taken into account as memory allocated by the server. -You should avoid using `malloc()`. -This function panics if unable to allocate enough memory. - - - -### `ValkeyModule_TryAlloc` - - void *ValkeyModule_TryAlloc(size_t bytes); - -**Available since:** 7.0.0 - -Similar to [`ValkeyModule_Alloc`](#ValkeyModule_Alloc), but returns NULL in case of allocation failure, instead -of panicking. - - - -### `ValkeyModule_Calloc` - - void *ValkeyModule_Calloc(size_t nmemb, size_t size); - -**Available since:** 4.0.0 - -Use like `calloc()`. Memory allocated with this function is reported in -INFO memory, used for keys eviction according to maxmemory settings -and in general is taken into account as memory allocated by the server. -You should avoid using `calloc()` directly. - - - -### `ValkeyModule_TryCalloc` - - void *ValkeyModule_TryCalloc(size_t nmemb, size_t size); - -**Available since:** 8.0.0 - -Similar to [`ValkeyModule_Calloc`](#ValkeyModule_Calloc), but returns NULL in case of allocation failure, instead -of panicking. - - - -### `ValkeyModule_Realloc` - - void *ValkeyModule_Realloc(void *ptr, size_t bytes); - -**Available since:** 4.0.0 - -Use like `realloc()` for memory obtained with [`ValkeyModule_Alloc()`](#ValkeyModule_Alloc). - - - -### `ValkeyModule_TryRealloc` - - void *ValkeyModule_TryRealloc(void *ptr, size_t bytes); - -**Available since:** 8.0.0 - -Similar to [`ValkeyModule_Realloc`](#ValkeyModule_Realloc), but returns NULL in case of allocation failure, -instead of panicking. - - - -### `ValkeyModule_Free` - - void ValkeyModule_Free(void *ptr); - -**Available since:** 4.0.0 - -Use like `free()` for memory obtained by [`ValkeyModule_Alloc()`](#ValkeyModule_Alloc) and -[`ValkeyModule_Realloc()`](#ValkeyModule_Realloc). However you should never try to free with -[`ValkeyModule_Free()`](#ValkeyModule_Free) memory allocated with `malloc()` inside your module. - - - -### `ValkeyModule_Strdup` - - char *ValkeyModule_Strdup(const char *str); - -**Available since:** 4.0.0 - -Like `strdup()` but returns memory allocated with [`ValkeyModule_Alloc()`](#ValkeyModule_Alloc). - - - -### `ValkeyModule_IncrExternalMemory` - - int ValkeyModule_IncrExternalMemory(size_t bytes); - -**Available since:** 9.2.0 - -Report memory obtained outside the server allocator, such as an `mmap()`ed -region, so it counts toward `used_memory` and maxmemory. Does not allocate. - -Report only resident memory, and only memory not already obtained from -[`ValkeyModule_Alloc()`](#ValkeyModule_Alloc). Each call must be matched by -[`ValkeyModule_DecrExternalMemory()`](#ValkeyModule_DecrExternalMemory) of the same size. - -May be called from a command callback or a thread-safe context. - -Returns `VALKEYMODULE_OK`, or `VALKEYMODULE_ERR` with errno set to ERANGE if the -total would overflow, leaving the accounting unchanged. - - - -### `ValkeyModule_DecrExternalMemory` - - int ValkeyModule_DecrExternalMemory(size_t bytes); - -**Available since:** 9.2.0 - -Stop accounting for memory reported with [`ValkeyModule_IncrExternalMemory()`](#ValkeyModule_IncrExternalMemory). -Frees nothing. - -Returns `VALKEYMODULE_OK`, or `VALKEYMODULE_ERR` with errno set to ERANGE if -`bytes` exceeds the reported total, leaving the accounting unchanged. - - - -### `ValkeyModule_PoolAlloc` - - void *ValkeyModule_PoolAlloc(ValkeyModuleCtx *ctx, size_t bytes); - -**Available since:** 4.0.0 - -Return heap allocated memory that will be freed automatically when the -module callback function returns. Mostly suitable for small allocations -that are short living and must be released when the callback returns -anyway. The returned memory is aligned to the architecture word size -if at least word size bytes are requested; otherwise, it is just -aligned to the next power of two, so for example a 3 bytes request is -4 bytes aligned while a 2 bytes request is 2 bytes aligned. - -There is no realloc style function since when this is needed to use the -pool allocator is not a good idea. - -The function returns NULL if `bytes` is 0. - - - -## Commands API - -These functions are used to implement custom commands. - -For examples, see [https://valkey.io/topics/modules-intro](https://valkey.io/topics/modules-intro). - - - -### `ValkeyModule_IsKeysPositionRequest` - - int ValkeyModule_IsKeysPositionRequest(ValkeyModuleCtx *ctx); - -**Available since:** 4.0.0 - -Return non-zero if a module command, that was declared with the -flag "getkeys-api", is called in a special way to get the keys positions -and not to get executed. Otherwise, zero is returned. - - - -### `ValkeyModule_KeyAtPosWithFlags` - - void ValkeyModule_KeyAtPosWithFlags(ValkeyModuleCtx *ctx, int pos, int flags); - -**Available since:** 7.0.0 - -When a module command is called in order to obtain the position of -keys, since it was flagged as "getkeys-api" during the registration, -the command implementation checks for this special call using the -[`ValkeyModule_IsKeysPositionRequest()`](#ValkeyModule_IsKeysPositionRequest) API and uses this function in -order to report keys. - -The supported flags are the ones used by [`ValkeyModule_SetCommandInfo`](#ValkeyModule_SetCommandInfo), see `VALKEYMODULE_CMD_KEY_`*. - - -The following is an example of how it could be used: - - if (ValkeyModule_IsKeysPositionRequest(ctx)) { - ValkeyModule_KeyAtPosWithFlags(ctx, 2, VALKEYMODULE_CMD_KEY_RO | VALKEYMODULE_CMD_KEY_ACCESS); - ValkeyModule_KeyAtPosWithFlags(ctx, 1, VALKEYMODULE_CMD_KEY_RW | VALKEYMODULE_CMD_KEY_UPDATE | VALKEYMODULE_CMD_KEY_ACCESS); - } - - Note: in the example above the get keys API could have been handled by key-specs (preferred). - Implementing the getkeys-api is required only when is it not possible to declare key-specs that cover all keys. - - - -### `ValkeyModule_KeyAtPos` - - void ValkeyModule_KeyAtPos(ValkeyModuleCtx *ctx, int pos); - -**Available since:** 4.0.0 - -This API existed before [`ValkeyModule_KeyAtPosWithFlags`](#ValkeyModule_KeyAtPosWithFlags) was added, now deprecated and -can be used for compatibility with older versions, before key-specs and flags -were introduced. - - - -### `ValkeyModule_IsChannelsPositionRequest` - - int ValkeyModule_IsChannelsPositionRequest(ValkeyModuleCtx *ctx); - -**Available since:** 7.0.0 - -Return non-zero if a module command, that was declared with the -flag "getchannels-api", is called in a special way to get the channel positions -and not to get executed. Otherwise, zero is returned. - - - -### `ValkeyModule_ChannelAtPosWithFlags` - - void ValkeyModule_ChannelAtPosWithFlags(ValkeyModuleCtx *ctx, - int pos, - int flags); - -**Available since:** 7.0.0 - -When a module command is called in order to obtain the position of -channels, since it was flagged as "getchannels-api" during the -registration, the command implementation checks for this special call -using the [`ValkeyModule_IsChannelsPositionRequest()`](#ValkeyModule_IsChannelsPositionRequest) API and uses this -function in order to report the channels. - -The supported flags are: -* `VALKEYMODULE_CMD_CHANNEL_SUBSCRIBE`: This command will subscribe to the channel. -* `VALKEYMODULE_CMD_CHANNEL_UNSUBSCRIBE`: This command will unsubscribe from this channel. -* `VALKEYMODULE_CMD_CHANNEL_PUBLISH`: This command will publish to this channel. -* `VALKEYMODULE_CMD_CHANNEL_PATTERN`: Instead of acting on a specific channel, will act on any - channel specified by the pattern. This is the same access - used by the PSUBSCRIBE and PUNSUBSCRIBE commands. - Not intended to be used with PUBLISH permissions. - -The following is an example of how it could be used: - - if (ValkeyModule_IsChannelsPositionRequest(ctx)) { - ValkeyModule_ChannelAtPosWithFlags(ctx, 1, VALKEYMODULE_CMD_CHANNEL_SUBSCRIBE | VALKEYMODULE_CMD_CHANNEL_PATTERN); - ValkeyModule_ChannelAtPosWithFlags(ctx, 1, VALKEYMODULE_CMD_CHANNEL_PUBLISH); - } - -Note: One usage of declaring channels is for evaluating ACL permissions. In this context, -unsubscribing is always allowed, so commands will only be checked against subscribe and -publish permissions. This is preferred over using [`ValkeyModule_ACLCheckChannelPermissions`](#ValkeyModule_ACLCheckChannelPermissions), since -it allows the ACLs to be checked before the command is executed. - - - -### `ValkeyModule_CreateCommand` - - int ValkeyModule_CreateCommand(ValkeyModuleCtx *ctx, - const char *name, - ValkeyModuleCmdFunc cmdfunc, - const char *strflags, - int firstkey, - int lastkey, - int keystep); - -**Available since:** 4.0.0 - -Register a new command in the server, that will be handled by -calling the function pointer 'cmdfunc' using the ValkeyModule calling -convention. - -The function returns `VALKEYMODULE_ERR` in these cases: -- If creation of module command is called outside the `ValkeyModule_OnLoad`. -- The specified command is already busy. -- The command name contains some chars that are not allowed. -- A set of invalid flags were passed. - -Otherwise, `VALKEYMODULE_OK` is returned and the new command is registered. - -This function must be called during the initialization of the module -inside the `ValkeyModule_OnLoad()` function. Calling this function outside -of the initialization function is not defined. - -The command function type is the following: - - int MyCommand_ValkeyCommand(ValkeyModuleCtx *ctx, ValkeyModuleString **argv, int argc); - -And is supposed to always return `VALKEYMODULE_OK`. - -The set of flags 'strflags' specify the behavior of the command, and should -be passed as a C string composed of space separated words, like for -example "write deny-oom". The set of flags are: - -* **"write"**: The command may modify the data set (it may also read - from it). -* **"readonly"**: The command returns data from keys but never writes. -* **"admin"**: The command is an administrative command (may change - replication or perform similar tasks). -* **"deny-oom"**: The command may use additional memory and should be - denied during out of memory conditions. -* **"deny-script"**: Don't allow this command in Lua scripts. -* **"allow-loading"**: Allow this command while the server is loading data. - Only commands not interacting with the data set - should be allowed to run in this mode. If not sure - don't use this flag. -* **"pubsub"**: The command publishes things on Pub/Sub channels. -* **"random"**: The command may have different outputs even starting - from the same input arguments and key values. - Starting from Redis OSS 7.0 this flag has been deprecated. - Declaring a command as "random" can be done using - command tips, see https://valkey.io/topics/command-tips. -* **"allow-stale"**: The command is allowed to run on replicas that don't - serve stale data. Don't use if you don't know what - this means. -* **"no-monitor"**: Don't propagate the command on monitor. Use this if - the command has sensitive data among the arguments. -* **"no-slowlog"**: Deprecated, please use "no-commandlog". -* **"no-commandlog"**: Don't log this command in the commandlog. Use this if - the command has sensitive data among the arguments. -* **"fast"**: The command time complexity is not greater - than O(log(N)) where N is the size of the collection or - anything else representing the normal scalability - issue with the command. -* **"getkeys-api"**: The command implements the interface to return - the arguments that are keys. Used when start/stop/step - is not enough because of the command syntax. -* **"no-cluster"**: The command should not register in Cluster - since is not designed to work with it because, for - example, is unable to report the position of the - keys, programmatically creates key names, or any - other reason. -* **"no-auth"**: This command can be run by an un-authenticated client. - Normally this is used by a command that is used - to authenticate a client. -* **"may-replicate"**: This command may generate replication traffic, even - though it's not a write command. -* **"no-mandatory-keys"**: All the keys this command may take are optional -* **"blocking"**: The command has the potential to block the client. -* **"allow-busy"**: Permit the command while the server is blocked either by - a script or by a slow module command, see - ValkeyModule_Yield. -* **"all-dbs"**: The command accesses all databases and to execute this - command user has to have `alldbs` -* **"getchannels-api"**: The command implements the interface to return - the arguments that are channels. - -The last three parameters specify which arguments of the new command are -keys. See [https://valkey.io/commands/command](https://valkey.io/commands/command) for more information. - -* `firstkey`: One-based index of the first argument that's a key. - Position 0 is always the command name itself. - 0 for commands with no keys. -* `lastkey`: One-based index of the last argument that's a key. - Negative numbers refer to counting backwards from the last - argument (-1 means the last argument provided) - 0 for commands with no keys. -* `keystep`: Step between first and last key indexes. - 0 for commands with no keys. - -This information is used by ACL, Cluster and the `COMMAND` command. - -NOTE: The scheme described above serves a limited purpose and can -only be used to find keys that exist at constant indices. -For non-trivial key arguments, you may pass 0,0,0 and use -[`ValkeyModule_SetCommandInfo`](#ValkeyModule_SetCommandInfo) to set key specs using a more advanced scheme and use -[`ValkeyModule_SetCommandACLCategories`](#ValkeyModule_SetCommandACLCategories) to set ACL categories of the commands. - - - -### `ValkeyModule_GetCommand` - - ValkeyModuleCommand *ValkeyModule_GetCommand(ValkeyModuleCtx *ctx, - const char *name); - -**Available since:** 7.0.0 - -Get an opaque structure, representing a module command, by command name. -This structure is used in some of the command-related APIs. - -NULL is returned in case of the following errors: - -* Command not found -* The command is not a module command -* The command doesn't belong to the calling module - - - -### `ValkeyModule_CreateSubcommand` - - int ValkeyModule_CreateSubcommand(ValkeyModuleCommand *parent, - const char *name, - ValkeyModuleCmdFunc cmdfunc, - const char *strflags, - int firstkey, - int lastkey, - int keystep); - -**Available since:** 7.0.0 - -Very similar to [`ValkeyModule_CreateCommand`](#ValkeyModule_CreateCommand) except that it is used to create -a subcommand, associated with another, container, command. - -Example: If a module has a configuration command, MODULE.CONFIG, then -GET and SET should be individual subcommands, while MODULE.CONFIG is -a command, but should not be registered with a valid `funcptr`: - - if (ValkeyModule_CreateCommand(ctx,"module.config",NULL,"",0,0,0) == VALKEYMODULE_ERR) - return VALKEYMODULE_ERR; - - ValkeyModuleCommand *parent = ValkeyModule_GetCommand(ctx,,"module.config"); - - if (ValkeyModule_CreateSubcommand(parent,"set",cmd_config_set,"",0,0,0) == VALKEYMODULE_ERR) - return VALKEYMODULE_ERR; - - if (ValkeyModule_CreateSubcommand(parent,"get",cmd_config_get,"",0,0,0) == VALKEYMODULE_ERR) - return VALKEYMODULE_ERR; - -Returns `VALKEYMODULE_OK` on success and `VALKEYMODULE_ERR` in case of the following errors: - -* Error while parsing `strflags` -* Command is marked as `no-cluster` but cluster mode is enabled -* `parent` is already a subcommand (we do not allow more than one level of command nesting) -* `parent` is a command with an implementation (`ValkeyModuleCmdFunc`) (A parent command should be a pure container of -subcommands) -* `parent` already has a subcommand called `name` -* Creating a subcommand is called outside of `ValkeyModule_OnLoad`. - - - -### `ValkeyModule_AddACLCategory` - - int ValkeyModule_AddACLCategory(ValkeyModuleCtx *ctx, const char *name); - -**Available since:** 8.0.0 - -[`ValkeyModule_AddACLCategory`](#ValkeyModule_AddACLCategory) can be used to add new ACL command categories. Category names -can only contain alphanumeric characters, underscores, or dashes. Categories can only be added -during the `ValkeyModule_OnLoad` function. Once a category has been added, it cannot be removed. -Any module can register a command to any added categories using [`ValkeyModule_SetCommandACLCategories`](#ValkeyModule_SetCommandACLCategories). - -Returns: -- `VALKEYMODULE_OK` on successfully adding the new ACL category. -- `VALKEYMODULE_ERR` on failure. - -On error the errno is set to: -- EINVAL if the name contains invalid characters. -- EBUSY if the category name already exists. -- ENOMEM if the number of categories reached the max limit of 64 categories. - - - -### `ValkeyModule_SetCommandACLCategories` - - int ValkeyModule_SetCommandACLCategories(ValkeyModuleCommand *command, - const char *aclflags); - -**Available since:** 7.2.0 - -[`ValkeyModule_SetCommandACLCategories`](#ValkeyModule_SetCommandACLCategories) can be used to set ACL categories to module -commands and subcommands. The set of ACL categories should be passed as -a space separated C string 'aclflags'. - -Example, the acl flags 'write slow' marks the command as part of the write and -slow ACL categories. - -On success `VALKEYMODULE_OK` is returned. On error `VALKEYMODULE_ERR` is returned. - -This function can only be called during the `ValkeyModule_OnLoad` function. If called -outside of this function, an error is returned. - - - -### `ValkeyModule_SetCommandInfo` - - int ValkeyModule_SetCommandInfo(ValkeyModuleCommand *command, - const ValkeyModuleCommandInfo *info); - -**Available since:** 7.0.0 - -Set additional command information. - -Affects the output of `COMMAND`, `COMMAND INFO` and `COMMAND DOCS`, Cluster, -ACL and is used to filter commands with the wrong number of arguments before -the call reaches the module code. - -This function can be called after creating a command using [`ValkeyModule_CreateCommand`](#ValkeyModule_CreateCommand) -and fetching the command pointer using [`ValkeyModule_GetCommand`](#ValkeyModule_GetCommand). The information can -only be set once for each command and has the following structure: - - typedef struct ValkeyModuleCommandInfo { - const ValkeyModuleCommandInfoVersion *version; - const char *summary; - const char *complexity; - const char *since; - ValkeyModuleCommandHistoryEntry *history; - const char *tips; - int arity; - ValkeyModuleCommandKeySpec *key_specs; - ValkeyModuleCommandArg *args; - } ValkeyModuleCommandInfo; - -All fields except `version` are optional. Explanation of the fields: - -- `version`: This field enables compatibility with different server versions. - Always set this field to `VALKEYMODULE_COMMAND_INFO_VERSION`. - -- `summary`: A short description of the command (optional). - -- `complexity`: Complexity description (optional). - -- `since`: The version where the command was introduced (optional). - Note: The version specified should be the module's, not the server version. - -- `history`: An array of `ValkeyModuleCommandHistoryEntry` (optional), which is - a struct with the following fields: - - const char *since; - const char *changes; - - `since` is a version string and `changes` is a string describing the - changes. The array is terminated by a zeroed entry, i.e. an entry with - both strings set to NULL. - -- `tips`: A string of space-separated tips regarding this command, meant for - clients and proxies. See [https://valkey.io/topics/command-tips](https://valkey.io/topics/command-tips). - -- `arity`: Number of arguments, including the command name itself. A positive - number specifies an exact number of arguments and a negative number - specifies a minimum number of arguments, so use -N to say >= N. The server - validates a call before passing it to a module, so this can replace an - arity check inside the module command implementation. A value of 0 (or an - omitted arity field) is equivalent to -2 if the command has sub commands - and -1 otherwise. - -- `key_specs`: An array of `ValkeyModuleCommandKeySpec`, terminated by an - element memset to zero. This is a scheme that tries to describe the - positions of key arguments better than the old [`ValkeyModule_CreateCommand`](#ValkeyModule_CreateCommand) arguments - `firstkey`, `lastkey`, `keystep` and is needed if those three are not - enough to describe the key positions. There are two steps to retrieve key - positions: *begin search* (BS) in which index should find the first key and - *find keys* (FK) which, relative to the output of BS, describes how can we - will which arguments are keys. Additionally, there are key specific flags. - - Key-specs cause the triplet (firstkey, lastkey, keystep) given in - ValkeyModule_CreateCommand to be recomputed, but it is still useful to provide - these three parameters in ValkeyModule_CreateCommand, to better support old server - versions where ValkeyModule_SetCommandInfo is not available. - - Note that key-specs don't fully replace the "getkeys-api" (see - ValkeyModule_CreateCommand, ValkeyModule_IsKeysPositionRequest and ValkeyModule_KeyAtPosWithFlags) so - it may be a good idea to supply both key-specs and implement the - getkeys-api. - - A key-spec has the following structure: - - typedef struct ValkeyModuleCommandKeySpec { - const char *notes; - uint64_t flags; - ValkeyModuleKeySpecBeginSearchType begin_search_type; - union { - struct { - int pos; - } index; - struct { - const char *keyword; - int startfrom; - } keyword; - } bs; - ValkeyModuleKeySpecFindKeysType find_keys_type; - union { - struct { - int lastkey; - int keystep; - int limit; - } range; - struct { - int keynumidx; - int firstkey; - int keystep; - } keynum; - } fk; - } ValkeyModuleCommandKeySpec; - - Explanation of the fields of ValkeyModuleCommandKeySpec: - - * `notes`: Optional notes or clarifications about this key spec. - - * `flags`: A bitwise or of key-spec flags described below. - - * `begin_search_type`: This describes how the first key is discovered. - There are two ways to determine the first key: - - * `VALKEYMODULE_KSPEC_BS_UNKNOWN`: There is no way to tell where the - key args start. - * `VALKEYMODULE_KSPEC_BS_INDEX`: Key args start at a constant index. - * `VALKEYMODULE_KSPEC_BS_KEYWORD`: Key args start just after a - specific keyword. - - * `bs`: This is a union in which the `index` or `keyword` branch is used - depending on the value of the `begin_search_type` field. - - * `bs.index.pos`: The index from which we start the search for keys. - (`VALKEYMODULE_KSPEC_BS_INDEX` only.) - - * `bs.keyword.keyword`: The keyword (string) that indicates the - beginning of key arguments. (`VALKEYMODULE_KSPEC_BS_KEYWORD` only.) - - * `bs.keyword.startfrom`: An index in argv from which to start - searching. Can be negative, which means start search from the end, - in reverse. Example: -2 means to start in reverse from the - penultimate argument. (`VALKEYMODULE_KSPEC_BS_KEYWORD` only.) - - * `find_keys_type`: After the "begin search", this describes which - arguments are keys. The strategies are: - - * `VALKEYMODULE_KSPEC_BS_UNKNOWN`: There is no way to tell where the - key args are located. - * `VALKEYMODULE_KSPEC_FK_RANGE`: Keys end at a specific index (or - relative to the last argument). - * `VALKEYMODULE_KSPEC_FK_KEYNUM`: There's an argument that contains - the number of key args somewhere before the keys themselves. - - `find_keys_type` and `fk` can be omitted if this keyspec describes - exactly one key. - - * `fk`: This is a union in which the `range` or `keynum` branch is used - depending on the value of the `find_keys_type` field. - - * `fk.range` (for `VALKEYMODULE_KSPEC_FK_RANGE`): A struct with the - following fields: - - * `lastkey`: Index of the last key relative to the result of the - begin search step. Can be negative, in which case it's not - relative. -1 indicates the last argument, -2 one before the - last and so on. - - * `keystep`: How many arguments should we skip after finding a - key, in order to find the next one? - - * `limit`: If `lastkey` is -1, we use `limit` to stop the search - by a factor. 0 and 1 mean no limit. 2 means 1/2 of the - remaining args, 3 means 1/3, and so on. - - * `fk.keynum` (for `VALKEYMODULE_KSPEC_FK_KEYNUM`): A struct with the - following fields: - - * `keynumidx`: Index of the argument containing the number of - keys to come, relative to the result of the begin search step. - - * `firstkey`: Index of the fist key relative to the result of the - begin search step. (Usually it's just after `keynumidx`, in - which case it should be set to `keynumidx + 1`.) - - * `keystep`: How many arguments should we skip after finding a - key, in order to find the next one? - - Key-spec flags: - - The first four refer to what the command actually does with the *value or - metadata of the key*, and not necessarily the user data or how it affects - it. Each key-spec may must have exactly one of these. Any operation - that's not distinctly deletion, overwrite or read-only would be marked as - RW. - - * `VALKEYMODULE_CMD_KEY_RO`: Read-Only. Reads the value of the key, but - doesn't necessarily return it. - - * `VALKEYMODULE_CMD_KEY_RW`: Read-Write. Modifies the data stored in the - value of the key or its metadata. - - * `VALKEYMODULE_CMD_KEY_OW`: Overwrite. Overwrites the data stored in the - value of the key. - - * `VALKEYMODULE_CMD_KEY_RM`: Deletes the key. - - The next four refer to *user data inside the value of the key*, not the - metadata like LRU, type, cardinality. It refers to the logical operation - on the user's data (actual input strings or TTL), being - used/returned/copied/changed. It doesn't refer to modification or - returning of metadata (like type, count, presence of data). ACCESS can be - combined with one of the write operations INSERT, DELETE or UPDATE. Any - write that's not an INSERT or a DELETE would be UPDATE. - - * `VALKEYMODULE_CMD_KEY_ACCESS`: Returns, copies or uses the user data - from the value of the key. - - * `VALKEYMODULE_CMD_KEY_UPDATE`: Updates data to the value, new value may - depend on the old value. - - * `VALKEYMODULE_CMD_KEY_INSERT`: Adds data to the value with no chance of - modification or deletion of existing data. - - * `VALKEYMODULE_CMD_KEY_DELETE`: Explicitly deletes some content from the - value of the key. - - Other flags: - - * `VALKEYMODULE_CMD_KEY_NOT_KEY`: The key is not actually a key, but - should be routed in cluster mode as if it was a key. - - * `VALKEYMODULE_CMD_KEY_INCOMPLETE`: The keyspec might not point out all - the keys it should cover. - - * `VALKEYMODULE_CMD_KEY_VARIABLE_FLAGS`: Some keys might have different - flags depending on arguments. - -- `args`: An array of `ValkeyModuleCommandArg`, terminated by an element memset - to zero. `ValkeyModuleCommandArg` is a structure with at the fields described - below. - - typedef struct ValkeyModuleCommandArg { - const char *name; - ValkeyModuleCommandArgType type; - int key_spec_index; - const char *token; - const char *summary; - const char *since; - int flags; - struct ValkeyModuleCommandArg *subargs; - } ValkeyModuleCommandArg; - - Explanation of the fields: - - * `name`: Name of the argument. - - * `type`: The type of the argument. See below for details. The types - `VALKEYMODULE_ARG_TYPE_ONEOF` and `VALKEYMODULE_ARG_TYPE_BLOCK` require - an argument to have sub-arguments, i.e. `subargs`. - - * `key_spec_index`: If the `type` is `VALKEYMODULE_ARG_TYPE_KEY` you must - provide the index of the key-spec associated with this argument. See - `key_specs` above. If the argument is not a key, you may specify -1. - - * `token`: The token preceding the argument (optional). Example: the - argument `seconds` in `SET` has a token `EX`. If the argument consists - of only a token (for example `NX` in `SET`) the type should be - `VALKEYMODULE_ARG_TYPE_PURE_TOKEN` and `value` should be NULL. - - * `summary`: A short description of the argument (optional). - - * `since`: The first version which included this argument (optional). - - * `flags`: A bitwise or of the macros `VALKEYMODULE_CMD_ARG_*`. See below. - - * `value`: The display-value of the argument. This string is what should - be displayed when creating the command syntax from the output of - `COMMAND`. If `token` is not NULL, it should also be displayed. - - Explanation of `ValkeyModuleCommandArgType`: - - * `VALKEYMODULE_ARG_TYPE_STRING`: String argument. - * `VALKEYMODULE_ARG_TYPE_INTEGER`: Integer argument. - * `VALKEYMODULE_ARG_TYPE_DOUBLE`: Double-precision float argument. - * `VALKEYMODULE_ARG_TYPE_KEY`: String argument representing a keyname. - * `VALKEYMODULE_ARG_TYPE_PATTERN`: String, but regex pattern. - * `VALKEYMODULE_ARG_TYPE_UNIX_TIME`: Integer, but Unix timestamp. - * `VALKEYMODULE_ARG_TYPE_PURE_TOKEN`: Argument doesn't have a placeholder. - It's just a token without a value. Example: the `KEEPTTL` option of the - `SET` command. - * `VALKEYMODULE_ARG_TYPE_ONEOF`: Used when the user can choose only one of - a few sub-arguments. Requires `subargs`. Example: the `NX` and `XX` - options of `SET`. - * `VALKEYMODULE_ARG_TYPE_BLOCK`: Used when one wants to group together - several sub-arguments, usually to apply something on all of them, like - making the entire group "optional". Requires `subargs`. Example: the - `LIMIT offset count` parameters in `ZRANGE`. - - Explanation of the command argument flags: - - * `VALKEYMODULE_CMD_ARG_OPTIONAL`: The argument is optional (like GET in - the SET command). - * `VALKEYMODULE_CMD_ARG_MULTIPLE`: The argument may repeat itself (like - key in DEL). - * `VALKEYMODULE_CMD_ARG_MULTIPLE_TOKEN`: The argument may repeat itself, - and so does its token (like `GET pattern` in SORT). - -On success `VALKEYMODULE_OK` is returned. On error `VALKEYMODULE_ERR` is returned -and `errno` is set to EINVAL if invalid info was provided or EEXIST if info -has already been set. If the info is invalid, a warning is logged explaining -which part of the info is invalid and why. - - - -### `ValkeyModule_UpdateRuntimeArgs` - - int ValkeyModule_UpdateRuntimeArgs(ValkeyModuleCtx *ctx, - ValkeyModuleString **argv, - int argc); - -**Available since:** 8.1.0 - -[`ValkeyModule_UpdateRuntimeArgs`](#ValkeyModule_UpdateRuntimeArgs) can be used to update the module argument values. -The function parameter 'argc' indicates the number of updated arguments, and 'argv' -represents the values of the updated arguments. -Once 'CONFIG REWRITE' command is called, the updated argument values can be saved into conf file. - -The function always returns `VALKEYMODULE_OK`. - - - -## Module information and time measurement - - - -### `ValkeyModule_IsModuleNameBusy` - - int ValkeyModule_IsModuleNameBusy(const char *name); - -**Available since:** 4.0.3 - -Return non-zero if the module name is busy. -Otherwise, zero is returned. - - - -### `ValkeyModule_Milliseconds` - - mstime_t ValkeyModule_Milliseconds(void); - -**Available since:** 4.0.0 - -Return the current UNIX time in milliseconds. - - - -### `ValkeyModule_MonotonicMicroseconds` - - uint64_t ValkeyModule_MonotonicMicroseconds(void); - -**Available since:** 7.0.0 - -Return counter of micro-seconds relative to an arbitrary point in time. - - - -### `ValkeyModule_Microseconds` - - ustime_t ValkeyModule_Microseconds(void); - -**Available since:** 7.2.0 - -Return the current UNIX time in microseconds - - - -### `ValkeyModule_CachedMicroseconds` - - ustime_t ValkeyModule_CachedMicroseconds(void); - -**Available since:** 7.2.0 - -Return the cached UNIX time in microseconds. -It is updated in the server cron job and before executing a command. -It is useful for complex call stacks, such as a command causing a -key space notification, causing a module to execute a [`ValkeyModule_Call`](#ValkeyModule_Call), -causing another notification, etc. -It makes sense that all this callbacks would use the same clock. - - - -### `ValkeyModule_BlockedClientMeasureTimeStart` - - int ValkeyModule_BlockedClientMeasureTimeStart(ValkeyModuleBlockedClient *bc); - -**Available since:** 6.2.0 - -Mark a point in time that will be used as the start time to calculate -the elapsed execution time when [`ValkeyModule_BlockedClientMeasureTimeEnd()`](#ValkeyModule_BlockedClientMeasureTimeEnd) is called. -Within the same command, you can call multiple times -[`ValkeyModule_BlockedClientMeasureTimeStart()`](#ValkeyModule_BlockedClientMeasureTimeStart) and [`ValkeyModule_BlockedClientMeasureTimeEnd()`](#ValkeyModule_BlockedClientMeasureTimeEnd) -to accumulate independent time intervals to the background duration. -This method always return `VALKEYMODULE_OK`. - -This function is not thread safe, If used in module thread and blocked callback (possibly main thread) -simultaneously, it's recommended to protect them with lock owned by caller instead of GIL. - - - -### `ValkeyModule_BlockedClientMeasureTimeEnd` - - int ValkeyModule_BlockedClientMeasureTimeEnd(ValkeyModuleBlockedClient *bc); - -**Available since:** 6.2.0 - -Mark a point in time that will be used as the end time -to calculate the elapsed execution time. -On success `VALKEYMODULE_OK` is returned. -This method only returns `VALKEYMODULE_ERR` if no start time was -previously defined ( meaning [`ValkeyModule_BlockedClientMeasureTimeStart`](#ValkeyModule_BlockedClientMeasureTimeStart) was not called ). - -This function is not thread safe, If used in module thread and blocked callback (possibly main thread) -simultaneously, it's recommended to protect them with lock owned by caller instead of GIL. - - - -### `ValkeyModule_Yield` - - void ValkeyModule_Yield(ValkeyModuleCtx *ctx, - int flags, - const char *busy_reply); - -**Available since:** 7.0.0 - -This API allows modules to let the server process background tasks, and some -commands during long blocking execution of a module command. -The module can call this API periodically. -The flags is a bit mask of these: - -- `VALKEYMODULE_YIELD_FLAG_NONE`: No special flags, can perform some background - operations, but not process client commands. -- `VALKEYMODULE_YIELD_FLAG_CLIENTS`: The server can also process client commands. - -The `busy_reply` argument is optional, and can be used to control the verbose -error string after the `-BUSY` error code. - -When the `VALKEYMODULE_YIELD_FLAG_CLIENTS` is used, the server will only start -processing client commands after the time defined by the -`busy-reply-threshold` config, in which case the server will start rejecting most -commands with `-BUSY` error, but allow the ones marked with the `allow-busy` -flag to be executed. -This API can also be used in thread safe context (while locked), and during -loading (in the `rdb_load` callback, in which case it'll reject commands with -the -LOADING error) - - - -### `ValkeyModule_SetModuleOptions` - - void ValkeyModule_SetModuleOptions(ValkeyModuleCtx *ctx, int options); - -**Available since:** 6.0.0 - -Set flags defining capabilities or behavior bit flags. - -`VALKEYMODULE_OPTIONS_HANDLE_IO_ERRORS`: -Generally, modules don't need to bother with this, as the process will just -terminate if a read error happens, however, setting this flag would allow -repl-diskless-load to work if enabled. -The module should use [`ValkeyModule_IsIOError`](#ValkeyModule_IsIOError) after reads, before using the -data that was read, and in case of error, propagate it upwards, and also be -able to release the partially populated value and all it's allocations. - -`VALKEYMODULE_OPTION_NO_IMPLICIT_SIGNAL_MODIFIED`: -See [`ValkeyModule_SignalModifiedKey()`](#ValkeyModule_SignalModifiedKey). - -`VALKEYMODULE_OPTIONS_HANDLE_REPL_ASYNC_LOAD`: -Setting this flag indicates module awareness of diskless async replication (repl-diskless-load=swapdb) -and that the server could be serving reads during replication instead of blocking with LOADING status. - -`VALKEYMODULE_OPTIONS_ALLOW_NESTED_KEYSPACE_NOTIFICATIONS`: -Declare that the module wants to get nested key-space notifications. -By default, the server will not fire key-space notifications that happened inside -a key-space notification callback. This flag allows to change this behavior -and fire nested key-space notifications. Notice: if enabled, the module -should protected itself from infinite recursion. - -`VALKEYMODULE_OPTIONS_SKIP_COMMAND_VALIDATION`: -When set, this option allows the module to skip command validation. -This is useful in scenarios where the module needs to bypass -command validation for specific operations -to reduce overhead or handle trusted custom command logic. -[`ValkeyModule_Replicate`](#ValkeyModule_Replicate) and [`ValkeyModule_EmitAOF`](#ValkeyModule_EmitAOF) -are affected by this option, allowing them to operate without -command validation check. - -`VALKEYMODULE_OPTIONS_HANDLE_ATOMIC_SLOT_MIGRATION`: -When set, this option indicates that the module is capable of handling -atomic slot migration. If not set, the module is assumed to not be aware of -atomic slot migration and CLUSTER MIGRATESLOTS will return an error. Modules -should set this flag if they understand keys may be loaded during the -migration but before ownership is transferred. - -`VALKEYMODULE_OPTIONS_HANDLE_FORKLESS`: -When set, this option indicates that the module is capable of handling -forkless operations (such as a forkless background save). Opting in has the -following implications the module must acknowledge: -- While a forkless operation is running, opening a key for write with - [`ValkeyModule_OpenKey()`](#ValkeyModule_OpenKey) may return NULL when the key is in use by the operation; the - module must handle that NULL return. -- A module that registers a data type also declares that its RDB save - callbacks are thread-safe. -- A module that registers an `aux_save`/`aux_save2` function must run it only in - the `VALKEYMODULE_AUX_BEFORE_RDB` section, and it must export only limited - data (this function runs on the main thread and blocks it during a forkless - operation). -When forkless background saving is configured, if any loaded module does not -set this flag, the server falls back to fork-based saving. - - - -### `ValkeyModule_SignalModifiedKey` - - int ValkeyModule_SignalModifiedKey(ValkeyModuleCtx *ctx, - ValkeyModuleString *keyname); - -**Available since:** 6.0.0 - -Signals that the key is modified from user's perspective (i.e. invalidate WATCH -and client side caching). - -This is done automatically when a key opened for writing is closed, unless -the option `VALKEYMODULE_OPTION_NO_IMPLICIT_SIGNAL_MODIFIED` has been set using -[`ValkeyModule_SetModuleOptions()`](#ValkeyModule_SetModuleOptions). - - - -## Automatic memory management for modules - - - -### `ValkeyModule_AutoMemory` - - void ValkeyModule_AutoMemory(ValkeyModuleCtx *ctx); - -**Available since:** 4.0.0 - -Enable automatic memory management. - -The function must be called as the first function of a command implementation -that wants to use automatic memory. - -When enabled, automatic memory management tracks and automatically frees -keys, call replies and `ValkeyModuleString` objects once the command returns. In most -cases this eliminates the need of calling the following functions: - -1. [`ValkeyModule_CloseKey()`](#ValkeyModule_CloseKey) -2. [`ValkeyModule_FreeCallReply()`](#ValkeyModule_FreeCallReply) -3. [`ValkeyModule_FreeString()`](#ValkeyModule_FreeString) - -These functions can still be used with automatic memory management enabled, -to optimize loops that make numerous allocations for example. - - - -## String objects APIs - - - -### `ValkeyModule_CreateString` - - ValkeyModuleString *ValkeyModule_CreateString(ValkeyModuleCtx *ctx, - const char *ptr, - size_t len); - -**Available since:** 4.0.0 - -Create a new module string object. The returned string must be freed -with [`ValkeyModule_FreeString()`](#ValkeyModule_FreeString), unless automatic memory is enabled. - -The string is created by copying the `len` bytes starting -at `ptr`. No reference is retained to the passed buffer. - -The module context 'ctx' is optional and may be NULL if you want to create -a string out of the context scope. However in that case, the automatic -memory management will not be available, and the string memory must be -managed manually. - - - -### `ValkeyModule_CreateStringPrintf` - - ValkeyModuleString *ValkeyModule_CreateStringPrintf(ValkeyModuleCtx *ctx, - const char *fmt, - ...); - -**Available since:** 4.0.0 - -Create a new module string object from a printf format and arguments. -The returned string must be freed with [`ValkeyModule_FreeString()`](#ValkeyModule_FreeString), unless -automatic memory is enabled. - -The string is created using the sds formatter function `sdscatvprintf()`. - -The passed context 'ctx' may be NULL if necessary, see the -[`ValkeyModule_CreateString()`](#ValkeyModule_CreateString) documentation for more info. - - - -### `ValkeyModule_CreateStringFromLongLong` - - ValkeyModuleString *ValkeyModule_CreateStringFromLongLong(ValkeyModuleCtx *ctx, - long long ll); - -**Available since:** 4.0.0 - -Like [`ValkeyModule_CreateString()`](#ValkeyModule_CreateString), but creates a string starting from a `long long` -integer instead of taking a buffer and its length. - -The returned string must be released with [`ValkeyModule_FreeString()`](#ValkeyModule_FreeString) or by -enabling automatic memory management. - -The passed context 'ctx' may be NULL if necessary, see the -[`ValkeyModule_CreateString()`](#ValkeyModule_CreateString) documentation for more info. - - - -### `ValkeyModule_CreateStringFromULongLong` - - ValkeyModuleString *ValkeyModule_CreateStringFromULongLong(ValkeyModuleCtx *ctx, - unsigned long long ull); - -**Available since:** 7.0.3 - -Like [`ValkeyModule_CreateString()`](#ValkeyModule_CreateString), but creates a string starting from a `unsigned long long` -integer instead of taking a buffer and its length. - -The returned string must be released with [`ValkeyModule_FreeString()`](#ValkeyModule_FreeString) or by -enabling automatic memory management. - -The passed context 'ctx' may be NULL if necessary, see the -[`ValkeyModule_CreateString()`](#ValkeyModule_CreateString) documentation for more info. - - - -### `ValkeyModule_CreateStringFromDouble` - - ValkeyModuleString *ValkeyModule_CreateStringFromDouble(ValkeyModuleCtx *ctx, - double d); - -**Available since:** 6.0.0 - -Like [`ValkeyModule_CreateString()`](#ValkeyModule_CreateString), but creates a string starting from a double -instead of taking a buffer and its length. - -The returned string must be released with [`ValkeyModule_FreeString()`](#ValkeyModule_FreeString) or by -enabling automatic memory management. - - - -### `ValkeyModule_CreateStringFromLongDouble` - - ValkeyModuleString *ValkeyModule_CreateStringFromLongDouble(ValkeyModuleCtx *ctx, - long double ld, - int humanfriendly); - -**Available since:** 6.0.0 - -Like [`ValkeyModule_CreateString()`](#ValkeyModule_CreateString), but creates a string starting from a long -double. - -The returned string must be released with [`ValkeyModule_FreeString()`](#ValkeyModule_FreeString) or by -enabling automatic memory management. - -The passed context 'ctx' may be NULL if necessary, see the -[`ValkeyModule_CreateString()`](#ValkeyModule_CreateString) documentation for more info. - - - -### `ValkeyModule_CreateStringFromString` - - ValkeyModuleString *ValkeyModule_CreateStringFromString(ValkeyModuleCtx *ctx, - const ValkeyModuleString *str); - -**Available since:** 4.0.0 - -Like [`ValkeyModule_CreateString()`](#ValkeyModule_CreateString), but creates a string starting from another -`ValkeyModuleString`. - -The returned string must be released with [`ValkeyModule_FreeString()`](#ValkeyModule_FreeString) or by -enabling automatic memory management. - -The passed context 'ctx' may be NULL if necessary, see the -[`ValkeyModule_CreateString()`](#ValkeyModule_CreateString) documentation for more info. - - - -### `ValkeyModule_CreateStringFromStreamID` - - ValkeyModuleString *ValkeyModule_CreateStringFromStreamID(ValkeyModuleCtx *ctx, - const ValkeyModuleStreamID *id); - -**Available since:** 6.2.0 - -Creates a string from a stream ID. The returned string must be released with -[`ValkeyModule_FreeString()`](#ValkeyModule_FreeString), unless automatic memory is enabled. - -The passed context `ctx` may be NULL if necessary. See the -[`ValkeyModule_CreateString()`](#ValkeyModule_CreateString) documentation for more info. - - - -### `ValkeyModule_FreeString` - - void ValkeyModule_FreeString(ValkeyModuleCtx *ctx, ValkeyModuleString *str); - -**Available since:** 4.0.0 - -Free a module string object obtained with one of the module API calls -that return new string objects. - -It is possible to call this function even when automatic memory management -is enabled. In that case the string will be released ASAP and removed -from the pool of string to release at the end. - -If the string was created with a NULL context 'ctx', it is also possible to -pass ctx as NULL when releasing the string (but passing a context will not -create any issue). Strings created with a context should be freed also passing -the context, so if you want to free a string out of context later, make sure -to create it using a NULL context. - -This API is not thread safe, access to these retained strings (if they originated -from a client command arguments) must be done with GIL locked. - - - -### `ValkeyModule_RetainString` - - void ValkeyModule_RetainString(ValkeyModuleCtx *ctx, ValkeyModuleString *str); - -**Available since:** 4.0.0 - -Every call to this function, will make the string 'str' requiring -an additional call to [`ValkeyModule_FreeString()`](#ValkeyModule_FreeString) in order to really -free the string. Note that the automatic freeing of the string obtained -enabling modules automatic memory management counts for one -[`ValkeyModule_FreeString()`](#ValkeyModule_FreeString) call (it is just executed automatically). - -Normally you want to call this function when, at the same time -the following conditions are true: - -1. You have automatic memory management enabled. -2. You want to create string objects. -3. Those string objects you create need to live *after* the callback - function(for example a command implementation) creating them returns. - -Usually you want this in order to store the created string object -into your own data structure, for example when implementing a new data -type. - -Note that when memory management is turned off, you don't need -any call to RetainString() since creating a string will always result -into a string that lives after the callback function returns, if -no FreeString() call is performed. - -It is possible to call this function with a NULL context. - -When strings are going to be retained for an extended duration, it is good -practice to also call [`ValkeyModule_TrimStringAllocation()`](#ValkeyModule_TrimStringAllocation) in order to -optimize memory usage. - -Threaded modules that reference retained strings from other threads *must* -explicitly trim the allocation as soon as the string is retained. Not doing -so may result with automatic trimming which is not thread safe. - -This API is not thread safe, access to these retained strings (if they originated -from a client command arguments) must be done with GIL locked. - - - -### `ValkeyModule_HoldString` - - ValkeyModuleString *ValkeyModule_HoldString(ValkeyModuleCtx *ctx, - ValkeyModuleString *str); - -**Available since:** 6.0.7 - - -This function can be used instead of [`ValkeyModule_RetainString()`](#ValkeyModule_RetainString). -The main difference between the two is that this function will always -succeed, whereas [`ValkeyModule_RetainString()`](#ValkeyModule_RetainString) may fail because of an -assertion. - -The function returns a pointer to `ValkeyModuleString`, which is owned -by the caller. It requires a call to [`ValkeyModule_FreeString()`](#ValkeyModule_FreeString) to free -the string when automatic memory management is disabled for the context. -When automatic memory management is enabled, you can either call -[`ValkeyModule_FreeString()`](#ValkeyModule_FreeString) or let the automation free it. - -This function is more efficient than [`ValkeyModule_CreateStringFromString()`](#ValkeyModule_CreateStringFromString) -because whenever possible, it avoids copying the underlying -`ValkeyModuleString`. The disadvantage of using this function is that it -might not be possible to use [`ValkeyModule_StringAppendBuffer()`](#ValkeyModule_StringAppendBuffer) on the -returned `ValkeyModuleString`. - -It is possible to call this function with a NULL context. - -When strings are going to be held for an extended duration, it is good -practice to also call [`ValkeyModule_TrimStringAllocation()`](#ValkeyModule_TrimStringAllocation) in order to -optimize memory usage. - -Threaded modules that reference held strings from other threads *must* -explicitly trim the allocation as soon as the string is held. Not doing -so may result with automatic trimming which is not thread safe. - -This API is not thread safe, access to these retained strings (if they originated -from a client command arguments) must be done with GIL locked. - - - -### `ValkeyModule_StringPtrLen` - - const char *ValkeyModule_StringPtrLen(const ValkeyModuleString *str, - size_t *len); - -**Available since:** 4.0.0 - -Given a string module object, this function returns the string pointer -and length of the string. The returned pointer and length should only -be used for read only accesses and never modified. - - - -### `ValkeyModule_StringToLongLong` - - int ValkeyModule_StringToLongLong(const ValkeyModuleString *str, long long *ll); - -**Available since:** 4.0.0 - -Convert the string into a `long long` integer, storing it at `*ll`. -Returns `VALKEYMODULE_OK` on success. If the string can't be parsed -as a valid, strict `long long` (no spaces before/after), `VALKEYMODULE_ERR` -is returned. - - - -### `ValkeyModule_StringToULongLong` - - int ValkeyModule_StringToULongLong(const ValkeyModuleString *str, - unsigned long long *ull); - -**Available since:** 7.0.3 - -Convert the string into a `unsigned long long` integer, storing it at `*ull`. -Returns `VALKEYMODULE_OK` on success. If the string can't be parsed -as a valid, strict `unsigned long long` (no spaces before/after), `VALKEYMODULE_ERR` -is returned. - - - -### `ValkeyModule_StringToDouble` - - int ValkeyModule_StringToDouble(const ValkeyModuleString *str, double *d); - -**Available since:** 4.0.0 - -Convert the string into a double, storing it at `*d`. -Returns `VALKEYMODULE_OK` on success or `VALKEYMODULE_ERR` if the string is -not a valid string representation of a double value. - - - -### `ValkeyModule_StringToLongDouble` - - int ValkeyModule_StringToLongDouble(const ValkeyModuleString *str, - long double *ld); - -**Available since:** 6.0.0 - -Convert the string into a long double, storing it at `*ld`. -Returns `VALKEYMODULE_OK` on success or `VALKEYMODULE_ERR` if the string is -not a valid string representation of a double value. - - - -### `ValkeyModule_StringToStreamID` - - int ValkeyModule_StringToStreamID(const ValkeyModuleString *str, - ValkeyModuleStreamID *id); - -**Available since:** 6.2.0 - -Convert the string into a stream ID, storing it at `*id`. -Returns `VALKEYMODULE_OK` on success and returns `VALKEYMODULE_ERR` if the string -is not a valid string representation of a stream ID. The special IDs "+" and -"-" are allowed. - - - -### `ValkeyModule_StringCompare` - - int ValkeyModule_StringCompare(const ValkeyModuleString *a, - const ValkeyModuleString *b); - -**Available since:** 4.0.0 - -Compare two string objects, returning -1, 0 or 1 respectively if -a < b, a == b, a > b. Strings are compared byte by byte as two -binary blobs without any encoding care / collation attempt. - - - -### `ValkeyModule_StringAppendBuffer` - - int ValkeyModule_StringAppendBuffer(ValkeyModuleCtx *ctx, - ValkeyModuleString *str, - const char *buf, - size_t len); - -**Available since:** 4.0.0 - -Append the specified buffer to the string 'str'. The string must be a -string created by the user that is referenced only a single time; otherwise, -`VALKEYMODULE_ERR` is returned and the operation is not performed. - - - -### `ValkeyModule_TrimStringAllocation` - - void ValkeyModule_TrimStringAllocation(ValkeyModuleString *str); - -**Available since:** 7.0.0 - -Trim possible excess memory allocated for a `ValkeyModuleString`. - -Sometimes a `ValkeyModuleString` may have more memory allocated for -it than required, typically for argv arguments that were constructed -from network buffers. This function optimizes such strings by reallocating -their memory, which is useful for strings that are not short lived but -retained for an extended duration. - -This operation is *not thread safe* and should only be called when -no concurrent access to the string is guaranteed. Using it for an argv -string in a module command before the string is potentially available -to other threads is generally safe. - -Currently, the server may also automatically trim retained strings when a -module command returns. However, doing this explicitly should still be -a preferred option: - -1. Future versions of the server may abandon auto-trimming. -2. Auto-trimming as currently implemented is *not thread safe*. - A background thread manipulating a recently retained string may end up - in a race condition with the auto-trim, which could result with - data corruption. - - - -## Reply APIs - -These functions are used for sending replies to the client. - -Most functions always return `VALKEYMODULE_OK` so you can use it with -'return' in order to return from the command implementation with: - - if (... some condition ...) - return ValkeyModule_ReplyWithLongLong(ctx,mycount); - -### Reply with collection functions - -After starting a collection reply, the module must make calls to other -`ReplyWith*` style functions in order to emit the elements of the collection. -Collection types include: Array, Map, Set and Attribute. - -When producing collections with a number of elements that is not known -beforehand, the function can be called with a special flag -`VALKEYMODULE_POSTPONED_LEN` (`VALKEYMODULE_POSTPONED_ARRAY_LEN` in the past), -and the actual number of elements can be later set with `ValkeyModule_ReplySet`*Length() -call (which will set the latest "open" count if there are multiple ones). - - - -### `ValkeyModule_WrongArity` - - int ValkeyModule_WrongArity(ValkeyModuleCtx *ctx); - -**Available since:** 4.0.0 - -Send an error about the number of arguments given to the command, -citing the command name in the error message. Returns `VALKEYMODULE_OK`. - -Example: - - if (argc != 3) return ValkeyModule_WrongArity(ctx); - - - -### `ValkeyModule_ReplyWithLongLong` - - int ValkeyModule_ReplyWithLongLong(ValkeyModuleCtx *ctx, long long ll); - -**Available since:** 4.0.0 - -Send an integer reply to the client, with the specified `long long` value. -The function always returns `VALKEYMODULE_OK`. - - - -### `ValkeyModule_ReplyWithError` - - int ValkeyModule_ReplyWithError(ValkeyModuleCtx *ctx, const char *err); - -**Available since:** 4.0.0 - -Reply with the error 'err'. - -Note that 'err' must contain all the error, including -the initial error code. The function only provides the initial "-", so -the usage is, for example: - - ValkeyModule_ReplyWithError(ctx,"ERR Wrong Type"); - -and not just: - - ValkeyModule_ReplyWithError(ctx,"Wrong Type"); - -The function always returns `VALKEYMODULE_OK`. - - - -### `ValkeyModule_ReplyWithErrorFormat` - - int ValkeyModule_ReplyWithErrorFormat(ValkeyModuleCtx *ctx, - const char *fmt, - ...); - -**Available since:** 7.2.0 - -Reply with the error create from a printf format and arguments. - -Note that 'fmt' must contain all the error, including -the initial error code. The function only provides the initial "-", so -the usage is, for example: - - ValkeyModule_ReplyWithErrorFormat(ctx,"ERR Wrong Type: %s",type); - -and not just: - - ValkeyModule_ReplyWithErrorFormat(ctx,"Wrong Type: %s",type); - -The function always returns `VALKEYMODULE_OK`. - - - -### `ValkeyModule_ReplyWithCustomErrorFormat` - - int ValkeyModule_ReplyWithCustomErrorFormat(ValkeyModuleCtx *ctx, - int update_error_stats, - const char *fmt, - ...); - -**Available since:** 9.1.0 - -Reply with a custom error created from a printf format and arguments. - -`update_error_stats`: if true server error stats are updated after the reply -is sent to the client, otherwise no stats are updated. - -The function always returns `VALKEYMODULE_OK`. - - - -### `ValkeyModule_ReplyWithSimpleString` - - int ValkeyModule_ReplyWithSimpleString(ValkeyModuleCtx *ctx, const char *msg); - -**Available since:** 4.0.0 - -Reply with a simple string (`+... \r\n` in RESP protocol). This replies -are suitable only when sending a small non-binary string with small -overhead, like "OK" or similar replies. - -The function always returns `VALKEYMODULE_OK`. - - - -### `ValkeyModule_ReplyWithArray` - - int ValkeyModule_ReplyWithArray(ValkeyModuleCtx *ctx, long len); - -**Available since:** 4.0.0 - -Reply with an array type of 'len' elements. - -After starting an array reply, the module must make `len` calls to other -`ReplyWith*` style functions in order to emit the elements of the array. -See Reply APIs section for more details. - -Use [`ValkeyModule_ReplySetArrayLength()`](#ValkeyModule_ReplySetArrayLength) to set deferred length. - -The function always returns `VALKEYMODULE_OK`. - - - -### `ValkeyModule_ReplyWithMap` - - int ValkeyModule_ReplyWithMap(ValkeyModuleCtx *ctx, long len); - -**Available since:** 7.0.0 - -Reply with a RESP3 Map type of 'len' pairs. -Visit [https://valkey.io/topics/protocol](https://valkey.io/topics/protocol) for more info about RESP3. - -After starting a map reply, the module must make `len*2` calls to other -`ReplyWith*` style functions in order to emit the elements of the map. -See Reply APIs section for more details. - -If the connected client is using RESP2, the reply will be converted to a flat -array. - -Use [`ValkeyModule_ReplySetMapLength()`](#ValkeyModule_ReplySetMapLength) to set deferred length. - -The function always returns `VALKEYMODULE_OK`. - - - -### `ValkeyModule_ReplyWithSet` - - int ValkeyModule_ReplyWithSet(ValkeyModuleCtx *ctx, long len); - -**Available since:** 7.0.0 - -Reply with a RESP3 Set type of 'len' elements. -Visit [https://valkey.io/topics/protocol](https://valkey.io/topics/protocol) for more info about RESP3. - -After starting a set reply, the module must make `len` calls to other -`ReplyWith*` style functions in order to emit the elements of the set. -See Reply APIs section for more details. - -If the connected client is using RESP2, the reply will be converted to an -array type. - -Use [`ValkeyModule_ReplySetSetLength()`](#ValkeyModule_ReplySetSetLength) to set deferred length. - -The function always returns `VALKEYMODULE_OK`. - - - -### `ValkeyModule_ReplyWithAttribute` - - int ValkeyModule_ReplyWithAttribute(ValkeyModuleCtx *ctx, long len); - -**Available since:** 7.0.0 - -Add attributes (metadata) to the reply. Should be done before adding the -actual reply. see [https://valkey.io/topics/protocol](https://valkey.io/topics/protocol) - -After starting an attribute's reply, the module must make `len*2` calls to other -`ReplyWith*` style functions in order to emit the elements of the attribute map. -See Reply APIs section for more details. - -Use [`ValkeyModule_ReplySetAttributeLength()`](#ValkeyModule_ReplySetAttributeLength) to set deferred length. - -Not supported by RESP2 and will return `VALKEYMODULE_ERR`; otherwise, -the function always returns `VALKEYMODULE_OK`. - - - -### `ValkeyModule_ReplyWithNullArray` - - int ValkeyModule_ReplyWithNullArray(ValkeyModuleCtx *ctx); - -**Available since:** 6.0.0 - -Reply to the client with a null array, simply null in RESP3, -null array in RESP2. - -Note: In RESP3 there's no difference between Null reply and -NullArray reply, so to prevent ambiguity it's better to avoid -using this API and use [`ValkeyModule_ReplyWithNull`](#ValkeyModule_ReplyWithNull) instead. - -The function always returns `VALKEYMODULE_OK`. - - - -### `ValkeyModule_ReplyWithEmptyArray` - - int ValkeyModule_ReplyWithEmptyArray(ValkeyModuleCtx *ctx); - -**Available since:** 6.0.0 - -Reply to the client with an empty array. - -The function always returns `VALKEYMODULE_OK`. - - - -### `ValkeyModule_ReplySetArrayLength` - - void ValkeyModule_ReplySetArrayLength(ValkeyModuleCtx *ctx, long len); - -**Available since:** 4.0.0 - -When [`ValkeyModule_ReplyWithArray()`](#ValkeyModule_ReplyWithArray) is used with the argument -`VALKEYMODULE_POSTPONED_LEN`, because we don't know beforehand the number -of items we are going to output as elements of the array, this function -will take care to set the array length. - -Since it is possible to have multiple array replies pending with unknown -length, this function guarantees to always set the latest array length -that was created in a postponed way. - -For example in order to output an array like [1,[10,20,30]] we -could write: - - ValkeyModule_ReplyWithArray(ctx,VALKEYMODULE_POSTPONED_LEN); - ValkeyModule_ReplyWithLongLong(ctx,1); - ValkeyModule_ReplyWithArray(ctx,VALKEYMODULE_POSTPONED_LEN); - ValkeyModule_ReplyWithLongLong(ctx,10); - ValkeyModule_ReplyWithLongLong(ctx,20); - ValkeyModule_ReplyWithLongLong(ctx,30); - ValkeyModule_ReplySetArrayLength(ctx,3); // Set len of 10,20,30 array. - ValkeyModule_ReplySetArrayLength(ctx,2); // Set len of top array - -Note that in the above example there is no reason to postpone the array -length, since we produce a fixed number of elements, but in the practice -the code may use an iterator or other ways of creating the output so -that is not easy to calculate in advance the number of elements. - - - -### `ValkeyModule_ReplySetMapLength` - - void ValkeyModule_ReplySetMapLength(ValkeyModuleCtx *ctx, long len); - -**Available since:** 7.0.0 - -Very similar to [`ValkeyModule_ReplySetArrayLength`](#ValkeyModule_ReplySetArrayLength) except `len` should -exactly half of the number of `ReplyWith*` functions called in the -context of the map. -Visit [https://valkey.io/topics/protocol](https://valkey.io/topics/protocol) for more info about RESP3. - - - -### `ValkeyModule_ReplySetSetLength` - - void ValkeyModule_ReplySetSetLength(ValkeyModuleCtx *ctx, long len); - -**Available since:** 7.0.0 - -Very similar to [`ValkeyModule_ReplySetArrayLength`](#ValkeyModule_ReplySetArrayLength) -Visit [https://valkey.io/topics/protocol](https://valkey.io/topics/protocol) for more info about RESP3. - - - -### `ValkeyModule_ReplySetAttributeLength` - - void ValkeyModule_ReplySetAttributeLength(ValkeyModuleCtx *ctx, long len); - -**Available since:** 7.0.0 - -Very similar to [`ValkeyModule_ReplySetMapLength`](#ValkeyModule_ReplySetMapLength) -Visit [https://valkey.io/topics/protocol](https://valkey.io/topics/protocol) for more info about RESP3. - -Must not be called if [`ValkeyModule_ReplyWithAttribute`](#ValkeyModule_ReplyWithAttribute) returned an error. - - - -### `ValkeyModule_ReplyWithStringBuffer` - - int ValkeyModule_ReplyWithStringBuffer(ValkeyModuleCtx *ctx, - const char *buf, - size_t len); - -**Available since:** 4.0.0 - -Reply with a bulk string, taking in input a C buffer pointer and length. - -The function always returns `VALKEYMODULE_OK`. - - - -### `ValkeyModule_ReplyWithCString` - - int ValkeyModule_ReplyWithCString(ValkeyModuleCtx *ctx, const char *buf); - -**Available since:** 5.0.6 - -Reply with a bulk string, taking in input a C buffer pointer that is -assumed to be null-terminated. - -The function always returns `VALKEYMODULE_OK`. - - - -### `ValkeyModule_ReplyWithString` - - int ValkeyModule_ReplyWithString(ValkeyModuleCtx *ctx, ValkeyModuleString *str); - -**Available since:** 4.0.0 - -Reply with a bulk string, taking in input a `ValkeyModuleString` object. - -The function always returns `VALKEYMODULE_OK`. - - - -### `ValkeyModule_ReplyWithEmptyString` - - int ValkeyModule_ReplyWithEmptyString(ValkeyModuleCtx *ctx); - -**Available since:** 6.0.0 - -Reply with an empty string. - -The function always returns `VALKEYMODULE_OK`. - - - -### `ValkeyModule_ReplyWithVerbatimStringType` - - int ValkeyModule_ReplyWithVerbatimStringType(ValkeyModuleCtx *ctx, - const char *buf, - size_t len, - const char *ext); - -**Available since:** 7.0.0 - -Reply with a binary safe string, which should not be escaped or filtered -taking in input a C buffer pointer, length and a 3 character type/extension. - -The function always returns `VALKEYMODULE_OK`. - - - -### `ValkeyModule_ReplyWithVerbatimString` - - int ValkeyModule_ReplyWithVerbatimString(ValkeyModuleCtx *ctx, - const char *buf, - size_t len); - -**Available since:** 6.0.0 - -Reply with a binary safe string, which should not be escaped or filtered -taking in input a C buffer pointer and length. - -The function always returns `VALKEYMODULE_OK`. - - - -### `ValkeyModule_ReplyWithNull` - - int ValkeyModule_ReplyWithNull(ValkeyModuleCtx *ctx); - -**Available since:** 4.0.0 - -Reply to the client with a NULL. - -The function always returns `VALKEYMODULE_OK`. - - - -### `ValkeyModule_ReplyWithBool` - - int ValkeyModule_ReplyWithBool(ValkeyModuleCtx *ctx, int b); - -**Available since:** 7.0.0 - -Reply with a RESP3 Boolean type. -Visit [https://valkey.io/topics/protocol](https://valkey.io/topics/protocol) for more info about RESP3. - -In RESP3, this is boolean type -In RESP2, it's a string response of "1" and "0" for true and false respectively. - -The function always returns `VALKEYMODULE_OK`. - - - -### `ValkeyModule_ReplyWithCallReply` - - int ValkeyModule_ReplyWithCallReply(ValkeyModuleCtx *ctx, - ValkeyModuleCallReply *reply); - -**Available since:** 4.0.0 - -Reply exactly what a command returned us with [`ValkeyModule_Call()`](#ValkeyModule_Call). -This function is useful when we use [`ValkeyModule_Call()`](#ValkeyModule_Call) in order to -execute some command, as we want to reply to the client exactly the -same reply we obtained by the command. - -Return: -- `VALKEYMODULE_OK` on success. -- `VALKEYMODULE_ERR` if the given reply is in RESP3 format but the client expects RESP2. - In case of an error, it's the module writer responsibility to translate the reply - to RESP2 (or handle it differently by returning an error). Notice that for - module writer convenience, it is possible to pass `0` as a parameter to the fmt - argument of [`ValkeyModule_Call`](#ValkeyModule_Call) so that the `ValkeyModuleCallReply` will return in the same - protocol (RESP2 or RESP3) as set in the current client's context. - - - -### `ValkeyModule_ReplyWithDouble` - - int ValkeyModule_ReplyWithDouble(ValkeyModuleCtx *ctx, double d); - -**Available since:** 4.0.0 - -Reply with a RESP3 Double type. -Visit [https://valkey.io/topics/protocol](https://valkey.io/topics/protocol) for more info about RESP3. - -Send a string reply obtained converting the double 'd' into a bulk string. -This function is basically equivalent to converting a double into -a string into a C buffer, and then calling the function -[`ValkeyModule_ReplyWithStringBuffer()`](#ValkeyModule_ReplyWithStringBuffer) with the buffer and length. - -In RESP3 the string is tagged as a double, while in RESP2 it's just a plain string -that the user will have to parse. - -The function always returns `VALKEYMODULE_OK`. - - - -### `ValkeyModule_ReplyWithBigNumber` - - int ValkeyModule_ReplyWithBigNumber(ValkeyModuleCtx *ctx, - const char *bignum, - size_t len); - -**Available since:** 7.0.0 - -Reply with a RESP3 BigNumber type. -Visit [https://valkey.io/topics/protocol](https://valkey.io/topics/protocol) for more info about RESP3. - -In RESP3, this is a string of length `len` that is tagged as a BigNumber, -however, it's up to the caller to ensure that it's a valid BigNumber. -In RESP2, this is just a plain bulk string response. - -The function always returns `VALKEYMODULE_OK`. - - - -### `ValkeyModule_ReplyWithLongDouble` - - int ValkeyModule_ReplyWithLongDouble(ValkeyModuleCtx *ctx, long double ld); - -**Available since:** 6.0.0 - -Send a string reply obtained converting the long double 'ld' into a bulk -string. This function is basically equivalent to converting a long double -into a string into a C buffer, and then calling the function -[`ValkeyModule_ReplyWithStringBuffer()`](#ValkeyModule_ReplyWithStringBuffer) with the buffer and length. -The double string uses human readable formatting (see -`addReplyHumanLongDouble` in networking.c). - -The function always returns `VALKEYMODULE_OK`. - - - -## Commands replication API - - - -### `ValkeyModule_Replicate` - - int ValkeyModule_Replicate(ValkeyModuleCtx *ctx, - const char *cmdname, - const char *fmt, - ...); - -**Available since:** 4.0.0 - -Replicate the specified command and arguments to replicas and AOF, as effect -of execution of the calling command implementation. - -The replicated commands are always wrapped into the MULTI/EXEC that -contains all the commands replicated in a given module command -execution. However the commands replicated with [`ValkeyModule_Call()`](#ValkeyModule_Call) -are the first items, the ones replicated with [`ValkeyModule_Replicate()`](#ValkeyModule_Replicate) -will all follow before the EXEC. - -Modules should try to use one interface or the other. - -This command follows exactly the same interface of [`ValkeyModule_Call()`](#ValkeyModule_Call), -so a set of format specifiers must be passed, followed by arguments -matching the provided format specifiers. - -Please refer to [`ValkeyModule_Call()`](#ValkeyModule_Call) for more information. - -Using the special "A" and "R" modifiers, the caller can exclude either -the AOF or the replicas from the propagation of the specified command. -Otherwise, by default, the command will be propagated in both channels. - -#### Note about calling this function from a thread safe context: - -Normally when you call this function from the callback implementing a -module command, or any other callback provided by the Module API, -The server will accumulate all the calls to this function in the context of -the callback, and will propagate all the commands wrapped in a MULTI/EXEC -transaction. However when calling this function from a threaded safe context -that can live an undefined amount of time, and can be locked/unlocked in -at will, the behavior is different: MULTI/EXEC wrapper is not emitted -and the command specified is inserted in the AOF and replication stream -immediately. - -#### Return value - -The command returns `VALKEYMODULE_ERR` if the format specifiers are invalid, -the command name does not belong to a known command, or the server is -paused for replica traffic (e.g. during CLIENT PAUSE WRITE or CLUSTER -FAILOVER). - - - -### `ValkeyModule_ReplicateVerbatim` - - int ValkeyModule_ReplicateVerbatim(ValkeyModuleCtx *ctx); - -**Available since:** 4.0.0 - -This function will replicate the command exactly as it was invoked -by the client. Note that this function will not wrap the command into -a MULTI/EXEC stanza, so it should not be mixed with other replication -commands. - -Basically this form of replication is useful when you want to propagate -the command to the replicas and AOF file exactly as it was called, since -the command can just be re-executed to deterministically re-create the -new state starting from the old one. - -The function returns `VALKEYMODULE_ERR` if the server is paused for -replica traffic (e.g. during CLIENT PAUSE WRITE or CLUSTER FAILOVER), -otherwise `VALKEYMODULE_OK` is returned. - - - -## DB and Key APIs – Generic API - - - -### `ValkeyModule_GetClientId` - - unsigned long long ValkeyModule_GetClientId(ValkeyModuleCtx *ctx); - -**Available since:** 4.0.0 - -Return the ID of the current client calling the currently active module -command. The returned ID has a few guarantees: - -1. The ID is different for each different client, so if the same client - executes a module command multiple times, it can be recognized as - having the same ID; otherwise, the ID will be different. -2. The ID increases monotonically. Clients connecting to the server later - are guaranteed to get IDs greater than any past ID previously seen. - -Valid IDs are from 1 to 2^64 - 1. If 0 is returned it means there is no way -to fetch the ID in the context the function was currently called. - -After obtaining the ID, it is possible to check if the command execution -is actually happening in the context of AOF loading, using this macro: - - if (ValkeyModule_IsAOFClient(ValkeyModule_GetClientId(ctx)) { - // Handle it differently. - } - - - -### `ValkeyModule_GetClientUserNameById` - - ValkeyModuleString *ValkeyModule_GetClientUserNameById(ValkeyModuleCtx *ctx, - uint64_t id); - -**Available since:** 6.2.1 - -Return the ACL user name used by the client with the specified client ID. -Client ID can be obtained with [`ValkeyModule_GetClientId()`](#ValkeyModule_GetClientId) API. If the client does not -exist, NULL is returned and errno is set to ENOENT. If the client isn't -using an ACL user, NULL is returned and errno is set to ENOTSUP - - - -### `ValkeyModule_MustObeyClient` - - int ValkeyModule_MustObeyClient(ValkeyModuleCtx *ctx); - -**Available since:** 8.1.0 - -Returns 1 if commands are arriving from the primary client or AOF client -and should never be rejected. -This check can be used in places such as skipping validation of commands -on replicas (to not diverge from primary) or from AOF files. -Returns 0 otherwise (and also if ctx or if the client is NULL). - - - -### `ValkeyModule_GetClientInfoById` - - int ValkeyModule_GetClientInfoById(void *ci, uint64_t id); - -**Available since:** 6.0.0 - -Return information about the client with the specified ID (that was -previously obtained via the [`ValkeyModule_GetClientId()`](#ValkeyModule_GetClientId) API). If the -client exists, `VALKEYMODULE_OK` is returned; otherwise, `VALKEYMODULE_ERR` -is returned. - -When the client exist and the `ci` pointer is not NULL, but points to -a structure of type `ValkeyModuleClientInfoV`1, previously initialized with -the correct `VALKEYMODULE_CLIENTINFO_INITIALIZER_V1`, the structure is populated -with the following fields: - - uint64_t flags; // VALKEYMODULE_CLIENTINFO_FLAG_* - uint64_t id; // Client ID - char addr[46]; // IPv4 or IPv6 address. - uint16_t port; // TCP port. - uint16_t db; // Selected DB. - -Note: the client ID is useless in the context of this call, since we - already know, however the same structure could be used in other - contexts where we don't know the client ID, yet the same structure - is returned. - -With flags having the following meaning: - - VALKEYMODULE_CLIENTINFO_FLAG_SSL Client using SSL connection. - VALKEYMODULE_CLIENTINFO_FLAG_PUBSUB Client in Pub/Sub mode. - VALKEYMODULE_CLIENTINFO_FLAG_BLOCKED Client blocked in command. - VALKEYMODULE_CLIENTINFO_FLAG_TRACKING Client with keys tracking on. - VALKEYMODULE_CLIENTINFO_FLAG_UNIXSOCKET Client using unix domain socket. - VALKEYMODULE_CLIENTINFO_FLAG_MULTI Client in MULTI state. - VALKEYMODULE_CLIENTINFO_FLAG_READONLY Client in ReadOnly state. - VALKEYMODULE_CLIENTINFO_FLAG_PRIMARY Client is the replication link - from this replica's primary, - over which replicated commands - are applied. - VALKEYMODULE_CLIENTINFO_FLAG_REPLICA Client is a replica connection. - Also set for MONITOR clients, - together with FLAG_MONITOR. - VALKEYMODULE_CLIENTINFO_FLAG_MONITOR Client in monitor mode. - VALKEYMODULE_CLIENTINFO_FLAG_MODULE Client is a module. - VALKEYMODULE_CLIENTINFO_FLAG_AUTHENTICATED - Client has been authenticated. - VALKEYMODULE_CLIENTINFO_FLAG_EVER_AUTHENTICATED - Client has successfully been - authenticated in its lifetime. - VALKEYMODULE_CLIENTINFO_FLAG_FAKE Fake clients are internal to valkey. - -Note: The flags `VALKEYMODULE_CLIENTINFO_FLAG_PRIMARY` and below were added in Valkey 9.1. - -Passing NULL is a way to just check if the client exists in case -we are not interested in any additional information. - -This is the correct usage when we want the client info structure -returned: - - ValkeyModuleClientInfo ci = VALKEYMODULE_CLIENTINFO_INITIALIZER; - int retval = ValkeyModule_GetClientInfoById(&ci,client_id); - if (retval == VALKEYMODULE_OK) { - printf("Address: %s\n", ci.addr); - } - - - -### `ValkeyModule_GetClientNameById` - - ValkeyModuleString *ValkeyModule_GetClientNameById(ValkeyModuleCtx *ctx, - uint64_t id); - -**Available since:** 7.0.3 - -Returns the name of the client connection with the given ID. - -If the client ID does not exist or if the client has no name associated with -it, NULL is returned. - - - -### `ValkeyModule_SetClientNameById` - - int ValkeyModule_SetClientNameById(uint64_t id, ValkeyModuleString *name); - -**Available since:** 7.0.3 - -Sets the name of the client with the given ID. This is equivalent to the client calling -`CLIENT SETNAME name`. - -Returns `VALKEYMODULE_OK` on success. On failure, `VALKEYMODULE_ERR` is returned -and errno is set as follows: - -- ENOENT if the client does not exist -- EINVAL if the name contains invalid characters - - - -### `ValkeyModule_PublishMessage` - - int ValkeyModule_PublishMessage(ValkeyModuleCtx *ctx, - ValkeyModuleString *channel, - ValkeyModuleString *message); - -**Available since:** 6.0.0 - -Publish a message to subscribers (see PUBLISH command). - - - -### `ValkeyModule_PublishMessageShard` - - int ValkeyModule_PublishMessageShard(ValkeyModuleCtx *ctx, - ValkeyModuleString *channel, - ValkeyModuleString *message); - -**Available since:** 7.0.0 - -Publish a message to shard-subscribers (see SPUBLISH command). - - - -### `ValkeyModule_GetSelectedDb` - - int ValkeyModule_GetSelectedDb(ValkeyModuleCtx *ctx); - -**Available since:** 4.0.0 - -Return the currently selected DB. -When inside a MULTI/EXEC transaction, returns `transaction_db_id` which tracks -the DB selected within the transaction (may differ from client->db->id). -Otherwise, returns the client's actual DB. - - - -### `ValkeyModule_GetContextFlags` - - int ValkeyModule_GetContextFlags(ValkeyModuleCtx *ctx); - -**Available since:** 4.0.3 - -Return the current context's flags. The flags provide information on the -current request context (whether the client is a Lua script or in a MULTI), -and about the instance in general, i.e replication and persistence. - -It is possible to call this function even with a NULL context, however -in this case the following flags will not be reported: - - * LUA, MULTI, REPLICATED, DIRTY (see below for more info). - -Available flags and their meaning: - - * `VALKEYMODULE_CTX_FLAGS_LUA`: The command is running in a Lua script - - * `VALKEYMODULE_CTX_FLAGS_MULTI`: The command is running inside a transaction - - * `VALKEYMODULE_CTX_FLAGS_REPLICATED`: The command was sent over the replication - link by the PRIMARY - - * `VALKEYMODULE_CTX_FLAGS_PRIMARY`: The instance is a primary - - * `VALKEYMODULE_CTX_FLAGS_REPLICA`: The instance is a replica - - * `VALKEYMODULE_CTX_FLAGS_READONLY`: The instance is read-only - - * `VALKEYMODULE_CTX_FLAGS_CLUSTER`: The instance is in cluster mode - - * `VALKEYMODULE_CTX_FLAGS_AOF`: The instance has AOF enabled - - * `VALKEYMODULE_CTX_FLAGS_RDB`: The instance has RDB enabled - - * `VALKEYMODULE_CTX_FLAGS_MAXMEMORY`: The instance has Maxmemory set - - * `VALKEYMODULE_CTX_FLAGS_EVICT`: Maxmemory is set and has an eviction - policy that may delete keys - - * `VALKEYMODULE_CTX_FLAGS_OOM`: The server is out of memory according to the - maxmemory setting. - - * `VALKEYMODULE_CTX_FLAGS_OOM_WARNING`: Less than 25% of memory remains before - reaching the maxmemory level. - - * `VALKEYMODULE_CTX_FLAGS_LOADING`: Server is loading RDB/AOF - - * `VALKEYMODULE_CTX_FLAGS_REPLICA_IS_STALE`: No active link with the primary. - - * `VALKEYMODULE_CTX_FLAGS_REPLICA_IS_CONNECTING`: The replica is trying to - connect with the primary. - - * `VALKEYMODULE_CTX_FLAGS_REPLICA_IS_TRANSFERRING`: primary -> Replica RDB - transfer is in progress. - - * `VALKEYMODULE_CTX_FLAGS_REPLICA_IS_ONLINE`: The replica has an active link - with its primary. This is the - contrary of STALE state. - - * `VALKEYMODULE_CTX_FLAGS_ACTIVE_CHILD`: There is currently some background - process active (RDB, AUX or module). - - * `VALKEYMODULE_CTX_FLAGS_MULTI_DIRTY`: The next EXEC will fail due to dirty - CAS (touched keys). - - * `VALKEYMODULE_CTX_FLAGS_IS_CHILD`: The server is currently running inside - background child process. - - * `VALKEYMODULE_CTX_FLAGS_RESP3`: Indicate the that client attached to this - context is using RESP3. - - * `VALKEYMODULE_CTX_FLAGS_SERVER_STARTUP`: The instance is starting - - * `VALKEYMODULE_CTX_FLAGS_SLOT_IMPORT_CLIENT`: Indicate the that client attached to this - context is the slot import client. - - * `VALKEYMODULE_CTX_FLAGS_SLOT_EXPORT_CLIENT`: Indicate the that client attached to this - context is the slot export client. - - - -### `ValkeyModule_AvoidReplicaTraffic` - - int ValkeyModule_AvoidReplicaTraffic(void); - -**Available since:** 6.0.0 - -Returns true if a client sent the CLIENT PAUSE command to the server or -if the Cluster does a manual failover, pausing the clients. -This is needed when we have a primary with replicas, and want to write, -without adding further data to the replication channel, that the replicas -replication offset, match the one of the primary. When this happens, it is -safe to failover the primary without data loss. - -However modules may generate traffic by calling [`ValkeyModule_Call()`](#ValkeyModule_Call) with -the "!" flag, or by calling [`ValkeyModule_Replicate()`](#ValkeyModule_Replicate), in a context outside -commands execution, for instance in timeout callbacks, threads safe -contexts, and so forth. When modules will generate too much traffic, it -will be hard for the primary and replicas offset to match, because there -is more data to send in the replication channel. - -So modules may want to try to avoid very heavy background work that has -the effect of creating data to the replication channel, when this function -returns true. This is mostly useful for modules that have background -garbage collection tasks, or that do writes and replicate such writes -periodically in timer callbacks or other periodic callbacks. - - - -### `ValkeyModule_SelectDb` - - int ValkeyModule_SelectDb(ValkeyModuleCtx *ctx, int newid); - -**Available since:** 4.0.0 - -Change the currently selected DB. Returns an error if the id -is out of range. - -Note that the client will retain the currently selected DB even after -the command implemented by the module calling this function -returns. - -If the module command wishes to change something in a different DB and -returns back to the original one, it should call [`ValkeyModule_GetSelectedDb()`](#ValkeyModule_GetSelectedDb) -before in order to restore the old DB number before returning. - - - -### `ValkeyModule_KeyExists` - - int ValkeyModule_KeyExists(ValkeyModuleCtx *ctx, robj *keyname); - -**Available since:** 7.0.0 - -Check if a key exists, without affecting its last access time. - -This is equivalent to calling [`ValkeyModule_OpenKey`](#ValkeyModule_OpenKey) with the mode `VALKEYMODULE_READ` | -`VALKEYMODULE_OPEN_KEY_NOTOUCH`, then checking if NULL was returned and, if not, -calling [`ValkeyModule_CloseKey`](#ValkeyModule_CloseKey) on the opened key. - - - -### `ValkeyModule_OpenKey` - - ValkeyModuleKey *ValkeyModule_OpenKey(ValkeyModuleCtx *ctx, - robj *keyname, - int mode); - -**Available since:** 4.0.0 - -Return a handle representing a key, so that it is possible -to call other APIs with the key handle as argument to perform -operations on the key. - -The return value is the handle representing the key, that must be -closed with [`ValkeyModule_CloseKey()`](#ValkeyModule_CloseKey). - -If the key does not exist and `VALKEYMODULE_WRITE` mode is requested, the handle -is still returned, since it is possible to perform operations on -a yet not existing key (that will be created, for example, after -a list push operation). If the mode is just `VALKEYMODULE_READ` instead, and the -key does not exist, NULL is returned. However it is still safe to -call [`ValkeyModule_CloseKey()`](#ValkeyModule_CloseKey) and [`ValkeyModule_KeyType()`](#ValkeyModule_KeyType) on a NULL -value. - -Valkey 9.2+: When opening a key with `VALKEYMODULE_WRITE`, NULL will be returned -if the key is currently write-locked (i.e. if forkless operations are operating -on the key). This change is non-breaking as: -* Modules have to opt-in using `VALKEYMODULE_OPTIONS_HANDLE_FORKLESS` -* Module write commands are blocked (before execution), if a declared key is write-locked -The risk is only for a module that performs [`ValkeyModule_OpenKey()`](#ValkeyModule_OpenKey) on a key which was NOT -declared in the current command OR arbitrarily opens keys during a timer event. - -Extra flags that can be pass to the API under the mode argument: -* `VALKEYMODULE_OPEN_KEY_NOTOUCH` - Avoid touching the LRU/LFU of the key when opened. -* `VALKEYMODULE_OPEN_KEY_NONOTIFY` - Don't trigger keyspace event on key misses. -* `VALKEYMODULE_OPEN_KEY_NOSTATS` - Don't update keyspace hits/misses counters. -* `VALKEYMODULE_OPEN_KEY_NOEXPIRE` - Avoid deleting lazy expired keys. -* `VALKEYMODULE_OPEN_KEY_NOEFFECTS` - Avoid any effects from fetching the key. - - - -### `ValkeyModule_GetOpenKeyModesAll` - - int ValkeyModule_GetOpenKeyModesAll(void); - -**Available since:** 7.2.0 - - -Returns the full OpenKey modes mask, using the return value -the module can check if a certain set of OpenKey modes are supported -by the server version in use. -Example: - - int supportedMode = ValkeyModule_GetOpenKeyModesAll(); - if (supportedMode & VALKEYMODULE_OPEN_KEY_NOTOUCH) { - // VALKEYMODULE_OPEN_KEY_NOTOUCH is supported - } else{ - // VALKEYMODULE_OPEN_KEY_NOTOUCH is not supported - } - - - -### `ValkeyModule_CloseKey` - - void ValkeyModule_CloseKey(ValkeyModuleKey *key); - -**Available since:** 4.0.0 - -Close a key handle. The key handle is freed and should not be accessed anymore. - - - -### `ValkeyModule_KeyType` - - int ValkeyModule_KeyType(ValkeyModuleKey *key); - -**Available since:** 4.0.0 - -Return the type of the key as one of the following: - -- `VALKEYMODULE_KEYTYPE_EMPTY` -- `VALKEYMODULE_KEYTYPE_STRING` -- `VALKEYMODULE_KEYTYPE_LIST` -- `VALKEYMODULE_KEYTYPE_HASH` -- `VALKEYMODULE_KEYTYPE_SET` -- `VALKEYMODULE_KEYTYPE_ZSET` -- `VALKEYMODULE_KEYTYPE_MODULE` -- `VALKEYMODULE_KEYTYPE_STREAM` -- `VALKEYMODULE_KEYTYPE_PATH_HASH` - -If the key pointer is NULL then `VALKEYMODULE_KEYTYPE_EMPTY` is returned. - - - -### `ValkeyModule_ValueLength` - - size_t ValkeyModule_ValueLength(ValkeyModuleKey *key); - -**Available since:** 4.0.0 - -Return the length of the value associated with the key. -For strings this is the length of the string. For all the other types -is the number of elements (just counting keys for hashes). - -If the key pointer is NULL or the key is empty, zero is returned. - - - -### `ValkeyModule_DeleteKey` - - int ValkeyModule_DeleteKey(ValkeyModuleKey *key); - -**Available since:** 4.0.0 - -If the key is open for writing, remove it, and set up the key to -accept new writes as an empty key (that will be created on demand). -On success `VALKEYMODULE_OK` is returned. If the key is not open for -writing `VALKEYMODULE_ERR` is returned. - - - -### `ValkeyModule_UnlinkKey` - - int ValkeyModule_UnlinkKey(ValkeyModuleKey *key); - -**Available since:** 4.0.7 - -If the key is open for writing, unlink it (that is delete it in a -non-blocking way, not reclaiming memory immediately) and set up the key to -accept new writes as an empty key (that will be created on demand). -On success `VALKEYMODULE_OK` is returned. If the key is not open for -writing `VALKEYMODULE_ERR` is returned. - - - -### `ValkeyModule_GetExpire` - - mstime_t ValkeyModule_GetExpire(ValkeyModuleKey *key); - -**Available since:** 4.0.0 - -Return the key expire value, as milliseconds of remaining TTL. -If no TTL is associated with the key or if the key is empty, -`VALKEYMODULE_NO_EXPIRE` is returned. - - - -### `ValkeyModule_SetExpire` - - int ValkeyModule_SetExpire(ValkeyModuleKey *key, mstime_t expire); - -**Available since:** 4.0.0 - -Set a new expire for the key. If the special expire -`VALKEYMODULE_NO_EXPIRE` is set, the expire is cancelled if there was -one (the same as the PERSIST command). - -Note that the expire must be provided as a positive integer representing -the number of milliseconds of TTL the key should have. - -The function returns `VALKEYMODULE_OK` on success or `VALKEYMODULE_ERR` if -the key was not open for writing or is an empty key. - - - -### `ValkeyModule_GetAbsExpire` - - mstime_t ValkeyModule_GetAbsExpire(ValkeyModuleKey *key); - -**Available since:** 6.2.2 - -Return the key expire value, as absolute Unix timestamp. -If no TTL is associated with the key or if the key is empty, -`VALKEYMODULE_NO_EXPIRE` is returned. - - - -### `ValkeyModule_SetAbsExpire` - - int ValkeyModule_SetAbsExpire(ValkeyModuleKey *key, mstime_t expire); - -**Available since:** 6.2.2 - -Set a new expire for the key. If the special expire -`VALKEYMODULE_NO_EXPIRE` is set, the expire is cancelled if there was -one (the same as the PERSIST command). - -Note that the expire must be provided as a positive integer representing -the absolute Unix timestamp the key should have. - -The function returns `VALKEYMODULE_OK` on success or `VALKEYMODULE_ERR` if -the key was not open for writing or is an empty key. - - - -### `ValkeyModule_ResetDataset` - - void ValkeyModule_ResetDataset(int restart_aof, int async); - -**Available since:** 6.0.0 - -Performs similar operation to FLUSHALL, and optionally start a new AOF file (if enabled) -If `restart_aof` is true, you must make sure the command that triggered this call is not -propagated to the AOF file. -When async is set to true, db contents will be freed by a background thread. - - - -### `ValkeyModule_DbSize` - - unsigned long long ValkeyModule_DbSize(ValkeyModuleCtx *ctx); - -**Available since:** 6.0.0 - -Returns the number of keys in the current db. - - - -### `ValkeyModule_RandomKey` - - ValkeyModuleString *ValkeyModule_RandomKey(ValkeyModuleCtx *ctx); - -**Available since:** 6.0.0 - -Returns a name of a random key, or NULL if current db is empty. - - - -### `ValkeyModule_GetKeyNameFromOptCtx` - - const ValkeyModuleString *ValkeyModule_GetKeyNameFromOptCtx(ValkeyModuleKeyOptCtx *ctx); - -**Available since:** 7.0.0 - -Returns the name of the key currently being processed. - - - -### `ValkeyModule_GetToKeyNameFromOptCtx` - - const ValkeyModuleString *ValkeyModule_GetToKeyNameFromOptCtx(ValkeyModuleKeyOptCtx *ctx); - -**Available since:** 7.0.0 - -Returns the name of the target key currently being processed. - - - -### `ValkeyModule_GetDbIdFromOptCtx` - - int ValkeyModule_GetDbIdFromOptCtx(ValkeyModuleKeyOptCtx *ctx); - -**Available since:** 7.0.0 - -Returns the dbid currently being processed. - - - -### `ValkeyModule_GetToDbIdFromOptCtx` - - int ValkeyModule_GetToDbIdFromOptCtx(ValkeyModuleKeyOptCtx *ctx); - -**Available since:** 7.0.0 - -Returns the target dbid currently being processed. - - - -## Key API for String type - -See also [`ValkeyModule_ValueLength()`](#ValkeyModule_ValueLength), which returns the length of a string. - - - -### `ValkeyModule_StringSet` - - int ValkeyModule_StringSet(ValkeyModuleKey *key, ValkeyModuleString *str); - -**Available since:** 4.0.0 - -If the key is open for writing, set the specified string 'str' as the -value of the key, deleting the old value if any. -On success `VALKEYMODULE_OK` is returned. If the key is not open for -writing or there is an active iterator, `VALKEYMODULE_ERR` is returned. - - - -### `ValkeyModule_StringDMA` - - char *ValkeyModule_StringDMA(ValkeyModuleKey *key, size_t *len, int mode); - -**Available since:** 4.0.0 - -Prepare the key associated string value for DMA access, and returns -a pointer and size (by reference), that the user can use to read or -modify the string in-place accessing it directly via pointer. - -The 'mode' is composed by bitwise OR-ing the following flags: - - VALKEYMODULE_READ -- Read access - VALKEYMODULE_WRITE -- Write access - -If the DMA is not requested for writing, the pointer returned should -only be accessed in a read-only fashion. - -On error (wrong type) NULL is returned. - -DMA access rules: - -1. No other key writing function should be called since the moment -the pointer is obtained, for all the time we want to use DMA access -to read or modify the string. - -2. Each time [`ValkeyModule_StringTruncate()`](#ValkeyModule_StringTruncate) is called, to continue with the DMA -access, [`ValkeyModule_StringDMA()`](#ValkeyModule_StringDMA) should be called again to re-obtain -a new pointer and length. - -3. If the returned pointer is not NULL, but the length is zero, no -byte can be touched (the string is empty, or the key itself is empty) -so a [`ValkeyModule_StringTruncate()`](#ValkeyModule_StringTruncate) call should be used if there is to enlarge -the string, and later call StringDMA() again to get the pointer. - - - -### `ValkeyModule_StringTruncate` - - int ValkeyModule_StringTruncate(ValkeyModuleKey *key, size_t newlen); - -**Available since:** 4.0.0 - -If the key is open for writing and is of string type, resize it, padding -with zero bytes if the new length is greater than the old one. - -After this call, [`ValkeyModule_StringDMA()`](#ValkeyModule_StringDMA) must be called again to continue -DMA access with the new pointer. - -The function returns `VALKEYMODULE_OK` on success, and `VALKEYMODULE_ERR` on -error, that is, the key is not open for writing, is not a string -or resizing for more than 512 MB is requested. - -If the key is empty, a string key is created with the new string value -unless the new length value requested is zero. - - - -## Key API for List type - -Many of the list functions access elements by index. Since a list is in -essence a doubly-linked list, accessing elements by index is generally an -O(N) operation. However, if elements are accessed sequentially or with -indices close together, the functions are optimized to seek the index from -the previous index, rather than seeking from the ends of the list. - -This enables iteration to be done efficiently using a simple for loop: - - long n = ValkeyModule_ValueLength(key); - for (long i = 0; i < n; i++) { - ValkeyModuleString *elem = ValkeyModule_ListGet(key, i); - // Do stuff... - } - -Note that after modifying a list using [`ValkeyModule_ListPop`](#ValkeyModule_ListPop), [`ValkeyModule_ListSet`](#ValkeyModule_ListSet) or -[`ValkeyModule_ListInsert`](#ValkeyModule_ListInsert), the internal iterator is invalidated so the next operation -will require a linear seek. - -Modifying a list in any another way, for example using [`ValkeyModule_Call()`](#ValkeyModule_Call), while a key -is open will confuse the internal iterator and may cause trouble if the key -is used after such modifications. The key must be reopened in this case. - -See also [`ValkeyModule_ValueLength()`](#ValkeyModule_ValueLength), which returns the length of a list. - - - -### `ValkeyModule_ListPush` - - int ValkeyModule_ListPush(ValkeyModuleKey *key, - int where, - ValkeyModuleString *ele); - -**Available since:** 4.0.0 - -Push an element into a list, on head or tail depending on 'where' argument -(`VALKEYMODULE_LIST_HEAD` or `VALKEYMODULE_LIST_TAIL`). If the key refers to an -empty key opened for writing, the key is created. On success, `VALKEYMODULE_OK` -is returned. On failure, `VALKEYMODULE_ERR` is returned and `errno` is set as -follows: - -- EINVAL if key or ele is NULL. -- ENOTSUP if the key is of another type than list. -- EBADF if the key is not opened for writing. - -Note: Before Redis OSS 7.0, `errno` was not set by this function. - - - -### `ValkeyModule_ListPop` - - ValkeyModuleString *ValkeyModule_ListPop(ValkeyModuleKey *key, int where); - -**Available since:** 4.0.0 - -Pop an element from the list, and returns it as a module string object -that the user should be free with [`ValkeyModule_FreeString()`](#ValkeyModule_FreeString) or by enabling -automatic memory. The `where` argument specifies if the element should be -popped from the beginning or the end of the list (`VALKEYMODULE_LIST_HEAD` or -`VALKEYMODULE_LIST_TAIL`). On failure, the command returns NULL and sets -`errno` as follows: - -- EINVAL if key is NULL. -- ENOTSUP if the key is empty or of another type than list. -- EBADF if the key is not opened for writing. - -Note: Before Redis OSS 7.0, `errno` was not set by this function. - - - -### `ValkeyModule_ListGet` - - ValkeyModuleString *ValkeyModule_ListGet(ValkeyModuleKey *key, long index); - -**Available since:** 7.0.0 - -Returns the element at index `index` in the list stored at `key`, like the -LINDEX command. The element should be free'd using [`ValkeyModule_FreeString()`](#ValkeyModule_FreeString) or using -automatic memory management. - -The index is zero-based, so 0 means the first element, 1 the second element -and so on. Negative indices can be used to designate elements starting at the -tail of the list. Here, -1 means the last element, -2 means the penultimate -and so forth. - -When no value is found at the given key and index, NULL is returned and -`errno` is set as follows: - -- EINVAL if key is NULL. -- ENOTSUP if the key is not a list. -- EBADF if the key is not opened for reading. -- EDOM if the index is not a valid index in the list. - - - -### `ValkeyModule_ListSet` - - int ValkeyModule_ListSet(ValkeyModuleKey *key, - long index, - ValkeyModuleString *value); - -**Available since:** 7.0.0 - -Replaces the element at index `index` in the list stored at `key`. - -The index is zero-based, so 0 means the first element, 1 the second element -and so on. Negative indices can be used to designate elements starting at the -tail of the list. Here, -1 means the last element, -2 means the penultimate -and so forth. - -On success, `VALKEYMODULE_OK` is returned. On failure, `VALKEYMODULE_ERR` is -returned and `errno` is set as follows: - -- EINVAL if key or value is NULL. -- ENOTSUP if the key is not a list. -- EBADF if the key is not opened for writing. -- EDOM if the index is not a valid index in the list. - - - -### `ValkeyModule_ListInsert` - - int ValkeyModule_ListInsert(ValkeyModuleKey *key, - long index, - ValkeyModuleString *value); - -**Available since:** 7.0.0 - -Inserts an element at the given index. - -The index is zero-based, so 0 means the first element, 1 the second element -and so on. Negative indices can be used to designate elements starting at the -tail of the list. Here, -1 means the last element, -2 means the penultimate -and so forth. The index is the element's index after inserting it. - -On success, `VALKEYMODULE_OK` is returned. On failure, `VALKEYMODULE_ERR` is -returned and `errno` is set as follows: - -- EINVAL if key or value is NULL. -- ENOTSUP if the key of another type than list. -- EBADF if the key is not opened for writing. -- EDOM if the index is not a valid index in the list. - - - -### `ValkeyModule_ListDelete` - - int ValkeyModule_ListDelete(ValkeyModuleKey *key, long index); - -**Available since:** 7.0.0 - -Removes an element at the given index. The index is 0-based. A negative index -can also be used, counting from the end of the list. - -On success, `VALKEYMODULE_OK` is returned. On failure, `VALKEYMODULE_ERR` is -returned and `errno` is set as follows: - -- EINVAL if key or value is NULL. -- ENOTSUP if the key is not a list. -- EBADF if the key is not opened for writing. -- EDOM if the index is not a valid index in the list. - - - -## Key API for Sorted Set type - -See also [`ValkeyModule_ValueLength()`](#ValkeyModule_ValueLength), which returns the length of a sorted set. - - - -### `ValkeyModule_ZsetAdd` - - int ValkeyModule_ZsetAdd(ValkeyModuleKey *key, - double score, - ValkeyModuleString *ele, - int *flagsptr); - -**Available since:** 4.0.0 - -Add a new element into a sorted set, with the specified 'score'. -If the element already exists, the score is updated. - -A new sorted set is created at value if the key is an empty open key -setup for writing. - -Additional flags can be passed to the function via a pointer, the flags -are both used to receive input and to communicate state when the function -returns. 'flagsptr' can be NULL if no special flags are used. - -The input flags are: - - VALKEYMODULE_ZADD_XX: Element must already exist. Do nothing otherwise. - VALKEYMODULE_ZADD_NX: Element must not exist. Do nothing otherwise. - VALKEYMODULE_ZADD_GT: If element exists, new score must be greater than the current score. - Do nothing otherwise. Can optionally be combined with XX. - VALKEYMODULE_ZADD_LT: If element exists, new score must be less than the current score. - Do nothing otherwise. Can optionally be combined with XX. - -The output flags are: - - VALKEYMODULE_ZADD_ADDED: The new element was added to the sorted set. - VALKEYMODULE_ZADD_UPDATED: The score of the element was updated. - VALKEYMODULE_ZADD_NOP: No operation was performed because XX or NX flags. - -On success the function returns `VALKEYMODULE_OK`. On the following errors -`VALKEYMODULE_ERR` is returned: - -* The key was not opened for writing. -* The key is of the wrong type. -* 'score' double value is not a number (NaN). - - - -### `ValkeyModule_ZsetIncrby` - - int ValkeyModule_ZsetIncrby(ValkeyModuleKey *key, - double score, - ValkeyModuleString *ele, - int *flagsptr, - double *newscore); - -**Available since:** 4.0.0 - -This function works exactly like [`ValkeyModule_ZsetAdd()`](#ValkeyModule_ZsetAdd), but instead of setting -a new score, the score of the existing element is incremented, or if the -element does not already exist, it is added assuming the old score was -zero. - -The input and output flags, and the return value, have the same exact -meaning, with the only difference that this function will return -`VALKEYMODULE_ERR` even when 'score' is a valid double number, but adding it -to the existing score results into a NaN (not a number) condition. - -This function has an additional field 'newscore', if not NULL is filled -with the new score of the element after the increment, if no error -is returned. - - - -### `ValkeyModule_ZsetRem` - - int ValkeyModule_ZsetRem(ValkeyModuleKey *key, - ValkeyModuleString *ele, - int *deleted); - -**Available since:** 4.0.0 - -Remove the specified element from the sorted set. -The function returns `VALKEYMODULE_OK` on success, and `VALKEYMODULE_ERR` -on one of the following conditions: - -* The key was not opened for writing. -* The key is of the wrong type. - -The return value does NOT indicate the fact the element was really -removed (since it existed) or not, just if the function was executed -with success. - -In order to know if the element was removed, the additional argument -'deleted' must be passed, that populates the integer by reference -setting it to 1 or 0 depending on the outcome of the operation. -The 'deleted' argument can be NULL if the caller is not interested -to know if the element was really removed. - -Empty keys will be handled correctly by doing nothing. - - - -### `ValkeyModule_ZsetScore` - - int ValkeyModule_ZsetScore(ValkeyModuleKey *key, - ValkeyModuleString *ele, - double *score); - -**Available since:** 4.0.0 - -On success retrieve the double score associated at the sorted set element -'ele' and returns `VALKEYMODULE_OK`. Otherwise, `VALKEYMODULE_ERR` is returned -to signal one of the following conditions: - -* There is no such element 'ele' in the sorted set. -* The key is not a sorted set. -* The key is an open empty key. - - - -## Key API for Sorted Set iterator - - - -### `ValkeyModule_ZsetRangeStop` - - void ValkeyModule_ZsetRangeStop(ValkeyModuleKey *key); - -**Available since:** 4.0.0 - -Stop a sorted set iteration. - - - -### `ValkeyModule_ZsetRangeEndReached` - - int ValkeyModule_ZsetRangeEndReached(ValkeyModuleKey *key); - -**Available since:** 4.0.0 - -Return the "End of range" flag value to signal the end of the iteration: -set when the range is empty or the most recent step found no element in its -direction, cleared again by a step that moves. - - - -### `ValkeyModule_ZsetFirstInScoreRange` - - int ValkeyModule_ZsetFirstInScoreRange(ValkeyModuleKey *key, - double min, - double max, - int minex, - int maxex); - -**Available since:** 4.0.0 - -Set up a sorted set iterator seeking the first element in the specified -range. Returns `VALKEYMODULE_OK` if the iterator was correctly initialized -otherwise `VALKEYMODULE_ERR` is returned in the following conditions: - -1. The value stored at key is not a sorted set or the key is empty. - -The range is specified according to the two double values 'min' and 'max'. -Both can be infinite using the following two macros: - -* `VALKEYMODULE_POSITIVE_INFINITE` for positive infinite value -* `VALKEYMODULE_NEGATIVE_INFINITE` for negative infinite value - -'minex' and 'maxex' parameters, if true, respectively set up a range -where the min and max value are exclusive (not included) instead of -inclusive. - - - -### `ValkeyModule_ZsetLastInScoreRange` - - int ValkeyModule_ZsetLastInScoreRange(ValkeyModuleKey *key, - double min, - double max, - int minex, - int maxex); - -**Available since:** 4.0.0 - -Exactly like [`ValkeyModule_ZsetFirstInScoreRange()`](#ValkeyModule_ZsetFirstInScoreRange) but the last element of -the range is selected for the start of the iteration instead. - - - -### `ValkeyModule_ZsetFirstInLexRange` - - int ValkeyModule_ZsetFirstInLexRange(ValkeyModuleKey *key, - ValkeyModuleString *min, - ValkeyModuleString *max); - -**Available since:** 4.0.0 - -Set up a sorted set iterator seeking the first element in the specified -lexicographical range. Returns `VALKEYMODULE_OK` if the iterator was correctly -initialized otherwise `VALKEYMODULE_ERR` is returned in the -following conditions: - -1. The value stored at key is not a sorted set or the key is empty. -2. The lexicographical range 'min' and 'max' format is invalid. - -'min' and 'max' should be provided as two `ValkeyModuleString` objects -in the same format as the parameters passed to the ZRANGEBYLEX command. -The function does not take ownership of the objects, so they can be released -ASAP after the iterator is setup. - - - -### `ValkeyModule_ZsetLastInLexRange` - - int ValkeyModule_ZsetLastInLexRange(ValkeyModuleKey *key, - ValkeyModuleString *min, - ValkeyModuleString *max); - -**Available since:** 4.0.0 - -Exactly like [`ValkeyModule_ZsetFirstInLexRange()`](#ValkeyModule_ZsetFirstInLexRange) but the last element of -the range is selected for the start of the iteration instead. - - - -### `ValkeyModule_ZsetRangeCurrentElement` - - ValkeyModuleString *ValkeyModule_ZsetRangeCurrentElement(ValkeyModuleKey *key, - double *score); - -**Available since:** 4.0.0 - -Return the current sorted set element of an active sorted set iterator -or NULL if the range specified in the iterator does not include any -element. - - - -### `ValkeyModule_ZsetRangeNext` - - int ValkeyModule_ZsetRangeNext(ValkeyModuleKey *key); - -**Available since:** 4.0.0 - -Go to the next element of the sorted set iterator. Returns 1 if there was -a next element, 0 if we are already at the latest element or the range -does not include any item at all. - - - -### `ValkeyModule_ZsetRangePrev` - - int ValkeyModule_ZsetRangePrev(ValkeyModuleKey *key); - -**Available since:** 4.0.0 - -Go to the previous element of the sorted set iterator. Returns 1 if there was -a previous element, 0 if we are already at the first element or the range -does not include any item at all. - - - -## Key API for Hash type - -See also [`ValkeyModule_ValueLength()`](#ValkeyModule_ValueLength), which returns the number of fields in a hash. - - - -### `ValkeyModule_HashSetStringRef` - - int ValkeyModule_HashSetStringRef(ValkeyModuleKey *key, - ValkeyModuleString *field, - const char *buf, - size_t len); - -**Available since:** 9.1.0 - -Sets the value of a hash field to a non-owning string reference (stringRef) -pointing to the buffer parameter, which remains owned by the module. - -NOTE: This API is designed for memory efficiency by avoiding memory duplication -between the module and the core engine, which is critical when the buffer size is large. -For example, valkey-search uses this interface to avoid maintaining two copies of the -indexed vectors. - -The function receives the hash key, field name, buffer to share along with its size. - -Returns `VALKEYMODULE_OK` on success. Returns `VALKEYMODULE_ERR` if the key or field -is missing, the key is not a hash, or the update fails. - - - -### `ValkeyModule_HashHasStringRef` - - int ValkeyModule_HashHasStringRef(ValkeyModuleKey *key, - ValkeyModuleString *field); - -**Available since:** 9.1.0 - -Checks if the value of a hash entry is a shared string reference (stringRef). -The function receives the hash key and field name to perform the check against. - -Returns 1 if the field exists and holds a string reference. Returns 0 in every -other case, including a missing or non-hash key, a missing field name and a -field which doesn't exist or is already expired. Note that the return value is -a plain boolean and not an OK/ERR status, since `VALKEYMODULE_ERR` can't be told -apart from a positive answer. - - - -### `ValkeyModule_HashSet` - - int ValkeyModule_HashSet(ValkeyModuleKey *key, int flags, ...); - -**Available since:** 4.0.0 - -Set the field of the specified hash field to the specified value. -If the key is an empty key open for writing, it is created with an empty -hash value, in order to set the specified field. - -The function is variadic and the user must specify pairs of field -names and values, both as `ValkeyModuleString` pointers (unless the -CFIELD option is set, see later). At the end of the field/value-ptr pairs, -NULL must be specified as last argument to signal the end of the arguments -in the variadic function. - -Example to set the hash argv[1] to the value argv[2]: - - ValkeyModule_HashSet(key,VALKEYMODULE_HASH_NONE,argv[1],argv[2],NULL); - -The function can also be used in order to delete fields (if they exist) -by setting them to the specified value of `VALKEYMODULE_HASH_DELETE`: - - ValkeyModule_HashSet(key,VALKEYMODULE_HASH_NONE,argv[1], - VALKEYMODULE_HASH_DELETE,NULL); - -The behavior of the command changes with the specified flags, that can be -set to `VALKEYMODULE_HASH_NONE` if no special behavior is needed. - - VALKEYMODULE_HASH_NX: The operation is performed only if the field was not - already existing in the hash. - VALKEYMODULE_HASH_XX: The operation is performed only if the field was - already existing, so that a new value could be - associated to an existing filed, but no new fields - are created. - VALKEYMODULE_HASH_CFIELDS: The field names passed are null terminated C - strings instead of ValkeyModuleString objects. - VALKEYMODULE_HASH_COUNT_ALL: Include the number of inserted fields in the - returned number, in addition to the number of - updated and deleted fields. (Added in Redis OSS - 6.2.) - -Unless NX is specified, the command overwrites the old field value with -the new one. - -When using `VALKEYMODULE_HASH_CFIELDS`, field names are reported using -normal C strings, so for example to delete the field "foo" the following -code can be used: - - ValkeyModule_HashSet(key,VALKEYMODULE_HASH_CFIELDS,"foo", - VALKEYMODULE_HASH_DELETE,NULL); - -Return value: - -The number of fields existing in the hash prior to the call, which have been -updated (its old value has been replaced by a new value) or deleted. If the -flag `VALKEYMODULE_HASH_COUNT_ALL` is set, inserted fields not previously -existing in the hash are also counted. - -If the return value is zero, `errno` is set (since Redis OSS 6.2) as follows: - -- EINVAL if any unknown flags are set or if key is NULL. -- ENOTSUP if the key is associated with a non Hash value. -- EBADF if the key was not opened for writing. -- ENOENT if no fields were counted as described under Return value above. - This is not actually an error. The return value can be zero if all fields - were just created and the `COUNT_ALL` flag was unset, or if changes were held - back due to the NX and XX flags. - -NOTICE: The return value semantics of this function are very different -between Redis OSS 6.2 and older versions. Modules that use it should determine -the server version and handle it accordingly. - - - -### `ValkeyModule_HashGet` - - int ValkeyModule_HashGet(ValkeyModuleKey *key, int flags, ...); - -**Available since:** 4.0.0 - -Get fields from a hash value. This function is called using a variable -number of arguments, alternating a field name (as a `ValkeyModuleString` -pointer) with a pointer to a `ValkeyModuleString` pointer, that is set to the -value of the field if the field exists, or NULL if the field does not exist. -At the end of the field/value-ptr pairs, NULL must be specified as last -argument to signal the end of the arguments in the variadic function. - -This is an example usage: - - ValkeyModuleString *first, *second; - ValkeyModule_HashGet(mykey,VALKEYMODULE_HASH_NONE,argv[1],&first, - argv[2],&second,NULL); - -As with [`ValkeyModule_HashSet()`](#ValkeyModule_HashSet) the behavior of the command can be specified -passing flags different than `VALKEYMODULE_HASH_NONE`: - -`VALKEYMODULE_HASH_CFIELDS`: field names as null terminated C strings. - -`VALKEYMODULE_HASH_EXISTS`: instead of setting the value of the field -expecting a `ValkeyModuleString` pointer to pointer, the function just -reports if the field exists or not and expects an integer pointer -as the second element of each pair. - -Example of `VALKEYMODULE_HASH_CFIELDS`: - - ValkeyModuleString *username, *hashedpass; - ValkeyModule_HashGet(mykey,VALKEYMODULE_HASH_CFIELDS,"username",&username,"hp",&hashedpass, NULL); - -Example of `VALKEYMODULE_HASH_EXISTS`: - - int exists; - ValkeyModule_HashGet(mykey,VALKEYMODULE_HASH_EXISTS,argv[1],&exists,NULL); - -The function returns `VALKEYMODULE_OK` on success and `VALKEYMODULE_ERR` if -the key is not a hash value. - -Memory management: - -The returned `ValkeyModuleString` objects should be released with -[`ValkeyModule_FreeString()`](#ValkeyModule_FreeString), or by enabling automatic memory management. - - - -## Key API for Stream type - -For an introduction to streams, see [https://valkey.io/topics/streams-intro](https://valkey.io/topics/streams-intro). - -The type `ValkeyModuleStreamID`, which is used in stream functions, is a struct -with two 64-bit fields and is defined as - - typedef struct ValkeyModuleStreamID { - uint64_t ms; - uint64_t seq; - } ValkeyModuleStreamID; - -See also [`ValkeyModule_ValueLength()`](#ValkeyModule_ValueLength), which returns the length of a stream, and the -conversion functions [`ValkeyModule_StringToStreamID()`](#ValkeyModule_StringToStreamID) and [`ValkeyModule_CreateStringFromStreamID()`](#ValkeyModule_CreateStringFromStreamID). - - - -### `ValkeyModule_StreamAdd` - - int ValkeyModule_StreamAdd(ValkeyModuleKey *key, - int flags, - ValkeyModuleStreamID *id, - ValkeyModuleString **argv, - long numfields); - -**Available since:** 6.2.0 - -Adds an entry to a stream. Like XADD without trimming. - -- `key`: The key where the stream is (or will be) stored -- `flags`: A bit field of - - `VALKEYMODULE_STREAM_ADD_AUTOID`: Assign a stream ID automatically, like - `*` in the XADD command. -- `id`: If the `AUTOID` flag is set, this is where the assigned ID is - returned. Can be NULL if `AUTOID` is set, if you don't care to receive the - ID. If `AUTOID` is not set, this is the requested ID. -- `argv`: A pointer to an array of size `numfields * 2` containing the - fields and values. -- `numfields`: The number of field-value pairs in `argv`. - -Returns `VALKEYMODULE_OK` if an entry has been added. On failure, -`VALKEYMODULE_ERR` is returned and `errno` is set as follows: - -- EINVAL if called with invalid arguments -- ENOTSUP if the key refers to a value of a type other than stream -- EBADF if the key was not opened for writing -- EDOM if the given ID was 0-0 or not greater than all other IDs in the - stream (only if the AUTOID flag is unset) -- EFBIG if the stream has reached the last possible ID -- ERANGE if the elements are too large to be stored. - - - -### `ValkeyModule_StreamDelete` - - int ValkeyModule_StreamDelete(ValkeyModuleKey *key, ValkeyModuleStreamID *id); - -**Available since:** 6.2.0 - -Deletes an entry from a stream. - -- `key`: A key opened for writing, with no stream iterator started. -- `id`: The stream ID of the entry to delete. - -Returns `VALKEYMODULE_OK` on success. On failure, `VALKEYMODULE_ERR` is returned -and `errno` is set as follows: - -- EINVAL if called with invalid arguments -- ENOTSUP if the key refers to a value of a type other than stream or if the - key is empty -- EBADF if the key was not opened for writing or if a stream iterator is - associated with the key -- ENOENT if no entry with the given stream ID exists - -See also [`ValkeyModule_StreamIteratorDelete()`](#ValkeyModule_StreamIteratorDelete) for deleting the current entry while -iterating using a stream iterator. - - - -### `ValkeyModule_StreamIteratorStart` - - int ValkeyModule_StreamIteratorStart(ValkeyModuleKey *key, - int flags, - ValkeyModuleStreamID *start, - ValkeyModuleStreamID *end); - -**Available since:** 6.2.0 - -Sets up a stream iterator. - -- `key`: The stream key opened for reading using [`ValkeyModule_OpenKey()`](#ValkeyModule_OpenKey). -- `flags`: - - `VALKEYMODULE_STREAM_ITERATOR_EXCLUSIVE`: Don't include `start` and `end` - in the iterated range. - - `VALKEYMODULE_STREAM_ITERATOR_REVERSE`: Iterate in reverse order, starting - from the `end` of the range. -- `start`: The lower bound of the range. Use NULL for the beginning of the - stream. -- `end`: The upper bound of the range. Use NULL for the end of the stream. - -Returns `VALKEYMODULE_OK` on success. On failure, `VALKEYMODULE_ERR` is returned -and `errno` is set as follows: - -- EINVAL if called with invalid arguments -- ENOTSUP if the key refers to a value of a type other than stream or if the - key is empty -- EBADF if the key was not opened for writing or if a stream iterator is - already associated with the key -- EDOM if `start` or `end` is outside the valid range - -Returns `VALKEYMODULE_OK` on success and `VALKEYMODULE_ERR` if the key doesn't -refer to a stream or if invalid arguments were given. - -The stream IDs are retrieved using [`ValkeyModule_StreamIteratorNextID()`](#ValkeyModule_StreamIteratorNextID) and -for each stream ID, the fields and values are retrieved using -[`ValkeyModule_StreamIteratorNextField()`](#ValkeyModule_StreamIteratorNextField). The iterator is freed by calling -[`ValkeyModule_StreamIteratorStop()`](#ValkeyModule_StreamIteratorStop). - -Example (error handling omitted): - - ValkeyModule_StreamIteratorStart(key, 0, startid_ptr, endid_ptr); - ValkeyModuleStreamID id; - long numfields; - while (ValkeyModule_StreamIteratorNextID(key, &id, &numfields) == - VALKEYMODULE_OK) { - ValkeyModuleString *field, *value; - while (ValkeyModule_StreamIteratorNextField(key, &field, &value) == - VALKEYMODULE_OK) { - // - // ... Do stuff ... - // - ValkeyModule_FreeString(ctx, field); - ValkeyModule_FreeString(ctx, value); - } - } - ValkeyModule_StreamIteratorStop(key); - - - -### `ValkeyModule_StreamIteratorStop` - - int ValkeyModule_StreamIteratorStop(ValkeyModuleKey *key); - -**Available since:** 6.2.0 - -Stops a stream iterator created using [`ValkeyModule_StreamIteratorStart()`](#ValkeyModule_StreamIteratorStart) and -reclaims its memory. - -Returns `VALKEYMODULE_OK` on success. On failure, `VALKEYMODULE_ERR` is returned -and `errno` is set as follows: - -- EINVAL if called with a NULL key -- ENOTSUP if the key refers to a value of a type other than stream or if the - key is empty -- EBADF if the key was not opened for writing or if no stream iterator is - associated with the key - - - -### `ValkeyModule_StreamIteratorNextID` - - int ValkeyModule_StreamIteratorNextID(ValkeyModuleKey *key, - ValkeyModuleStreamID *id, - long *numfields); - -**Available since:** 6.2.0 - -Finds the next stream entry and returns its stream ID and the number of -fields. - -- `key`: Key for which a stream iterator has been started using - [`ValkeyModule_StreamIteratorStart()`](#ValkeyModule_StreamIteratorStart). -- `id`: The stream ID returned. NULL if you don't care. -- `numfields`: The number of fields in the found stream entry. NULL if you - don't care. - -Returns `VALKEYMODULE_OK` and sets `*id` and `*numfields` if an entry was found. -On failure, `VALKEYMODULE_ERR` is returned and `errno` is set as follows: - -- EINVAL if called with a NULL key -- ENOTSUP if the key refers to a value of a type other than stream or if the - key is empty -- EBADF if no stream iterator is associated with the key -- ENOENT if there are no more entries in the range of the iterator - -In practice, if [`ValkeyModule_StreamIteratorNextID()`](#ValkeyModule_StreamIteratorNextID) is called after a successful call -to [`ValkeyModule_StreamIteratorStart()`](#ValkeyModule_StreamIteratorStart) and with the same key, it is safe to assume that -an `VALKEYMODULE_ERR` return value means that there are no more entries. - -Use [`ValkeyModule_StreamIteratorNextField()`](#ValkeyModule_StreamIteratorNextField) to retrieve the fields and values. -See the example at [`ValkeyModule_StreamIteratorStart()`](#ValkeyModule_StreamIteratorStart). - - - -### `ValkeyModule_StreamIteratorNextField` - - int ValkeyModule_StreamIteratorNextField(ValkeyModuleKey *key, - ValkeyModuleString **field_ptr, - ValkeyModuleString **value_ptr); - -**Available since:** 6.2.0 - -Retrieves the next field of the current stream ID and its corresponding value -in a stream iteration. This function should be called repeatedly after calling -[`ValkeyModule_StreamIteratorNextID()`](#ValkeyModule_StreamIteratorNextID) to fetch each field-value pair. - -- `key`: Key where a stream iterator has been started. -- `field_ptr`: This is where the field is returned. -- `value_ptr`: This is where the value is returned. - -Returns `VALKEYMODULE_OK` and points `*field_ptr` and `*value_ptr` to freshly -allocated `ValkeyModuleString` objects. The string objects are freed -automatically when the callback finishes if automatic memory is enabled. On -failure, `VALKEYMODULE_ERR` is returned and `errno` is set as follows: - -- EINVAL if called with a NULL key -- ENOTSUP if the key refers to a value of a type other than stream or if the - key is empty -- EBADF if no stream iterator is associated with the key -- ENOENT if there are no more fields in the current stream entry - -In practice, if [`ValkeyModule_StreamIteratorNextField()`](#ValkeyModule_StreamIteratorNextField) is called after a successful -call to [`ValkeyModule_StreamIteratorNextID()`](#ValkeyModule_StreamIteratorNextID) and with the same key, it is safe to assume -that an `VALKEYMODULE_ERR` return value means that there are no more fields. - -See the example at [`ValkeyModule_StreamIteratorStart()`](#ValkeyModule_StreamIteratorStart). - - - -### `ValkeyModule_StreamIteratorDelete` - - int ValkeyModule_StreamIteratorDelete(ValkeyModuleKey *key); - -**Available since:** 6.2.0 - -Deletes the current stream entry while iterating. - -This function can be called after [`ValkeyModule_StreamIteratorNextID()`](#ValkeyModule_StreamIteratorNextID) or after any -calls to [`ValkeyModule_StreamIteratorNextField()`](#ValkeyModule_StreamIteratorNextField). - -Returns `VALKEYMODULE_OK` on success. On failure, `VALKEYMODULE_ERR` is returned -and `errno` is set as follows: - -- EINVAL if key is NULL -- ENOTSUP if the key is empty or is of another type than stream -- EBADF if the key is not opened for writing, if no iterator has been started -- ENOENT if the iterator has no current stream entry - - - -### `ValkeyModule_StreamTrimByLength` - - long long ValkeyModule_StreamTrimByLength(ValkeyModuleKey *key, - int flags, - long long length); - -**Available since:** 6.2.0 - -Trim a stream by length, similar to XTRIM with MAXLEN. - -- `key`: Key opened for writing. -- `flags`: A bitfield of - - `VALKEYMODULE_STREAM_TRIM_APPROX`: Trim less if it improves performance, - like XTRIM with `~`. -- `length`: The number of stream entries to keep after trimming. - -Returns the number of entries deleted. On failure, a negative value is -returned and `errno` is set as follows: - -- EINVAL if called with invalid arguments -- ENOTSUP if the key is empty or of a type other than stream -- EBADF if the key is not opened for writing - - - -### `ValkeyModule_StreamTrimByID` - - long long ValkeyModule_StreamTrimByID(ValkeyModuleKey *key, - int flags, - ValkeyModuleStreamID *id); - -**Available since:** 6.2.0 - -Trim a stream by ID, similar to XTRIM with MINID. - -- `key`: Key opened for writing. -- `flags`: A bitfield of - - `VALKEYMODULE_STREAM_TRIM_APPROX`: Trim less if it improves performance, - like XTRIM with `~`. -- `id`: The smallest stream ID to keep after trimming. - -Returns the number of entries deleted. On failure, a negative value is -returned and `errno` is set as follows: - -- EINVAL if called with invalid arguments -- ENOTSUP if the key is empty or of a type other than stream -- EBADF if the key is not opened for writing - - - -## Calling commands from modules - -[`ValkeyModule_Call()`](#ValkeyModule_Call) sends a command to the server. The remaining functions handle the reply. - - - -### `ValkeyModule_FreeCallReply` - - void ValkeyModule_FreeCallReply(ValkeyModuleCallReply *reply); - -**Available since:** 4.0.0 - -Free a Call reply and all the nested replies it contains if it's an -array. - - - -### `ValkeyModule_CallReplyType` - - int ValkeyModule_CallReplyType(ValkeyModuleCallReply *reply); - -**Available since:** 4.0.0 - -Return the reply type as one of the following: - -- `VALKEYMODULE_REPLY_UNKNOWN` -- `VALKEYMODULE_REPLY_STRING` -- `VALKEYMODULE_REPLY_ERROR` -- `VALKEYMODULE_REPLY_INTEGER` -- `VALKEYMODULE_REPLY_ARRAY` -- `VALKEYMODULE_REPLY_NULL` -- `VALKEYMODULE_REPLY_MAP` -- `VALKEYMODULE_REPLY_SET` -- `VALKEYMODULE_REPLY_BOOL` -- `VALKEYMODULE_REPLY_DOUBLE` -- `VALKEYMODULE_REPLY_BIG_NUMBER` -- `VALKEYMODULE_REPLY_VERBATIM_STRING` -- `VALKEYMODULE_REPLY_ATTRIBUTE` -- `VALKEYMODULE_REPLY_SIMPLE_STRING` -- `VALKEYMODULE_REPLY_ARRAY_NULL` -- `VALKEYMODULE_REPLY_PROMISE` - - - -### `ValkeyModule_CallReplyLength` - - size_t ValkeyModule_CallReplyLength(ValkeyModuleCallReply *reply); - -**Available since:** 4.0.0 - -Return the reply type length, where applicable. - - - -### `ValkeyModule_CallReplyArrayElement` - - ValkeyModuleCallReply *ValkeyModule_CallReplyArrayElement(ValkeyModuleCallReply *reply, - size_t idx); - -**Available since:** 4.0.0 - -Return the 'idx'-th nested call reply element of an array reply, or NULL -if the reply type is wrong or the index is out of range. - - - -### `ValkeyModule_CallReplyInteger` - - long long ValkeyModule_CallReplyInteger(ValkeyModuleCallReply *reply); - -**Available since:** 4.0.0 - -Return the `long long` of an integer reply. - - - -### `ValkeyModule_CallReplyDouble` - - double ValkeyModule_CallReplyDouble(ValkeyModuleCallReply *reply); - -**Available since:** 7.0.0 - -Return the double value of a double reply. - - - -### `ValkeyModule_CallReplyBigNumber` - - const char *ValkeyModule_CallReplyBigNumber(ValkeyModuleCallReply *reply, - size_t *len); - -**Available since:** 7.0.0 - -Return the big number value of a big number reply. - - - -### `ValkeyModule_CallReplyVerbatim` - - const char *ValkeyModule_CallReplyVerbatim(ValkeyModuleCallReply *reply, - size_t *len, - const char **format); - -**Available since:** 7.0.0 - -Return the value of a verbatim string reply, -An optional output argument can be given to get verbatim reply format. - - - -### `ValkeyModule_CallReplyBool` - - int ValkeyModule_CallReplyBool(ValkeyModuleCallReply *reply); - -**Available since:** 7.0.0 - -Return the Boolean value of a Boolean reply. - - - -### `ValkeyModule_CallReplySetElement` - - ValkeyModuleCallReply *ValkeyModule_CallReplySetElement(ValkeyModuleCallReply *reply, - size_t idx); - -**Available since:** 7.0.0 - -Return the 'idx'-th nested call reply element of a set reply, or NULL -if the reply type is wrong or the index is out of range. - - - -### `ValkeyModule_CallReplyMapElement` - - int ValkeyModule_CallReplyMapElement(ValkeyModuleCallReply *reply, - size_t idx, - ValkeyModuleCallReply **key, - ValkeyModuleCallReply **val); - -**Available since:** 7.0.0 - -Retrieve the 'idx'-th key and value of a map reply. - -Returns: -- `VALKEYMODULE_OK` on success. -- `VALKEYMODULE_ERR` if idx out of range or if the reply type is wrong. - -The `key` and `value` arguments are used to return by reference, and may be -NULL if not required. - - - -### `ValkeyModule_CallReplyAttribute` - - ValkeyModuleCallReply *ValkeyModule_CallReplyAttribute(ValkeyModuleCallReply *reply); - -**Available since:** 7.0.0 - -Return the attribute of the given reply, or NULL if no attribute exists. - - - -### `ValkeyModule_CallReplyAttributeElement` - - int ValkeyModule_CallReplyAttributeElement(ValkeyModuleCallReply *reply, - size_t idx, - ValkeyModuleCallReply **key, - ValkeyModuleCallReply **val); - -**Available since:** 7.0.0 - -Retrieve the 'idx'-th key and value of an attribute reply. - -Returns: -- `VALKEYMODULE_OK` on success. -- `VALKEYMODULE_ERR` if idx out of range or if the reply type is wrong. - -The `key` and `value` arguments are used to return by reference, and may be -NULL if not required. - - - -### `ValkeyModule_CallReplyPromiseSetUnblockHandler` - - void ValkeyModule_CallReplyPromiseSetUnblockHandler(ValkeyModuleCallReply *reply, - ValkeyModuleOnUnblocked on_unblock, - void *private_data); - -**Available since:** 7.2.0 - -Set unblock handler (callback and private data) on the given promise `ValkeyModuleCallReply`. -The given reply must be of promise type (`VALKEYMODULE_REPLY_PROMISE`). - - - -### `ValkeyModule_CallReplyPromiseAbort` - - int ValkeyModule_CallReplyPromiseAbort(ValkeyModuleCallReply *reply, - void **private_data); - -**Available since:** 7.2.0 - -Abort the execution of a given promise `ValkeyModuleCallReply`. -return `REDMODULE_OK` in case the abort was done successfully and `VALKEYMODULE_ERR` -if its not possible to abort the execution (execution already finished). -In case the execution was aborted (`REDMODULE_OK` was returned), the `private_data` out parameter -will be set with the value of the private data that was given on '[`ValkeyModule_CallReplyPromiseSetUnblockHandler`](#ValkeyModule_CallReplyPromiseSetUnblockHandler)' -so the caller will be able to release the private data. - -If the execution was aborted successfully, it is promised that the unblock handler will not be called. -That said, it is possible that the abort operation will successes but the operation will still continue. -This can happened if, for example, a module implements some blocking command and does not respect the -disconnect callback. For server-provided commands this cannot happened. - - - -### `ValkeyModule_CallReplyStringPtr` - - const char *ValkeyModule_CallReplyStringPtr(ValkeyModuleCallReply *reply, - size_t *len); - -**Available since:** 4.0.0 - -Return the pointer and length of a string or error reply. - - - -### `ValkeyModule_CreateStringFromCallReply` - - ValkeyModuleString *ValkeyModule_CreateStringFromCallReply(ValkeyModuleCallReply *reply); - -**Available since:** 4.0.0 - -Return a new string object from a call reply of type string, error or -integer. Otherwise, (wrong reply type) return NULL. - - - -### `ValkeyModule_SetContextUser` - - void ValkeyModule_SetContextUser(ValkeyModuleCtx *ctx, - const ValkeyModuleUser *user); - -**Available since:** 7.0.6 - -Modifies the user that [`ValkeyModule_Call`](#ValkeyModule_Call) will use (e.g. for ACL checks) - - - -### `ValkeyModule_Call` - - ValkeyModuleCallReply *ValkeyModule_Call(ValkeyModuleCtx *ctx, - const char *cmdname, - const char *fmt, - ...); - -**Available since:** 4.0.0 - -Exported API to call any command from modules. - -* **cmdname**: The command to call. -* **fmt**: A format specifier string for the command's arguments. Each - of the arguments should be specified by a valid type specification. The - format specifier can also contain the modifiers `!`, `A`, `3` and `R` which - don't have a corresponding argument. - - * `b` -- The argument is a buffer and is immediately followed by another - argument that is the buffer's length. - * `c` -- The argument is a pointer to a plain C string (null-terminated). - * `l` -- The argument is a `long long` integer. - * `s` -- The argument is a ValkeyModuleString. - * `v` -- The argument(s) is a vector of ValkeyModuleString. - * `!` -- Sends the command and its arguments to replicas and AOF. - * `A` -- Suppress AOF propagation, send only to replicas (requires `!`). - * `R` -- Suppress replicas propagation, send only to AOF (requires `!`). - * `3` -- Return a RESP3 reply. This will change the command reply. - e.g., HGETALL returns a map instead of a flat array. - * `0` -- Return the reply in auto mode, i.e. the reply format will be the - same as the client attached to the given ValkeyModuleCtx. This will - probably used when you want to pass the reply directly to the client. - * `C` -- Run a command as the user attached to the context. - User is either attached automatically via the client that directly - issued the command and created the context or via ValkeyModule_SetContextUser. - If the context is not directly created by an issued command (such as a - background context and no user was set on it via ValkeyModule_SetContextUser, - ValkeyModule_Call will fail. - Checks if the command can be executed according to ACL rules and causes - the command to run as the determined user, so that any future user - dependent activity, such as ACL checks within scripts will proceed as - expected. - Otherwise, the command will run as the unrestricted user. - * `S` -- Run the command in a script mode, this means that it will raise - an error if a command which are not allowed inside a script - (flagged with the `deny-script` flag) is invoked (like SHUTDOWN). - In addition, on script mode, write commands are not allowed if there are - not enough good replicas (as configured with `min-replicas-to-write`) - or when the server is unable to persist to the disk. - * `W` -- Do not allow to run any write command (flagged with the `write` flag). - * `M` -- Do not allow `deny-oom` flagged commands when over the memory limit. - * `E` -- Return error as ValkeyModuleCallReply. If there is an error before - invoking the command, the error is returned using errno mechanism. - This flag allows to get the error also as an error CallReply with - relevant error message. - * 'D' -- A "Dry Run" mode. Return before executing the underlying call(). - If everything succeeded, it will return with a NULL; otherwise, it will - return with a CallReply object denoting the error, as if it was called with - the 'E' code. - * 'K' -- Allow running blocking commands. If enabled and the command gets blocked, a - special VALKEYMODULE_REPLY_PROMISE will be returned. This reply type - indicates that the command was blocked and the reply will be given asynchronously. - The module can use this reply object to set a handler which will be called when - the command gets unblocked using ValkeyModule_CallReplyPromiseSetUnblockHandler. - The handler must be set immediately after the command invocation (without releasing - the lock in between). If the handler is not set, the blocking command will - still continue its execution but the reply will be ignored (fire and forget), - notice that this is dangerous in case of role change, as explained below. - The module can use ValkeyModule_CallReplyPromiseAbort to abort the command invocation - if it was not yet finished (see ValkeyModule_CallReplyPromiseAbort documentation for more - details). It is also the module's responsibility to abort the execution on role change, either by using - server event (to get notified when the instance becomes a replica) or relying on the disconnect - callback of the original client. Failing to do so can result in a write operation on a replica. - Unlike other call replies, promise call reply **must** be freed while the GIL is locked. - Notice that on unblocking, the only promise is that the unblock handler will be called, - If the blocking ValkeyModule_Call caused the module to also block some real client (using ValkeyModule_BlockClient), - it is the module responsibility to unblock this client on the unblock handler. - On the unblock handler it is only allowed to perform the following: - * Calling additional commands using ValkeyModule_Call - * Open keys using ValkeyModule_OpenKey - * Replicate data to the replica or AOF - - Specifically, it is not allowed to call any module API which are client related such as: - * ValkeyModule_Reply* API's - * ValkeyModule_BlockClient - * ValkeyModule_GetCurrentUserName - - * 'X' -- Return exact reply types, including the differences between simple - string and bulk string, and the RESP 2 difference between nulls - and null arrays. - -* **...**: The actual arguments to the command. - -On success a `ValkeyModuleCallReply` object is returned; otherwise, -NULL is returned and errno is set to the following values: - -* EBADF: wrong format specifier. -* EINVAL: wrong command arity. -* ENOENT: command does not exist. -* EPERM: operation in Cluster instance with key in non local slot. -* EROFS: operation in Cluster instance when a write command is sent - in a readonly state. -* ENETDOWN: operation in Cluster instance when cluster is down. -* ENOTSUP: No ACL user for the specified module context -* EACCES: Command cannot be executed, according to ACL rules -* ENOSPC: Write or deny-oom command is not allowed -* ESPIPE: Command not allowed on script mode - -Example code fragment: - - reply = ValkeyModule_Call(ctx,"INCRBY","sc",argv[1],"10"); - if (ValkeyModule_CallReplyType(reply) == VALKEYMODULE_REPLY_INTEGER) { - long long myval = ValkeyModule_CallReplyInteger(reply); - // Do something with myval. - } - -This API is documented here: [https://valkey.io/topics/modules-intro](https://valkey.io/topics/modules-intro) - - - -### `ValkeyModule_CallArgv` - - int ValkeyModule_CallArgv(ValkeyModuleCtx *ctx, - ValkeyModuleString **argv, - int argc, - int flags, - const ValkeyModuleReplyHandlers *resp_handlers, - void *reply_ctx); - -**Available since:** 9.2.0 - -Low-level API to call any command from modules. - -This is an optimized version of [`ValkeyModule_Call`](#ValkeyModule_Call) when the module already has the -arguments prepared as an array of `ValkeyModuleString` pointers. Unlike -[`ValkeyModule_Call`](#ValkeyModule_Call), this function does not allocate a CallReply object. Instead, the -reply is delivered directly through the `resp_handlers` callbacks, enabling -zero-copy pass-through and avoiding intermediate parsing overhead. - -This API is synchronous. -The ownership of the `argv` array remains with the caller. The reply callbacks -run before this function returns; `reply_ctx` need only remain valid until then. - -If infrastructure (such as a forkless operation) prevents the command from -executing without blocking, sets errno = EAGAIN. With -`VALKEYMODULE_CALL_ARGV_ERRORS_AS_REPLIES`, delivers an error reply and returns -`VALKEYMODULE_OK`; otherwise returns `VALKEYMODULE_ERR` without reply callbacks. -The command has not executed and is not queued for later execution. -The caller may retry later, but must not busy-wait on the server thread. - -* **argv**: The array of arguments. -* **argc**: The length of the array of arguments. -* **flags**: A combination of `VALKEYMODULE_CALL_ARGV_`* flags. The supported flags are: - * `VALKEYMODULE_CALL_ARGV_REPLICATE`: Propagate the command to replicas and AOF - (format specifier: "!"). - * `VALKEYMODULE_CALL_ARGV_NO_AOF`: Do not propagate the command to the AOF - file (format specifier: "A"). - * `VALKEYMODULE_CALL_ARGV_NO_REPLICAS`: Do not propagate the command to - replicas (format specifier: "R"). - * `VALKEYMODULE_CALL_ARGV_RESP_3`: Request a RESP3 reply from the inner command - (format specifier: "3"). - * `VALKEYMODULE_CALL_ARGV_RESP_AUTO`: Use the same RESP version as the calling - client (format specifier: "0"). Recommended for pass-through use cases. - * `VALKEYMODULE_CALL_ARGV_RUN_AS_USER`: Run the command with the given user for - ACL checks (format specifier: "C"). - * `VALKEYMODULE_CALL_ARGV_SCRIPT_MODE`: Mark the call as coming from script - execution (format specifier: "S"). - * `VALKEYMODULE_CALL_ARGV_NO_WRITES`: Disallow write commands in this call - (format specifier: "W"). - * `VALKEYMODULE_CALL_ARGV_ERRORS_AS_REPLIES`: Deliver command and validation - errors through reply_handlers and return VALKEYMODULE_OK, while leaving - errno set for validation errors such as wrong command arity (EINVAL) - or infrastructure refusal (EAGAIN). - Malformed API calls (EBADF) still return VALKEYMODULE_ERR without callbacks; - these indicate module programming errors rather than command errors. - errno is set before reply dispatch and again before returning. Callbacks - that change errno must preserve it if subsequent callbacks need its value - (format specifier: "E"). - * `VALKEYMODULE_CALL_ARGV_RESPECT_DENY_OOM`: Respect deny-oom policy when - executing the command (format specifier: "M"). - * `VALKEYMODULE_CALL_ARGV_DRY_RUN`: Execute in dry-run mode; implies - `VALKEYMODULE_CALL_ARGV_ERRORS_AS_REPLIES`. A successful dry run does not - execute the command or invoke reply callbacks (format specifier: "D"). - * `VALKEYMODULE_CALL_ARGV_REPLY_EXACT`: Request exact reply parsing (do not - coerce reply types) (format specifier: "X"). -* **resp_handlers**: Struct of callbacks that receive the command reply. The - `onRespAvailable` callback is called first with the raw RESP bytes; if it - returns 0 the per-type callbacks are skipped. `onBlocked` is not used. - May be NULL to discard the reply. Otherwise, version must be between 1 - and VALKEYMODULE_REPLY_HANDLERS_VERSION, inclusive. - -Returns `VALKEYMODULE_OK` on success. Returns `VALKEYMODULE_ERR` if an error -occurred before invoking the command and errno is set to one of: -* EAGAIN: Infrastructure would block the command (delivered through `reply_handlers` - and returns VALKEYMODULE_OK when ERRORS_AS_REPLIES is set). -* EBADF: invalid call arguments, unsupported flags, or an unsupported reply - handlers version (returned regardless of ERRORS_AS_REPLIES, without - invoking reply callbacks or executing the command). -* EINVAL: wrong command arity (delivered through `reply_handlers` and returns - VALKEYMODULE_OK when ERRORS_AS_REPLIES is set). -* ENOENT: command does not exist. -* EPERM: operation in Cluster instance with key in non local slot. -* EROFS: operation in Cluster instance when a write command is sent - in a readonly state. -* ENETDOWN: operation in Cluster instance when cluster is down. -* ENOTSUP: No ACL user for the specified module context -* EACCES: Command cannot be executed, according to ACL rules -* ENOSPC: Write or deny-oom command is not allowed, e.g. when writes - are paused (CLIENT PAUSE, failover) -* ESPIPE: Command not allowed on script mode - - - -### `ValkeyModule_CallReplyProto` - - const char *ValkeyModule_CallReplyProto(ValkeyModuleCallReply *reply, - size_t *len); - -**Available since:** 4.0.0 - -Return a pointer, and a length, to the protocol returned by the command -that returned the reply object. - - - -## Modules data types - -When String DMA or using existing data structures is not enough, it is -possible to create new data types from scratch. -The module must provide a set of callbacks for handling the -new values exported (for example in order to provide RDB saving/loading, -AOF rewrite, and so forth). In this section we define this API. - - - -### `ValkeyModule_CreateDataType` - - moduleType *ValkeyModule_CreateDataType(ValkeyModuleCtx *ctx, - const char *name, - int encver, - void *typemethods_ptr); - -**Available since:** 4.0.0 - -Register a new data type exported by the module. The parameters are the -following. Please for in depth documentation check the modules API -documentation, especially [https://valkey.io/topics/modules-native-types](https://valkey.io/topics/modules-native-types). - -* **name**: A 9 characters data type name that MUST be unique in the - Modules ecosystem. Be creative... and there will be no collisions. Use - the charset A-Z a-z 9-0, plus the two "-_" characters. A good - idea is to use, for example `-`. For example - "tree-AntZ" may mean "Tree data structure by @antirez". To use both - lower case and upper case letters helps in order to prevent collisions. -* **encver**: Encoding version, which is, the version of the serialization - that a module used in order to persist data. As long as the "name" - matches, the RDB loading will be dispatched to the type callbacks - whatever 'encver' is used, however the module can understand if - the encoding it must load are of an older version of the module. - For example the module "tree-AntZ" initially used encver=0. Later - after an upgrade, it started to serialize data in a different format - and to register the type with encver=1. However this module may - still load old data produced by an older version if the `rdb_load` - callback is able to check the encver value and act accordingly. - The encver must be a positive value between 0 and 1023. - -* **typemethods_ptr** is a pointer to a `ValkeyModuleTypeMethods` structure - that should be populated with the methods callbacks and structure - version, like in the following example: - - ValkeyModuleTypeMethods tm = { - .version = VALKEYMODULE_TYPE_METHOD_VERSION, - .rdb_load = myType_RDBLoadCallBack, - .rdb_save = myType_RDBSaveCallBack, - .aof_rewrite = myType_AOFRewriteCallBack, - .free = myType_FreeCallBack, - - // Optional fields - .digest = myType_DigestCallBack, - .mem_usage = myType_MemUsageCallBack, - .aux_load = myType_AuxRDBLoadCallBack, - .aux_save = myType_AuxRDBSaveCallBack, - .free_effort = myType_FreeEffortCallBack, - .unlink = myType_UnlinkCallBack, - .copy = myType_CopyCallback, - .defrag = myType_DefragCallback - - // Enhanced optional fields - .mem_usage2 = myType_MemUsageCallBack2, - .free_effort2 = myType_FreeEffortCallBack2, - .unlink2 = myType_UnlinkCallBack2, - .copy2 = myType_CopyCallback2, - } - -* **rdb_load**: A callback function pointer that loads data from RDB files. -* **rdb_save**: A callback function pointer that saves data to RDB files. -* **aof_rewrite**: A callback function pointer that rewrites data as commands. -* **digest**: A callback function pointer that is used for `DEBUG DIGEST`. -* **free**: A callback function pointer that can free a type value. -* **aux_save**: A callback function pointer that saves out of keyspace data to RDB files. - 'when' argument is either `VALKEYMODULE_AUX_BEFORE_RDB` or `VALKEYMODULE_AUX_AFTER_RDB`. -* **aux_load**: A callback function pointer that loads out of keyspace data from RDB files. - Similar to `aux_save`, returns `VALKEYMODULE_OK` on success, and ERR otherwise. -* **free_effort**: A callback function pointer that used to determine whether the module's - memory needs to be lazy reclaimed. The module should return the complexity involved by - freeing the value. for example: how many pointers are gonna be freed. Note that if it - returns 0, we'll always do an async free. -* **unlink**: A callback function pointer that used to notifies the module that the key has - been removed from the DB by the server, and may soon be freed by a background thread. Note that - it won't be called on FLUSHALL/FLUSHDB (both sync and async), and the module can use the - `ValkeyModuleEvent_FlushDB` to hook into that. -* **copy**: A callback function pointer that is used to make a copy of the specified key. - The module is expected to perform a deep copy of the specified value and return it. - In addition, hints about the names of the source and destination keys is provided. - A NULL return value is considered an error and the copy operation fails. - Note: if the target key exists and is being overwritten, the copy callback will be - called first, followed by a free callback to the value that is being replaced. - -* **defrag**: A callback function pointer that is used to request the module to defrag - a key. The module should then iterate pointers and call the relevant `ValkeyModule_Defrag*()` - functions to defragment pointers or complex types. The module should continue - iterating as long as [`ValkeyModule_DefragShouldStop()`](#ValkeyModule_DefragShouldStop) returns a zero value, and return a - zero value if finished or non-zero value if more work is left to be done. If more work - needs to be done, [`ValkeyModule_DefragCursorSet()`](#ValkeyModule_DefragCursorSet) and [`ValkeyModule_DefragCursorGet()`](#ValkeyModule_DefragCursorGet) can be used to track - this work across different calls. - Normally, the defrag mechanism invokes the callback without a time limit, so - [`ValkeyModule_DefragShouldStop()`](#ValkeyModule_DefragShouldStop) always returns zero. The "late defrag" mechanism which has - a time limit and provides cursor support is used only for keys that are determined - to have significant internal complexity. To determine this, the defrag mechanism - uses the `free_effort` callback and the 'active-defrag-max-scan-fields' config directive. - NOTE: The value is passed as a `void**` and the function is expected to update the - pointer if the top-level value pointer is defragmented and consequently changes. - -* **mem_usage2**: Similar to `mem_usage`, but provides the `ValkeyModuleKeyOptCtx` parameter - so that meta information such as key name and db id can be obtained, and - the `sample_size` for size estimation (see MEMORY USAGE command). -* **free_effort2**: Similar to `free_effort`, but provides the `ValkeyModuleKeyOptCtx` parameter - so that meta information such as key name and db id can be obtained. -* **unlink2**: Similar to `unlink`, but provides the `ValkeyModuleKeyOptCtx` parameter - so that meta information such as key name and db id can be obtained. -* **copy2**: Similar to `copy`, but provides the `ValkeyModuleKeyOptCtx` parameter - so that meta information such as key names and db ids can be obtained. -* **aux_save2**: Similar to `aux_save`, but with small semantic change, if the module - saves nothing on this callback then no data about this aux field will be written to the - RDB and it will be possible to load the RDB even if the module is not loaded. - -Note: the module name "AAAAAAAAA" is reserved and produces an error, it -happens to be pretty lame as well. - -If [`ValkeyModule_CreateDataType()`](#ValkeyModule_CreateDataType) is called outside of `ValkeyModule_OnLoad()` function, -there is already a module registering a type with the same name, -or if the module name or encver is invalid, NULL is returned. -Otherwise, the new type is registered into the server, and a reference of -type `ValkeyModuleType` is returned: the caller of the function should store -this reference into a global variable to make future use of it in the -modules type API, since a single module may register multiple types. -Example code fragment: - - static ValkeyModuleType *BalancedTreeType; - - int ValkeyModule_OnLoad(ValkeyModuleCtx *ctx) { - // some code here ... - BalancedTreeType = ValkeyModule_CreateDataType(...); - } - - - -### `ValkeyModule_ModuleTypeSetValue` - - int ValkeyModule_ModuleTypeSetValue(ValkeyModuleKey *key, - moduleType *mt, - void *value); - -**Available since:** 4.0.0 - -If the key is open for writing, set the specified module type object -as the value of the key, deleting the old value if any. -On success `VALKEYMODULE_OK` is returned. If the key is not open for -writing or there is an active iterator, `VALKEYMODULE_ERR` is returned. - - - -### `ValkeyModule_ModuleTypeGetType` - - moduleType *ValkeyModule_ModuleTypeGetType(ValkeyModuleKey *key); - -**Available since:** 4.0.0 - -Assuming [`ValkeyModule_KeyType()`](#ValkeyModule_KeyType) returned `VALKEYMODULE_KEYTYPE_MODULE` on -the key, returns the module type pointer of the value stored at key. - -If the key is NULL, is not associated with a module type, or is empty, -then NULL is returned instead. - - - -### `ValkeyModule_ModuleTypeGetValue` - - void *ValkeyModule_ModuleTypeGetValue(ValkeyModuleKey *key); - -**Available since:** 4.0.0 - -Assuming [`ValkeyModule_KeyType()`](#ValkeyModule_KeyType) returned `VALKEYMODULE_KEYTYPE_MODULE` on -the key, returns the module type low-level value stored at key, as -it was set by the user via [`ValkeyModule_ModuleTypeSetValue()`](#ValkeyModule_ModuleTypeSetValue). - -If the key is NULL, is not associated with a module type, or is empty, -then NULL is returned instead. - - - -## RDB loading and saving functions - - - -### `ValkeyModule_IsIOError` - - int ValkeyModule_IsIOError(ValkeyModuleIO *io); - -**Available since:** 6.0.0 - -Returns true if any previous IO API failed. -for `Load*` APIs the `VALKEYMODULE_OPTIONS_HANDLE_IO_ERRORS` flag must be set with -[`ValkeyModule_SetModuleOptions`](#ValkeyModule_SetModuleOptions) first. - - - -### `ValkeyModule_SaveUnsigned` - - void ValkeyModule_SaveUnsigned(ValkeyModuleIO *io, uint64_t value); - -**Available since:** 4.0.0 - -Save an unsigned 64 bit value into the RDB file. This function should only -be called in the context of the `rdb_save` method of modules implementing new -data types. - - - -### `ValkeyModule_LoadUnsigned` - - uint64_t ValkeyModule_LoadUnsigned(ValkeyModuleIO *io); - -**Available since:** 4.0.0 - -Load an unsigned 64 bit value from the RDB file. This function should only -be called in the context of the `rdb_load` method of modules implementing -new data types. - - - -### `ValkeyModule_SaveSigned` - - void ValkeyModule_SaveSigned(ValkeyModuleIO *io, int64_t value); - -**Available since:** 4.0.0 - -Like [`ValkeyModule_SaveUnsigned()`](#ValkeyModule_SaveUnsigned) but for signed 64 bit values. - - - -### `ValkeyModule_LoadSigned` - - int64_t ValkeyModule_LoadSigned(ValkeyModuleIO *io); - -**Available since:** 4.0.0 - -Like [`ValkeyModule_LoadUnsigned()`](#ValkeyModule_LoadUnsigned) but for signed 64 bit values. - - - -### `ValkeyModule_SaveString` - - void ValkeyModule_SaveString(ValkeyModuleIO *io, ValkeyModuleString *s); - -**Available since:** 4.0.0 - -In the context of the `rdb_save` method of a module type, saves a -string into the RDB file taking as input a `ValkeyModuleString`. - -The string can be later loaded with [`ValkeyModule_LoadString()`](#ValkeyModule_LoadString) or -other Load family functions expecting a serialized string inside -the RDB file. - - - -### `ValkeyModule_SaveStringBuffer` - - void ValkeyModule_SaveStringBuffer(ValkeyModuleIO *io, - const char *str, - size_t len); - -**Available since:** 4.0.0 - -Like [`ValkeyModule_SaveString()`](#ValkeyModule_SaveString) but takes a raw C pointer and length -as input. - - - -### `ValkeyModule_LoadString` - - ValkeyModuleString *ValkeyModule_LoadString(ValkeyModuleIO *io); - -**Available since:** 4.0.0 - -In the context of the `rdb_load` method of a module data type, loads a string -from the RDB file, that was previously saved with [`ValkeyModule_SaveString()`](#ValkeyModule_SaveString) -functions family. - -The returned string is a newly allocated `ValkeyModuleString` object, and -the user should at some point free it with a call to [`ValkeyModule_FreeString()`](#ValkeyModule_FreeString). - -If the data structure does not store strings as `ValkeyModuleString` objects, -the similar function [`ValkeyModule_LoadStringBuffer()`](#ValkeyModule_LoadStringBuffer) could be used instead. - - - -### `ValkeyModule_LoadStringBuffer` - - char *ValkeyModule_LoadStringBuffer(ValkeyModuleIO *io, size_t *lenptr); - -**Available since:** 4.0.0 - -Like [`ValkeyModule_LoadString()`](#ValkeyModule_LoadString) but returns a heap allocated string that -was allocated with [`ValkeyModule_Alloc()`](#ValkeyModule_Alloc), and can be resized or freed with -[`ValkeyModule_Realloc()`](#ValkeyModule_Realloc) or [`ValkeyModule_Free()`](#ValkeyModule_Free). - -The size of the string is stored at '*lenptr' if not NULL. -The returned string is not automatically NULL terminated, it is loaded -exactly as it was stored inside the RDB file. - - - -### `ValkeyModule_SaveDouble` - - void ValkeyModule_SaveDouble(ValkeyModuleIO *io, double value); - -**Available since:** 4.0.0 - -In the context of the `rdb_save` method of a module data type, saves a double -value to the RDB file. The double can be a valid number, a NaN or infinity. -It is possible to load back the value with [`ValkeyModule_LoadDouble()`](#ValkeyModule_LoadDouble). - - - -### `ValkeyModule_LoadDouble` - - double ValkeyModule_LoadDouble(ValkeyModuleIO *io); - -**Available since:** 4.0.0 - -In the context of the `rdb_save` method of a module data type, loads back the -double value saved by [`ValkeyModule_SaveDouble()`](#ValkeyModule_SaveDouble). - - - -### `ValkeyModule_SaveFloat` - - void ValkeyModule_SaveFloat(ValkeyModuleIO *io, float value); - -**Available since:** 4.0.0 - -In the context of the `rdb_save` method of a module data type, saves a float -value to the RDB file. The float can be a valid number, a NaN or infinity. -It is possible to load back the value with [`ValkeyModule_LoadFloat()`](#ValkeyModule_LoadFloat). - - - -### `ValkeyModule_LoadFloat` - - float ValkeyModule_LoadFloat(ValkeyModuleIO *io); - -**Available since:** 4.0.0 - -In the context of the `rdb_save` method of a module data type, loads back the -float value saved by [`ValkeyModule_SaveFloat()`](#ValkeyModule_SaveFloat). - - - -### `ValkeyModule_SaveLongDouble` - - void ValkeyModule_SaveLongDouble(ValkeyModuleIO *io, long double value); - -**Available since:** 6.0.0 - -In the context of the `rdb_save` method of a module data type, saves a long double -value to the RDB file. The double can be a valid number, a NaN or infinity. -It is possible to load back the value with [`ValkeyModule_LoadLongDouble()`](#ValkeyModule_LoadLongDouble). - - - -### `ValkeyModule_LoadLongDouble` - - long double ValkeyModule_LoadLongDouble(ValkeyModuleIO *io); - -**Available since:** 6.0.0 - -In the context of the `rdb_save` method of a module data type, loads back the -long double value saved by [`ValkeyModule_SaveLongDouble()`](#ValkeyModule_SaveLongDouble). - - - -## Key digest API (DEBUG DIGEST interface for modules types) - - - -### `ValkeyModule_DigestAddStringBuffer` - - void ValkeyModule_DigestAddStringBuffer(ValkeyModuleDigest *md, - const char *ele, - size_t len); - -**Available since:** 4.0.0 - -Add a new element to the digest. This function can be called multiple times -one element after the other, for all the elements that constitute a given -data structure. The function call must be followed by the call to -[`ValkeyModule_DigestEndSequence`](#ValkeyModule_DigestEndSequence) eventually, when all the elements that are -always in a given order are added. See the Modules data types -documentation for more info. However this is a quick example that uses the -Set, Hash and List data types as an example. - -To add a sequence of unordered elements (for example in the case of a -Set), the pattern to use is: - - foreach element { - AddElement(element); - EndSequence(); - } - -Because Sets are not ordered, so every element added has a position that -does not depend from the other. However if instead our elements are -ordered in pairs, like field-value pairs of a Hash, then one should -use: - - foreach key,value { - AddElement(key); - AddElement(value); - EndSequence(); - } - -Because the key and value will be always in the above order, while instead -the single key-value pairs, can appear in any position into a hash. - -A list of ordered elements would be implemented with: - - foreach element { - AddElement(element); - } - EndSequence(); - - - -### `ValkeyModule_DigestAddLongLong` - - void ValkeyModule_DigestAddLongLong(ValkeyModuleDigest *md, long long ll); - -**Available since:** 4.0.0 - -Like [`ValkeyModule_DigestAddStringBuffer()`](#ValkeyModule_DigestAddStringBuffer) but takes a `long long` as input -that gets converted into a string before adding it to the digest. - - - -### `ValkeyModule_DigestEndSequence` - - void ValkeyModule_DigestEndSequence(ValkeyModuleDigest *md); - -**Available since:** 4.0.0 - -See the documentation for `ValkeyModule_DigestAddElement()`. - - - -### `ValkeyModule_LoadDataTypeFromStringEncver` - - void *ValkeyModule_LoadDataTypeFromStringEncver(const ValkeyModuleString *str, - const moduleType *mt, - int encver); - -**Available since:** 7.0.0 - -Decode a serialized representation of a module data type 'mt', in a specific encoding version 'encver' -from string 'str' and return a newly allocated value, or NULL if decoding failed. - -This call basically reuses the '`rdb_load`' callback which module data types -implement in order to allow a module to arbitrarily serialize/de-serialize -keys, similar to how the 'DUMP' and 'RESTORE' commands are implemented. - -Modules should generally use the `VALKEYMODULE_OPTIONS_HANDLE_IO_ERRORS` flag and -make sure the de-serialization code properly checks and handles IO errors -(freeing allocated buffers and returning a NULL). - -If this is NOT done, the server will handle corrupted (or just truncated) serialized -data by producing an error message and terminating the process. - - - -### `ValkeyModule_LoadDataTypeFromString` - - void *ValkeyModule_LoadDataTypeFromString(const ValkeyModuleString *str, - const moduleType *mt); - -**Available since:** 6.0.0 - -Similar to [`ValkeyModule_LoadDataTypeFromStringEncver`](#ValkeyModule_LoadDataTypeFromStringEncver), original version of the API, kept -for backward compatibility. - - - -### `ValkeyModule_SaveDataTypeToString` - - ValkeyModuleString *ValkeyModule_SaveDataTypeToString(ValkeyModuleCtx *ctx, - void *data, - const moduleType *mt); - -**Available since:** 6.0.0 - -Encode a module data type 'mt' value 'data' into serialized form, and return it -as a newly allocated `ValkeyModuleString`. - -This call basically reuses the '`rdb_save`' callback which module data types -implement in order to allow a module to arbitrarily serialize/de-serialize -keys, similar to how the 'DUMP' and 'RESTORE' commands are implemented. - - - -### `ValkeyModule_GetKeyNameFromDigest` - - const ValkeyModuleString *ValkeyModule_GetKeyNameFromDigest(ValkeyModuleDigest *dig); - -**Available since:** 7.0.0 - -Returns the name of the key currently being processed. - - - -### `ValkeyModule_GetDbIdFromDigest` - - int ValkeyModule_GetDbIdFromDigest(ValkeyModuleDigest *dig); - -**Available since:** 7.0.0 - -Returns the database id of the key currently being processed. - - - -## AOF API for modules data types - - - -### `ValkeyModule_EmitAOF` - - void ValkeyModule_EmitAOF(ValkeyModuleIO *io, - const char *cmdname, - const char *fmt, - ...); - -**Available since:** 4.0.0 - -Emits a command into the AOF during the AOF rewriting process. This function -is only called in the context of the `aof_rewrite` method of data types exported -by a module. The command works exactly like [`ValkeyModule_Call()`](#ValkeyModule_Call) in the way -the parameters are passed, but it does not return anything as the error -handling is performed by the server itself. - - - -## IO context handling - - - -### `ValkeyModule_GetKeyNameFromIO` - - const ValkeyModuleString *ValkeyModule_GetKeyNameFromIO(ValkeyModuleIO *io); - -**Available since:** 5.0.5 - -Returns the name of the key currently being processed. -There is no guarantee that the key name is always available, so this may return NULL. - - - -### `ValkeyModule_GetKeyNameFromModuleKey` - - const ValkeyModuleString *ValkeyModule_GetKeyNameFromModuleKey(ValkeyModuleKey *key); - -**Available since:** 6.0.0 - -Returns a `ValkeyModuleString` with the name of the key from `ValkeyModuleKey`. - - - -### `ValkeyModule_GetDbIdFromModuleKey` - - int ValkeyModule_GetDbIdFromModuleKey(ValkeyModuleKey *key); - -**Available since:** 7.0.0 - -Returns a database id of the key from `ValkeyModuleKey`. - - - -### `ValkeyModule_GetDbIdFromIO` - - int ValkeyModule_GetDbIdFromIO(ValkeyModuleIO *io); - -**Available since:** 7.0.0 - -Returns the database id of the key currently being processed. -There is no guarantee that this info is always available, so this may return -1. - - - -## Logging - - - -### `ValkeyModule_Log` - - void ValkeyModule_Log(ValkeyModuleCtx *ctx, - const char *levelstr, - const char *fmt, - ...); - -**Available since:** 4.0.0 - -Produces a log message to the standard server log, the format accepts -printf-alike specifiers, while level is a string describing the log -level to use when emitting the log, and must be one of the following: - -* "debug" (`VALKEYMODULE_LOGLEVEL_DEBUG`) -* "verbose" (`VALKEYMODULE_LOGLEVEL_VERBOSE`) -* "notice" (`VALKEYMODULE_LOGLEVEL_NOTICE`) -* "warning" (`VALKEYMODULE_LOGLEVEL_WARNING`) - -If the specified log level is invalid, verbose is used by default. -There is a fixed limit to the length of the log line this function is able -to emit, this limit is not specified but is guaranteed to be more than -a few lines of text. - -The ctx argument may be NULL if cannot be provided in the context of the -caller for instance threads or callbacks, in which case a generic "module" -will be used instead of the module name. - - - -### `ValkeyModule_LogIOError` - - void ValkeyModule_LogIOError(ValkeyModuleIO *io, - const char *levelstr, - const char *fmt, - ...); - -**Available since:** 4.0.0 - -Log errors from RDB / AOF serialization callbacks. - -This function should be used when a callback is returning a critical -error to the caller since cannot load or save the data for some -critical reason. - - - -### `ValkeyModule__Assert` - - void ValkeyModule__Assert(const char *estr, const char *file, int line); - -**Available since:** 6.0.0 - -Valkey assert function. - -The macro `ValkeyModule_Assert(expression)` is recommended, rather than -calling this function directly. - -A failed assertion will shut down the server and produce logging information -that looks identical to information generated by the server itself. - - - -### `ValkeyModule_LatencyAddSample` - - void ValkeyModule_LatencyAddSample(const char *event, mstime_t latency); - -**Available since:** 6.0.0 - -Allows adding event to the latency monitor to be observed by the LATENCY -command. The call is skipped if the latency is smaller than the configured -latency-monitor-threshold. - - - -## Blocking clients from modules - -For a guide about blocking commands in modules, see -[https://valkey.io/topics/modules-blocking-ops](https://valkey.io/topics/modules-blocking-ops). - - - -### `ValkeyModule_RegisterAuthCallback` - - void ValkeyModule_RegisterAuthCallback(ValkeyModuleCtx *ctx, - ValkeyModuleAuthCallback cb); - -**Available since:** 7.2.0 - -This API registers a callback to execute in addition to normal password based authentication. -Multiple callbacks can be registered across different modules. When a Module is unloaded, all the -auth callbacks registered by it are unregistered. -The callbacks are attempted (in the order of most recently registered first) when the AUTH/HELLO -(with AUTH field provided) commands are called. -The callbacks will be called with a module context along with a username and a password, and are -expected to take one of the following actions: -(1) Authenticate - Use the `ValkeyModule_AuthenticateClient`* API and return `VALKEYMODULE_AUTH_HANDLED`. -This will immediately end the auth chain as successful and add the OK reply. -(2) Deny Authentication - Return `VALKEYMODULE_AUTH_HANDLED` without authenticating or blocking the -client. Optionally, `err` can be set to a custom error message and `err` will be automatically -freed by the server. -This will immediately end the auth chain as unsuccessful and add the ERR reply. -(3) Block a client on authentication - Use the [`ValkeyModule_BlockClientOnAuth`](#ValkeyModule_BlockClientOnAuth) API and return -`VALKEYMODULE_AUTH_HANDLED`. Here, the client will be blocked until the [`ValkeyModule_UnblockClient`](#ValkeyModule_UnblockClient) API is used -which will trigger the auth reply callback (provided through the [`ValkeyModule_BlockClientOnAuth`](#ValkeyModule_BlockClientOnAuth)). -In this reply callback, the Module should authenticate, deny or skip handling authentication. -(4) Skip handling Authentication - Return `VALKEYMODULE_AUTH_NOT_HANDLED` without blocking the -client. This will allow the engine to attempt the next module auth callback. -If none of the callbacks authenticate or deny auth, then password based auth is attempted and -will authenticate or add failure logs and reply to the clients accordingly. - -Note: If a client is disconnected while it was in the middle of blocking module auth, that -occurrence of the AUTH or HELLO command will not be tracked in the INFO command stats. - -The following is an example of how non-blocking module based authentication can be used: - - int auth_cb(ValkeyModuleCtx *ctx, ValkeyModuleString *username, ValkeyModuleString *password, ValkeyModuleString **err) { - const char *user = ValkeyModule_StringPtrLen(username, NULL); - const char *pwd = ValkeyModule_StringPtrLen(password, NULL); - if (!strcmp(user,"foo") && !strcmp(pwd,"valid_password")) { - ValkeyModule_AuthenticateClientWithACLUser(ctx, "foo", 3, NULL, NULL, NULL); - return VALKEYMODULE_AUTH_HANDLED; - } - - else if (!strcmp(user,"foo") && !strcmp(pwd,"wrong_password")) { - ValkeyModuleString *log = ValkeyModule_CreateString(ctx, "Module Auth", 11); - ValkeyModule_ACLAddLogEntryByUserName(ctx, username, log, VALKEYMODULE_ACL_LOG_AUTH); - ValkeyModule_FreeString(ctx, log); - const char *err_msg = "Auth denied by Misc Module."; - *err = ValkeyModule_CreateString(ctx, err_msg, strlen(err_msg)); - return VALKEYMODULE_AUTH_HANDLED; - } - return VALKEYMODULE_AUTH_NOT_HANDLED; - } - - int ValkeyModule_OnLoad(ValkeyModuleCtx *ctx, ValkeyModuleString **argv, int argc) { - if (ValkeyModule_Init(ctx,"authmodule",1,VALKEYMODULE_APIVER_1)== VALKEYMODULE_ERR) - return VALKEYMODULE_ERR; - ValkeyModule_RegisterAuthCallback(ctx, auth_cb); - return VALKEYMODULE_OK; - } - - - -### `ValkeyModule_BlockClient` - - ValkeyModuleBlockedClient *ValkeyModule_BlockClient(ValkeyModuleCtx *ctx, - ValkeyModuleCmdFunc reply_callback, - ValkeyModuleCmdFunc timeout_callback, - void (*free_privdata)(ValkeyModuleCtx *, void *), - long long timeout_ms); - -**Available since:** 4.0.0 - -Block a client in the context of a blocking command, returning a handle -which will be used, later, in order to unblock the client with a call to -[`ValkeyModule_UnblockClient()`](#ValkeyModule_UnblockClient). The arguments specify callback functions -and a timeout after which the client is unblocked. - -The callbacks are called in the following contexts: - - reply_callback: called after a successful ValkeyModule_UnblockClient() - call in order to reply to the client and unblock it. - - timeout_callback: called when the timeout is reached or if `CLIENT UNBLOCK` - is invoked, in order to send an error to the client. - - free_privdata: called in order to free the private data that is passed - by ValkeyModule_UnblockClient() call. - -Notes: -1. [`ValkeyModule_UnblockClient`](#ValkeyModule_UnblockClient) should be called for every blocked client, -even if client was killed, timed-out or disconnected. Failing to do so -will result in memory leaks. -2. Attempting to block the client on keyspace event notification in versions - prior to 8.1.1 leads to a crash. - -There are some cases where [`ValkeyModule_BlockClient()`](#ValkeyModule_BlockClient) cannot be used: - -1. If the client is executing a script. -2. If the client is executing a MULTI block. -3. If the client is a temporary module client. -4. If the client is already blocked. - -In cases 1 and 2, a call to [`ValkeyModule_BlockClient()`](#ValkeyModule_BlockClient) will **not** block the -client, but instead produce a specific error reply. Note that if the -BlockClient call originated from within a keyspace notification, no error -reply is generated but nullptr is returned while the errno is set to EINVAL. - -In case 3 and 4, a call to [`ValkeyModule_BlockClient()`](#ValkeyModule_BlockClient) are no-op, returning -nullptr. errno is set to EINVAL for case 3 while ENOTSUP for case 4. - -A module that registers a `timeout_callback` function can also be unblocked -using the `CLIENT UNBLOCK` command, which will trigger the timeout callback. -If a callback function is not registered, then the blocked client will be -treated as if it is not in a blocked state and `CLIENT UNBLOCK` will return -a zero value. - -Measuring background time: By default the time spent in the blocked command -is not account for the total command duration. To include such time you should -use [`ValkeyModule_BlockedClientMeasureTimeStart()`](#ValkeyModule_BlockedClientMeasureTimeStart) and [`ValkeyModule_BlockedClientMeasureTimeEnd()`](#ValkeyModule_BlockedClientMeasureTimeEnd) one, -or multiple times within the blocking command background work. - - - -### `ValkeyModule_BlockClientOnAuth` - - ValkeyModuleBlockedClient *ValkeyModule_BlockClientOnAuth(ValkeyModuleCtx *ctx, - ValkeyModuleAuthCallback reply_callback, - void (*free_privdata)(ValkeyModuleCtx *, void *)); - -**Available since:** 7.2.0 - -Block the current client for module authentication in the background. If module auth is not in -progress on the client, the API returns NULL. Otherwise, the client is blocked and the `ValkeyModule_BlockedClient` -is returned similar to the [`ValkeyModule_BlockClient`](#ValkeyModule_BlockClient) API. -Note: Only use this API from the context of a module auth callback. - -There are some cases where [`ValkeyModule_BlockClientOnAuth()`](#ValkeyModule_BlockClientOnAuth) cannot be used: - -1. If the client is not in the middle of module based authentication. This will not block the client - but instead produce a specific error reply. - -For details on other return values and error codes, see the comment block for -[`ValkeyModule_BlockClient()`](#ValkeyModule_BlockClient). - - - -### `ValkeyModule_BlockClientGetPrivateData` - - void *ValkeyModule_BlockClientGetPrivateData(ValkeyModuleBlockedClient *blocked_client); - -**Available since:** 7.2.0 - -Get the private data that was previously set on a blocked client - - - -### `ValkeyModule_BlockClientSetPrivateData` - - void ValkeyModule_BlockClientSetPrivateData(ValkeyModuleBlockedClient *blocked_client, - void *private_data); - -**Available since:** 7.2.0 - -Set private data on a blocked client - - - -### `ValkeyModule_BlockClientOnKeys` - - ValkeyModuleBlockedClient *ValkeyModule_BlockClientOnKeys(ValkeyModuleCtx *ctx, - ValkeyModuleCmdFunc reply_callback, - ValkeyModuleCmdFunc timeout_callback, - void (*free_privdata)(ValkeyModuleCtx *, void *), - long long timeout_ms, - ValkeyModuleString **keys, - int numkeys, - void *privdata); - -**Available since:** 6.0.0 - -This call is similar to [`ValkeyModule_BlockClient()`](#ValkeyModule_BlockClient), however in this case we -don't just block the client, but also ask the server to unblock it automatically -once certain keys become "ready", that is, contain more data. - -Basically this is similar to what a typical command usually does, -like BLPOP or BZPOPMAX: the client blocks if it cannot be served ASAP, -and later when the key receives new data (a list push for instance), the -client is unblocked and served. - -However in the case of this module API, when the client is unblocked? - -1. If you block on a key of a type that has blocking operations associated, - like a list, a sorted set, a stream, and so forth, the client may be - unblocked once the relevant key is targeted by an operation that normally - unblocks the native blocking operations for that type. So if we block - on a list key, an RPUSH command may unblock our client and so forth. -2. If you are implementing your native data type, or if you want to add new - unblocking conditions in addition to "1", you can call the modules API - [`ValkeyModule_SignalKeyAsReady()`](#ValkeyModule_SignalKeyAsReady). - -Anyway we can't be sure if the client should be unblocked just because the -key is signaled as ready: for instance a successive operation may change the -key, or a client in queue before this one can be served, modifying the key -as well and making it empty again. So when a client is blocked with -[`ValkeyModule_BlockClientOnKeys()`](#ValkeyModule_BlockClientOnKeys) the reply callback is not called after -[`ValkeyModule_UnblockClient()`](#ValkeyModule_UnblockClient) is called, but every time a key is signaled as ready: -if the reply callback can serve the client, it returns `VALKEYMODULE_OK` -and the client is unblocked; otherwise, it will return `VALKEYMODULE_ERR` -and we'll try again later. - -The reply callback can access the key that was signaled as ready by -calling the API [`ValkeyModule_GetBlockedClientReadyKey()`](#ValkeyModule_GetBlockedClientReadyKey), that returns -just the string name of the key as a `ValkeyModuleString` object. - -Thanks to this system we can setup complex blocking scenarios, like -unblocking a client only if a list contains at least 5 items or other -more fancy logics. - -Note that another difference with [`ValkeyModule_BlockClient()`](#ValkeyModule_BlockClient), is that here -we pass the private data directly when blocking the client: it will -be accessible later in the reply callback. Normally when blocking with -[`ValkeyModule_BlockClient()`](#ValkeyModule_BlockClient) the private data to reply to the client is -passed when calling [`ValkeyModule_UnblockClient()`](#ValkeyModule_UnblockClient) but here the unblocking -is performed by the server itself, so we need to have some private data before -hand. The private data is used to store any information about the specific -unblocking operation that you are implementing. Such information will be -freed using the `free_privdata` callback provided by the user. - -However the reply callback will be able to access the argument vector of -the command, so the private data is often not needed. - -Note: Under normal circumstances [`ValkeyModule_UnblockClient`](#ValkeyModule_UnblockClient) should not be - called for clients that are blocked on keys (Either the key will - become ready or a timeout will occur). If for some reason you do want - to call ValkeyModule_UnblockClient it is possible: Client will be - handled as if it were timed-out (You must implement the timeout - callback in that case). - - - -### `ValkeyModule_BlockClientOnKeysWithFlags` - - ValkeyModuleBlockedClient *ValkeyModule_BlockClientOnKeysWithFlags(ValkeyModuleCtx *ctx, - ValkeyModuleCmdFunc reply_callback, - ValkeyModuleCmdFunc timeout_callback, - void (*free_privdata)(ValkeyModuleCtx *, void *), - long long timeout_ms, - ValkeyModuleString **keys, - int numkeys, - void *privdata, - int flags); - -**Available since:** 7.2.0 - -Same as [`ValkeyModule_BlockClientOnKeys`](#ValkeyModule_BlockClientOnKeys), but can take `VALKEYMODULE_BLOCK_`* flags -Can be either `VALKEYMODULE_BLOCK_UNBLOCK_DEFAULT`, which means default behavior (same -as calling [`ValkeyModule_BlockClientOnKeys`](#ValkeyModule_BlockClientOnKeys)) - -The flags is a bit mask of these: - -- `VALKEYMODULE_BLOCK_UNBLOCK_DELETED`: The clients should to be awakened in case any of `keys` are deleted. - Mostly useful for commands that require the key to exist (like XREADGROUP) - - - -### `ValkeyModule_SignalKeyAsReady` - - void ValkeyModule_SignalKeyAsReady(ValkeyModuleCtx *ctx, - ValkeyModuleString *key); - -**Available since:** 6.0.0 - -This function is used in order to potentially unblock a client blocked -on keys with [`ValkeyModule_BlockClientOnKeys()`](#ValkeyModule_BlockClientOnKeys). When this function is called, -all the clients blocked for this key will get their `reply_callback` called. - - - -### `ValkeyModule_UnblockClient` - - int ValkeyModule_UnblockClient(ValkeyModuleBlockedClient *bc, void *privdata); - -**Available since:** 4.0.0 - -Unblock a client blocked by `ValkeyModule_BlockedClient`. This will trigger -the reply callbacks to be called in order to reply to the client. -The 'privdata' argument will be accessible by the reply callback, so -the caller of this function can pass any value that is needed in order to -actually reply to the client. - -A common usage for 'privdata' is a thread that computes something that -needs to be passed to the client, included but not limited some slow -to compute reply or some reply obtained via networking. - -Returns `VALKEYMODULE_OK` on success. On failure, `VALKEYMODULE_ERR` is returned -and `errno` is set as follows: - -- EINVAL if bc is NULL. -- ENOTSUP if bc contains `blocked on keys` but its timeout callback is NULL. - -Note 1: this function can be called from threads spawned by the module. - -Note 2: when we unblock a client that is blocked for keys using the API -[`ValkeyModule_BlockClientOnKeys()`](#ValkeyModule_BlockClientOnKeys), the privdata argument here is not used. -Unblocking a client that was blocked for keys using this API will still -require the client to get some reply, so the function will use the -"timeout" handler in order to do so (The privdata provided in -[`ValkeyModule_BlockClientOnKeys()`](#ValkeyModule_BlockClientOnKeys) is accessible from the timeout -callback via [`ValkeyModule_GetBlockedClientPrivateData`](#ValkeyModule_GetBlockedClientPrivateData)). - - - -### `ValkeyModule_AbortBlock` - - int ValkeyModule_AbortBlock(ValkeyModuleBlockedClient *bc); - -**Available since:** 4.0.0 - -Abort a blocked client blocking operation: the client will be unblocked -without firing any callback. - - - -### `ValkeyModule_SetDisconnectCallback` - - void ValkeyModule_SetDisconnectCallback(ValkeyModuleBlockedClient *bc, - ValkeyModuleDisconnectFunc callback); - -**Available since:** 5.0.0 - -Set a callback that will be called if a blocked client disconnects -before the module has a chance to call [`ValkeyModule_UnblockClient()`](#ValkeyModule_UnblockClient) - -Usually what you want to do there, is to cleanup your module state -so that you can call [`ValkeyModule_UnblockClient()`](#ValkeyModule_UnblockClient) safely; otherwise, -the client will remain blocked forever if the timeout is large. - -Notes: - -1. It is not safe to call Reply* family functions here, it is also - useless since the client is gone. - -2. This callback is not called if the client disconnects because of - a timeout. In such a case, the client is unblocked automatically - and the timeout callback is called. - - - -### `ValkeyModule_IsBlockedReplyRequest` - - int ValkeyModule_IsBlockedReplyRequest(ValkeyModuleCtx *ctx); - -**Available since:** 4.0.0 - -Return non-zero if a module command was called in order to fill the -reply for a blocked client. - - - -### `ValkeyModule_IsBlockedTimeoutRequest` - - int ValkeyModule_IsBlockedTimeoutRequest(ValkeyModuleCtx *ctx); - -**Available since:** 4.0.0 - -Return non-zero if a module command was called in order to fill the -reply for a blocked client that timed out. - - - -### `ValkeyModule_GetBlockedClientPrivateData` - - void *ValkeyModule_GetBlockedClientPrivateData(ValkeyModuleCtx *ctx); - -**Available since:** 4.0.0 - -Get the private data set by [`ValkeyModule_UnblockClient()`](#ValkeyModule_UnblockClient) - - - -### `ValkeyModule_GetBlockedClientReadyKey` - - ValkeyModuleString *ValkeyModule_GetBlockedClientReadyKey(ValkeyModuleCtx *ctx); - -**Available since:** 6.0.0 - -Get the key that is ready when the reply callback is called in the context -of a client blocked by [`ValkeyModule_BlockClientOnKeys()`](#ValkeyModule_BlockClientOnKeys). - - - -### `ValkeyModule_GetBlockedClientHandle` - - ValkeyModuleBlockedClient *ValkeyModule_GetBlockedClientHandle(ValkeyModuleCtx *ctx); - -**Available since:** 5.0.0 - -Get the blocked client associated with a given context. -This is useful in the reply and timeout callbacks of blocked clients, -before sometimes the module has the blocked client handle references -around, and wants to cleanup it. - - - -### `ValkeyModule_BlockedClientDisconnected` - - int ValkeyModule_BlockedClientDisconnected(ValkeyModuleCtx *ctx); - -**Available since:** 5.0.0 - -Return true if when the free callback of a blocked client is called, -the reason for the client to be unblocked is that it disconnected -while it was blocked. - - - -## Thread Safe Contexts - - - -### `ValkeyModule_GetThreadSafeContext` - - ValkeyModuleCtx *ValkeyModule_GetThreadSafeContext(ValkeyModuleBlockedClient *bc); - -**Available since:** 4.0.0 - -Return a context which can be used inside threads to make calls requiring a -context with certain modules APIs. If 'bc' is not NULL then the module will -be bound to a blocked client, and it will be possible to use the -`ValkeyModule_Reply*` family of functions to accumulate a reply for when the -client will be unblocked. Otherwise, the thread safe context will be -detached by a specific client. - -To call non-reply APIs, the thread safe context must be prepared with: - - ValkeyModule_ThreadSafeContextLock(ctx); - ... make your call here ... - ValkeyModule_ThreadSafeContextUnlock(ctx); - -This is not needed when using `ValkeyModule_Reply*` functions, assuming -that a blocked client was used when the context was created; otherwise, -no `ValkeyModule_Reply`* call should be made at all. - -NOTE: If you're creating a detached thread safe context (bc is NULL), -consider using [`ValkeyModule_GetDetachedThreadSafeContext`](#ValkeyModule_GetDetachedThreadSafeContext) which will also retain -the module ID and thus be more useful for logging. - - - -### `ValkeyModule_GetDetachedThreadSafeContext` - - ValkeyModuleCtx *ValkeyModule_GetDetachedThreadSafeContext(ValkeyModuleCtx *ctx); - -**Available since:** 6.0.9 - -Return a detached thread safe context that is not associated with any -specific blocked client, but is associated with the module's context. - -This is useful for modules that wish to hold a global context over -a long term, for purposes such as logging. - - - -### `ValkeyModule_FreeThreadSafeContext` - - void ValkeyModule_FreeThreadSafeContext(ValkeyModuleCtx *ctx); - -**Available since:** 4.0.0 - -Release a thread safe context. - - - -### `ValkeyModule_ThreadSafeContextLock` - - void ValkeyModule_ThreadSafeContextLock(ValkeyModuleCtx *ctx); - -**Available since:** 4.0.0 - -Acquire the server lock before executing a thread safe API call. -This is not needed for `ValkeyModule_Reply*` calls when there is -a blocked client connected to the thread safe context. - - - -### `ValkeyModule_ThreadSafeContextTryLock` - - int ValkeyModule_ThreadSafeContextTryLock(ValkeyModuleCtx *ctx); - -**Available since:** 6.0.8 - -Similar to [`ValkeyModule_ThreadSafeContextLock`](#ValkeyModule_ThreadSafeContextLock) but this function -would not block if the server lock is already acquired. - -If successful (lock acquired) `VALKEYMODULE_OK` is returned, -otherwise `VALKEYMODULE_ERR` is returned and errno is set -accordingly. - - - -### `ValkeyModule_ThreadSafeContextUnlock` - - void ValkeyModule_ThreadSafeContextUnlock(ValkeyModuleCtx *ctx); - -**Available since:** 4.0.0 - -Release the server lock after a thread safe API call was executed. - - - -## Module Keyspace Notifications API - - - -### `ValkeyModule_SubscribeToKeyspaceEvents` - - int ValkeyModule_SubscribeToKeyspaceEvents(ValkeyModuleCtx *ctx, - int types, - ValkeyModuleNotificationFunc callback); - -**Available since:** 4.0.9 - -Subscribe to keyspace notifications. This is a low-level version of the -keyspace-notifications API. A module can register callbacks to be notified -when keyspace events occur. - -Notification events are filtered by their type (string events, set events, -etc), and the subscriber callback receives only events that match a specific -mask of event types. - -When subscribing to notifications with [`ValkeyModule_SubscribeToKeyspaceEvents`](#ValkeyModule_SubscribeToKeyspaceEvents) -the module must provide an event type-mask, denoting the events the subscriber -is interested in. This can be an ORed mask of any of the following flags: - - - `VALKEYMODULE_NOTIFY_GENERIC`: Generic commands like DEL, EXPIRE, RENAME - - `VALKEYMODULE_NOTIFY_STRING`: String events - - `VALKEYMODULE_NOTIFY_LIST`: List events - - `VALKEYMODULE_NOTIFY_SET`: Set events - - `VALKEYMODULE_NOTIFY_HASH`: Hash events - - `VALKEYMODULE_NOTIFY_ZSET`: Sorted Set events - - `VALKEYMODULE_NOTIFY_EXPIRED`: Expiration events - - `VALKEYMODULE_NOTIFY_EVICTED`: Eviction events - - `VALKEYMODULE_NOTIFY_STREAM`: Stream events - - `VALKEYMODULE_NOTIFY_MODULE`: Module types events - - `VALKEYMODULE_NOTIFY_PATH_HASH`: Path hash events - - `VALKEYMODULE_NOTIFY_NEW`: New key events - - `VALKEYMODULE_NOTIFY_KEY_MISS`: Key-miss events - Notice, key-miss event is the only type - of event that is fired from within a read command. - Performing ValkeyModule_Call with a write command from within - this notification is wrong and discourage. It will - cause the read command that trigger the event to be - replicated to the AOF/Replica. - - `VALKEYMODULE_NOTIFY_ALL`: All events (Excluding `VALKEYMODULE_NOTIFY_KEY_MISS` and `VALKEYMODULE_NOTIFY_NEW`) - - `VALKEYMODULE_NOTIFY_LOADED`: A special notification available only for modules, - indicates that the key was loaded from persistence. - Notice, when this event fires, the given key - cannot be retained, use ValkeyModule_CreateStringFromString - instead. - -We do not distinguish between key events and keyspace events, and it is up -to the module to filter the actions taken based on the key. - -The subscriber signature is: - - int (*ValkeyModuleNotificationFunc) (ValkeyModuleCtx *ctx, int type, - const char *event, - ValkeyModuleString *key); - -`type` is the event type bit, that must match the mask given at registration -time. The event string is the actual command being executed, and key is the -relevant key. - -Notification callback gets executed with a context that cannot be -used to send anything to the client, and has the db number where the event -occurred as its selected db number. - -Notice that it is not necessary to enable notifications in valkey.conf for -module notifications to work. - -Warning: the notification callbacks are performed in a synchronous manner, -so notification callbacks must to be fast, or they would slow the server down. -If you need to take long actions, use threads to offload them. - -Moreover, the fact that the notification is executed synchronously means -that the notification code will be executed in the middle of server logic -(commands logic, eviction, expire). Changing the key space while the logic -runs is dangerous and discouraged. In order to react to key space events with -write actions, please refer to [`ValkeyModule_AddPostNotificationJob`](#ValkeyModule_AddPostNotificationJob). - -See [https://valkey.io/topics/notifications](https://valkey.io/topics/notifications) for more information. - - - -### `ValkeyModule_AddPostNotificationJob` - - int ValkeyModule_AddPostNotificationJob(ValkeyModuleCtx *ctx, - ValkeyModulePostNotificationJobFunc callback, - void *privdata, - void (*free_privdata)(void *)); - -**Available since:** 7.2.0 - -When running inside a key space notification callback, it is dangerous and highly discouraged to perform any write -operation (See [`ValkeyModule_SubscribeToKeyspaceEvents`](#ValkeyModule_SubscribeToKeyspaceEvents)). In order to still perform write actions in this scenario, -the server provides [`ValkeyModule_AddPostNotificationJob`](#ValkeyModule_AddPostNotificationJob) API. The API allows to register a job callback which the server will -call when the following condition are promised to be fulfilled: -1. It is safe to perform any write operation. -2. The job will be called atomically along side the key space notification. - -Notice, one job might trigger key space notifications that will trigger more jobs. -This raises a concerns of entering an infinite loops, we consider infinite loops -as a logical bug that need to be fixed in the module, an attempt to protect against -infinite loops by halting the execution could result in violation of the feature correctness -and so the server will make no attempt to protect the module from infinite loops. - -'`free_pd`' can be NULL and in such case will not be used. - -Return `VALKEYMODULE_OK` on success and `VALKEYMODULE_ERR` if was called while loading data from disk (AOF or RDB) or -if the instance is a readonly replica. - - - -### `ValkeyModule_GetNotifyKeyspaceEvents` - - int ValkeyModule_GetNotifyKeyspaceEvents(void); - -**Available since:** 6.0.0 - -Get the configured bitmap of notify-keyspace-events (Could be used -for additional filtering in `ValkeyModuleNotificationFunc`) - - - -### `ValkeyModule_NotifyKeyspaceEvent` - - int ValkeyModule_NotifyKeyspaceEvent(ValkeyModuleCtx *ctx, - int type, - const char *event, - ValkeyModuleString *key); - -**Available since:** 6.0.0 - -Expose notifyKeyspaceEvent to modules - - - -## Modules Cluster API - - - -### `ValkeyModule_RegisterClusterMessageReceiver` - - void ValkeyModule_RegisterClusterMessageReceiver(ValkeyModuleCtx *ctx, - uint8_t type, - ValkeyModuleClusterMessageReceiver callback); - -**Available since:** 5.0.0 - -Register a callback receiver for cluster messages of type 'type'. If there -was already a registered callback, this will replace the callback function -with the one provided; otherwise, if the callback is set to NULL and there -is already a callback for this function, the callback is unregistered -(so this API call is also used in order to delete the receiver). - -When a message of this type is received, the registered callback function -will be invoked with details, including the 40-byte node ID of the sender. - -In Valkey 8.1 and later, the node ID is null-terminated. Prior to 8.1, it was -not null-terminated. - -Note: Old versions of Valkey could not handle type 255. This was fixed in -9.1.2, 9.0.6, 8.1.10, 8.0.11 and 7.2.15. - - - -### `ValkeyModule_SendClusterMessage` - - int ValkeyModule_SendClusterMessage(ValkeyModuleCtx *ctx, - const char *target_id, - uint8_t type, - const char *msg, - uint32_t len); - -**Available since:** 5.0.0 - -Send a message to all the nodes in the cluster if `target` is NULL; otherwise, -at the specified target, which is a `VALKEYMODULE_NODE_ID_LEN` bytes node ID, as -returned by the receiver callback or by the nodes iteration functions. - -In Valkey 8.1 and later, the cluster protocol overhead for this message is -~30B, to compare with earlier versions where it's ~2KB. - -The function returns `VALKEYMODULE_OK` if the message was successfully sent, -otherwise if the node is not connected or such node ID does not map to any -known cluster node, `VALKEYMODULE_ERR` is returned. - - - -### `ValkeyModule_GetClusterNodesList` - - char **ValkeyModule_GetClusterNodesList(ValkeyModuleCtx *ctx, size_t *numnodes); - -**Available since:** 5.0.0 - -Return an array of string pointers, each string pointer points to a cluster -node ID of exactly `VALKEYMODULE_NODE_ID_LEN` bytes (without any null term). -The number of returned node IDs is stored into `*numnodes`. -However if this function is called by a module not running an an -instance with Cluster enabled, NULL is returned instead. - -The IDs returned can be used with [`ValkeyModule_GetClusterNodeInfo()`](#ValkeyModule_GetClusterNodeInfo) in order -to get more information about single node. - -The array returned by this function must be freed using the function -[`ValkeyModule_FreeClusterNodesList()`](#ValkeyModule_FreeClusterNodesList). - -Example: - - size_t count, j; - char **ids = ValkeyModule_GetClusterNodesList(ctx,&count); - for (j = 0; j < count; j++) { - ValkeyModule_Log(ctx,"notice","Node %.*s", - VALKEYMODULE_NODE_ID_LEN,ids[j]); - } - ValkeyModule_FreeClusterNodesList(ids); - - - -### `ValkeyModule_FreeClusterNodesList` - - void ValkeyModule_FreeClusterNodesList(char **ids); - -**Available since:** 5.0.0 - -Free the node list obtained with [`ValkeyModule_GetClusterNodesList`](#ValkeyModule_GetClusterNodesList). - - - -### `ValkeyModule_GetMyClusterID` - - const char *ValkeyModule_GetMyClusterID(void); - -**Available since:** 5.0.0 - -Return this node ID (`VALKEYMODULE_CLUSTER_ID_LEN` bytes) or NULL if the cluster -is disabled. - - - -### `ValkeyModule_GetClusterSize` - - size_t ValkeyModule_GetClusterSize(void); - -**Available since:** 5.0.0 - -Return the number of nodes in the cluster, regardless of their state -(handshake, noaddress, ...) so that the number of active nodes may actually -be smaller, but not greater than this number. If the instance is not in -cluster mode, zero is returned. - - - -### `ValkeyModule_GetClusterNodeInfo` - - int ValkeyModule_GetClusterNodeInfo(ValkeyModuleCtx *ctx, - const char *id, - char *ip, - char *primary_id, - int *port, - int *flags); - -**Available since:** 5.0.0 - -Populate the specified info for the node having as ID the specified 'id', -then returns `VALKEYMODULE_OK`. Otherwise, if the format of node ID is invalid -or the node ID does not exist from the POV of this local node, `VALKEYMODULE_ERR` -is returned. - -The arguments `ip`, `primary_id`, `port` and `flags` can be NULL in case we don't -need to populate back certain info. If an `ip` and `primary_id` (only populated -if the instance is a replica) are specified, they point to buffers holding -at least `VALKEYMODULE_NODE_ID_LEN` bytes. The strings written back as `ip` -and `primary_id` are not null terminated. - -The list of flags reported is the following: - -* `VALKEYMODULE_NODE_MYSELF`: This node -* `VALKEYMODULE_NODE_PRIMARY`: The node is a primary -* `VALKEYMODULE_NODE_REPLICA`: The node is a replica -* `VALKEYMODULE_NODE_PFAIL`: We see the node as failing -* `VALKEYMODULE_NODE_FAIL`: The cluster agrees the node is failing -* `VALKEYMODULE_NODE_NOFAILOVER`: The replica is configured to never failover - - - -### `ValkeyModule_GetClusterNodeInfoForClient` - - int ValkeyModule_GetClusterNodeInfoForClient(ValkeyModuleCtx *ctx, - uint64_t client_id, - const char *node_id, - char *ip, - char *primary_id, - int *port, - int *flags); - -**Available since:** 8.0.0 - -Like [`ValkeyModule_GetClusterNodeInfo()`](#ValkeyModule_GetClusterNodeInfo), but returns IP address specifically for the given -client, depending on whether the client is connected over IPv4 or IPv6. - -See also [`ValkeyModule_GetClientId()`](#ValkeyModule_GetClientId). - - - -### `ValkeyModule_SetClusterFlags` - - void ValkeyModule_SetClusterFlags(ValkeyModuleCtx *ctx, uint64_t flags); - -**Available since:** 5.0.0 - -Set Cluster flags in order to change the normal behavior of -Cluster, especially with the goal of disabling certain functions. -This is useful for modules that use the Cluster API in order to create -a different distributed system, but still want to use the Cluster -message bus. Flags that can be set: - -* `CLUSTER_MODULE_FLAG_NO_FAILOVER` -* `CLUSTER_MODULE_FLAG_NO_REDIRECTION` - -With the following effects: - -* `NO_FAILOVER`: prevent Cluster replicas from failing over a dead primary. - Also disables the replica migration feature. - -* `NO_REDIRECTION`: Every node will accept any key, without trying to perform - partitioning according to the Cluster algorithm. - Slots information will still be propagated across the - cluster, but without effect. - - - -### `ValkeyModule_ClusterKeySlotC` - - unsigned int ValkeyModule_ClusterKeySlotC(const char *key, size_t keylen); - -**Available since:** 9.1.0 - -Returns the cluster slot of a key, similar to the `CLUSTER KEYSLOT` command. -This function works even if cluster mode is not enabled. - - - -### `ValkeyModule_ClusterKeySlot` - - unsigned int ValkeyModule_ClusterKeySlot(ValkeyModuleString *key); - -**Available since:** 8.0.0 - -Like [`ValkeyModule_ClusterKeySlotC()`](#ValkeyModule_ClusterKeySlotC) but gets the key as a `ValkeyModuleString`. - - - -### `ValkeyModule_ClusterCanonicalKeyNameInSlot` - - const char *ValkeyModule_ClusterCanonicalKeyNameInSlot(unsigned int slot); - -**Available since:** 8.0.0 - -Returns a short string that can be used as a key or as a hash tag in a key, -such that the key maps to the given cluster slot. Returns NULL if slot is not -a valid slot. - - - -## Modules Timers API - -Module timers are a high precision "green timers" abstraction where -every module can register even millions of timers without problems, even if -the actual event loop will just have a single timer that is used to awake the -module timers subsystem in order to process the next event. - -All the timers are stored into a radix tree, ordered by expire time, when -the main server event loop timer callback is called, we try to process all -the timers already expired one after the other. Then we re-enter the event -loop registering a timer that will expire when the next to process module -timer will expire. - -Every time the list of active timers drops to zero, we unregister the -main event loop timer, so that there is no overhead when such feature is -not used. - - - -### `ValkeyModule_CreateTimer` - - ValkeyModuleTimerID ValkeyModule_CreateTimer(ValkeyModuleCtx *ctx, - mstime_t period, - ValkeyModuleTimerProc callback, - void *data); - -**Available since:** 5.0.0 - -Create a new timer that will fire after `period` milliseconds, and will call -the specified function using `data` as argument. The returned timer ID can be -used to get information from the timer or to stop it before it fires. -Note that for the common use case of a repeating timer (Re-registration -of the timer inside the `ValkeyModuleTimerProc` callback) it matters when -this API is called: -If it is called at the beginning of 'callback' it means -the event will triggered every 'period'. -If it is called at the end of 'callback' it means -there will 'period' milliseconds gaps between events. -(If the time it takes to execute 'callback' is negligible the two -statements above mean the same) - - - -### `ValkeyModule_StopTimer` - - int ValkeyModule_StopTimer(ValkeyModuleCtx *ctx, - ValkeyModuleTimerID id, - void **data); - -**Available since:** 5.0.0 - -Stop a timer, returns `VALKEYMODULE_OK` if the timer was found, belonged to the -calling module, and was stopped; otherwise, `VALKEYMODULE_ERR` is returned. -If not NULL, the data pointer is set to the value of the data argument when -the timer was created. - - - -### `ValkeyModule_GetTimerInfo` - - int ValkeyModule_GetTimerInfo(ValkeyModuleCtx *ctx, - ValkeyModuleTimerID id, - uint64_t *remaining, - void **data); - -**Available since:** 5.0.0 - -Obtain information about a timer: its remaining time before firing -(in milliseconds), and the private data pointer associated with the timer. -If the timer specified does not exist or belongs to a different module -no information is returned and the function returns `VALKEYMODULE_ERR`; otherwise, -`VALKEYMODULE_OK` is returned. The arguments remaining or data can be NULL if -the caller does not need certain information. - - - -## Modules EventLoop API - - - -### `ValkeyModule_EventLoopAdd` - - int ValkeyModule_EventLoopAdd(int fd, - int mask, - ValkeyModuleEventLoopFunc func, - void *user_data); - -**Available since:** 7.0.0 - -Add a pipe / socket event to the event loop. - -* `mask` must be one of the following values: - - * `VALKEYMODULE_EVENTLOOP_READABLE` - * `VALKEYMODULE_EVENTLOOP_WRITABLE` - * `VALKEYMODULE_EVENTLOOP_READABLE | VALKEYMODULE_EVENTLOOP_WRITABLE` - -On success `VALKEYMODULE_OK` is returned; otherwise, -`VALKEYMODULE_ERR` is returned and errno is set to the following values: - -* ERANGE: `fd` is negative or higher than `maxclients` server config. -* EINVAL: `callback` is NULL or `mask` value is invalid. - -`errno` might take other values in case of an internal error. - -Example: - - void onReadable(int fd, void *user_data, int mask) { - char buf[32]; - int bytes = read(fd,buf,sizeof(buf)); - printf("Read %d bytes \n", bytes); - } - ValkeyModule_EventLoopAdd(fd, VALKEYMODULE_EVENTLOOP_READABLE, onReadable, NULL); - - - -### `ValkeyModule_EventLoopDel` - - int ValkeyModule_EventLoopDel(int fd, int mask); - -**Available since:** 7.0.0 - -Delete a pipe / socket event from the event loop. - -* `mask` must be one of the following values: - - * `VALKEYMODULE_EVENTLOOP_READABLE` - * `VALKEYMODULE_EVENTLOOP_WRITABLE` - * `VALKEYMODULE_EVENTLOOP_READABLE | VALKEYMODULE_EVENTLOOP_WRITABLE` - -On success `VALKEYMODULE_OK` is returned; otherwise, -`VALKEYMODULE_ERR` is returned and errno is set to the following values: - -* ERANGE: `fd` is negative or higher than `maxclients` server config. -* EINVAL: `mask` value is invalid. - - - -### `ValkeyModule_EventLoopAddOneShot` - - int ValkeyModule_EventLoopAddOneShot(ValkeyModuleEventLoopOneShotFunc func, - void *user_data); - -**Available since:** 7.0.0 - -This function can be called from other threads to trigger callback on the server -main thread. On success `VALKEYMODULE_OK` is returned. If `func` is NULL -`VALKEYMODULE_ERR` is returned and errno is set to EINVAL. - - - -## Modules ACL API - -Implements a hook into the authentication and authorization within the server. - - - -### `ValkeyModule_CreateModuleUser` - - ValkeyModuleUser *ValkeyModule_CreateModuleUser(const char *name); - -**Available since:** 6.0.0 - -Creates an ACL user that the module can use to authenticate a client. -After obtaining the user, the module should set what such user can do -using the `ValkeyModule_SetUserACL()` function. Once configured, the user -can be used in order to authenticate a connection, with the specified -ACL rules, using the `ValkeyModule_AuthClientWithUser()` function. - -Note that: - -* Users created here are not listed by the ACL command. -* Users created here are not checked for duplicated name, so it's up to - the module calling this function to take care of not creating users - with the same name. -* The created user can be used to authenticate multiple connections. - -The caller can later free the user using the function -[`ValkeyModule_FreeModuleUser()`](#ValkeyModule_FreeModuleUser). When this function is called, if there are -still clients authenticated with this user, they are disconnected. -The function to free the user should only be used when the caller really -wants to invalidate the user to define a new one with different -capabilities. - - - -### `ValkeyModule_FreeModuleUser` - - int ValkeyModule_FreeModuleUser(ValkeyModuleUser *user); - -**Available since:** 6.0.0 - -Frees a given user and disconnects all of the clients that have been -authenticated with it. See [`ValkeyModule_CreateModuleUser`](#ValkeyModule_CreateModuleUser) for detailed usage. - -Returns `VALKEYMODULE_OK`. - - - -### `ValkeyModule_SetModuleUserACL` - - int ValkeyModule_SetModuleUserACL(ValkeyModuleUser *user, const char *acl); - -**Available since:** 6.0.0 - -Sets the permissions of a user created through the module -interface. The syntax is the same as ACL SETUSER, so refer to the -documentation in acl.c for more information. See [`ValkeyModule_CreateModuleUser`](#ValkeyModule_CreateModuleUser) -for detailed usage. - -Returns `VALKEYMODULE_OK` on success and `VALKEYMODULE_ERR` on failure -and will set an errno describing why the operation failed. - - - -### `ValkeyModule_SetModuleUserACLString` - - int ValkeyModule_SetModuleUserACLString(ValkeyModuleCtx *ctx, - ValkeyModuleUser *user, - const char *acl, - ValkeyModuleString **error); - -**Available since:** 7.0.6 - -Sets the permission of a user with a complete ACL string, such as one -would use on the ACL SETUSER command line API. This differs from -[`ValkeyModule_SetModuleUserACL`](#ValkeyModule_SetModuleUserACL), which only takes single ACL operations at a time. - -Returns `VALKEYMODULE_OK` on success and `VALKEYMODULE_ERR` on failure -if a `ValkeyModuleString` is provided in error, a string describing the error -will be returned - - - -### `ValkeyModule_GetModuleUserACLString` - - ValkeyModuleString *ValkeyModule_GetModuleUserACLString(ValkeyModuleUser *user); - -**Available since:** 7.0.6 - -Get the ACL string for a given user -Returns a `ValkeyModuleString` - - - -### `ValkeyModule_GetCurrentUserName` - - ValkeyModuleString *ValkeyModule_GetCurrentUserName(ValkeyModuleCtx *ctx); - -**Available since:** 7.0.0 - -Retrieve the user name of the client connection behind the current context. -The user name can be used later, in order to get a `ValkeyModuleUser`. -See more information in [`ValkeyModule_GetModuleUserFromUserName`](#ValkeyModule_GetModuleUserFromUserName). - -The returned string must be released with [`ValkeyModule_FreeString()`](#ValkeyModule_FreeString) or by -enabling automatic memory management. - -If the context is not associated with a client connection, NULL is returned -and errno is set to EINVAL. - - - -### `ValkeyModule_GetModuleUserFromUserName` - - ValkeyModuleUser *ValkeyModule_GetModuleUserFromUserName(ValkeyModuleString *name); - -**Available since:** 7.0.0 - -A `ValkeyModuleUser` can be used to check if command, key or channel can be executed or -accessed according to the ACLs rules associated with that user. -When a Module wants to do ACL checks on a general ACL user (not created by [`ValkeyModule_CreateModuleUser`](#ValkeyModule_CreateModuleUser)), -it can get the `ValkeyModuleUser` from this API, based on the user name retrieved by [`ValkeyModule_GetCurrentUserName`](#ValkeyModule_GetCurrentUserName). - -Since a general ACL user can be deleted at any time, this `ValkeyModuleUser` should be used only in the context -where this function was called. In order to do ACL checks out of that context, the Module can store the user name, -and call this API at any other context. - -Returns NULL if the user is disabled or the user does not exist. -The caller should later free the user using the function [`ValkeyModule_FreeModuleUser()`](#ValkeyModule_FreeModuleUser). - - - -### `ValkeyModule_ACLCheckCommandPermissions` - - int ValkeyModule_ACLCheckCommandPermissions(ValkeyModuleUser *user, - ValkeyModuleString **argv, - int argc); - -**Available since:** 7.0.0 - -Checks if the command can be executed by the user, according to the ACLs associated with it. - -On success a `VALKEYMODULE_OK` is returned; otherwise, -`VALKEYMODULE_ERR` is returned and errno is set to the following values: - -* ENOENT: Specified command does not exist. -* EACCES: Command cannot be executed, according to ACL rules - -NOTE: Since 9.1, the underlying ACL check will NOT validate the user's access to the database. -For users WITHOUT the `alldbs` flag: `VALKEYMODULE_ERR` will be returned for any -READ or WRITE command, even if the user has permission to access the current database. - -For comprehensive ACL validation that handles all types of permissions for users, it is -recommended to use [`ValkeyModule_ACLCheckPermissions()`](#ValkeyModule_ACLCheckPermissions) instead, which accepts a dbid parameter -and properly validates access. - - - -### `ValkeyModule_ACLCheckKeyPermissions` - - int ValkeyModule_ACLCheckKeyPermissions(ValkeyModuleUser *user, - ValkeyModuleString *key, - int flags); - -**Available since:** 7.0.0 - -Check if the key can be accessed by the user according to the ACLs attached to the user -and the flags representing the key access. The flags are the same that are used in the -keyspec for logical operations. These flags are documented in [`ValkeyModule_SetCommandInfo`](#ValkeyModule_SetCommandInfo) as -the `VALKEYMODULE_CMD_KEY_ACCESS`, `VALKEYMODULE_CMD_KEY_UPDATE`, `VALKEYMODULE_CMD_KEY_INSERT`, -and `VALKEYMODULE_CMD_KEY_DELETE` flags. - -If no flags are supplied, the user is still required to have some access to the key for -this command to return successfully. - -If the user is able to access the key then `VALKEYMODULE_OK` is returned; otherwise, -`VALKEYMODULE_ERR` is returned and errno is set to one of the following values: - -* EINVAL: The provided flags are invalid. -* EACCESS: The user does not have permission to access the key. - - - -### `ValkeyModule_ACLCheckChannelPermissions` - - int ValkeyModule_ACLCheckChannelPermissions(ValkeyModuleUser *user, - ValkeyModuleString *ch, - int flags); - -**Available since:** 7.0.0 - -Check if the pubsub channel can be accessed by the user based off of the given -access flags. See [`ValkeyModule_ChannelAtPosWithFlags`](#ValkeyModule_ChannelAtPosWithFlags) for more information about the -possible flags that can be passed in. - -If the user is able to access the pubsub channel then `VALKEYMODULE_OK` is returned; otherwise, -`VALKEYMODULE_ERR` is returned and errno is set to one of the following values: - -* EINVAL: The provided flags are invalid. -* EACCESS: The user does not have permission to access the pubsub channel. - - - -### `ValkeyModule_ACLCheckPermissions` - - int ValkeyModule_ACLCheckPermissions(ValkeyModuleUser *user, - ValkeyModuleString **argv, - int argc, - int dbid, - ValkeyModuleACLLogEntryReason *denial_reason); - -**Available since:** 9.1.0 - -Check if the command with its arguments can be executed by the user, according to the -ACLs associated with it. This function performs a comprehensive ACL check including: -- Command permissions -- Key permissions -- Channel permissions -- Database permissions - -On success `VALKEYMODULE_OK` is returned, otherwise `VALKEYMODULE_ERR` is returned and -errno is set to one of the following values: -* EINVAL: Invalid arguments (e.g., negative dbid or dbid >= server.dbnum, command does not exist) -* EACCES: Permission denied (for any ACL violation) - -The optional `denial_reason` parameter can be used to get more specific information about -why the permission was denied. If provided (not NULL), it will be set to one of: -* `VALKEYMODULE_ACL_LOG_CMD`: User does not have permission to execute the command -* `VALKEYMODULE_ACL_LOG_KEY`: User does not have permission to access a key -* `VALKEYMODULE_ACL_LOG_CHANNEL`: User does not have permission to access a channel -* `VALKEYMODULE_ACL_LOG_DB`: User does not have permission to access the database - - - -### `ValkeyModule_ACLAddLogEntry` - - int ValkeyModule_ACLAddLogEntry(ValkeyModuleCtx *ctx, - ValkeyModuleUser *user, - ValkeyModuleString *object, - ValkeyModuleACLLogEntryReason reason); - -**Available since:** 7.0.0 - -Adds a new entry in the ACL log. -Returns `VALKEYMODULE_OK` on success and `VALKEYMODULE_ERR` on error. - -For more information about ACL log, please refer to [https://valkey.io/commands/acl-log](https://valkey.io/commands/acl-log) - - - -### `ValkeyModule_ACLAddLogEntryByUserName` - - int ValkeyModule_ACLAddLogEntryByUserName(ValkeyModuleCtx *ctx, - ValkeyModuleString *username, - ValkeyModuleString *object, - ValkeyModuleACLLogEntryReason reason); - -**Available since:** 7.2.0 - -Adds a new entry in the ACL log with the `username` `ValkeyModuleString` provided. -Returns `VALKEYMODULE_OK` on success and `VALKEYMODULE_ERR` on error. - -For more information about ACL log, please refer to [https://valkey.io/commands/acl-log](https://valkey.io/commands/acl-log) - - - -### `ValkeyModule_AuthenticateClientWithUser` - - int ValkeyModule_AuthenticateClientWithUser(ValkeyModuleCtx *ctx, - ValkeyModuleUser *module_user, - ValkeyModuleUserChangedFunc callback, - void *privdata, - uint64_t *client_id); - -**Available since:** 6.0.0 - -Authenticate the current context's user with the provided acl user. -Returns `VALKEYMODULE_ERR` if the user is disabled. - -See authenticateClientWithUser for information about callback, `client_id`, -and general usage for authentication. - - - -### `ValkeyModule_AuthenticateClientWithACLUser` - - int ValkeyModule_AuthenticateClientWithACLUser(ValkeyModuleCtx *ctx, - const char *name, - size_t len, - ValkeyModuleUserChangedFunc callback, - void *privdata, - uint64_t *client_id); - -**Available since:** 6.0.0 - -Authenticate the current context's user with the provided acl user. -Returns `VALKEYMODULE_ERR` if the user is disabled or the user does not exist. - -See authenticateClientWithUser for information about callback, `client_id`, -and general usage for authentication. - - - -### `ValkeyModule_DeauthenticateAndCloseClient` - - int ValkeyModule_DeauthenticateAndCloseClient(ValkeyModuleCtx *ctx, - uint64_t client_id); - -**Available since:** 6.0.0 - -Deauthenticate and close the client. The client resources will not be -immediately freed, but will be cleaned up in a background job. This is -the recommended way to deauthenticate a client since most clients can't -handle users becoming deauthenticated. Returns `VALKEYMODULE_ERR` when the -client doesn't exist and `VALKEYMODULE_OK` when the operation was successful. - -The client ID is returned from the [`ValkeyModule_AuthenticateClientWithUser`](#ValkeyModule_AuthenticateClientWithUser) and -[`ValkeyModule_AuthenticateClientWithACLUser`](#ValkeyModule_AuthenticateClientWithACLUser) APIs, but can be obtained through -the CLIENT api or through server events. - -This function is not thread safe, and must be executed within the context -of a command or thread safe context. - - - -### `ValkeyModule_RedactClientCommandArgument` - - int ValkeyModule_RedactClientCommandArgument(ValkeyModuleCtx *ctx, int pos); - -**Available since:** 7.0.0 - -Redact the client command argument specified at the given position. Redacted arguments -are obfuscated in user facing commands such as SLOWLOG or MONITOR, as well as -never being written to server logs. This command may be called multiple times on the -same position. - -Note that the command name, position 0, cannot be redacted. - -Returns `VALKEYMODULE_OK` if the argument was redacted and `VALKEYMODULE_ERR` if there -was an invalid parameter passed in or the position is outside the client -argument range. - - - -### `ValkeyModule_GetClientCertificate` - - ValkeyModuleString *ValkeyModule_GetClientCertificate(ValkeyModuleCtx *ctx, - uint64_t client_id); - -**Available since:** 6.0.9 - -Return the X.509 client-side certificate used by the client to authenticate -this connection. - -The return value is an allocated `ValkeyModuleString` that is a X.509 certificate -encoded in PEM (Base64) format. It should be freed (or auto-freed) by the caller. - -A NULL value is returned in the following conditions: - -- Connection ID does not exist -- Connection is not a TLS connection -- Connection is a TLS connection but no client certificate was used - - - -## Modules Dictionary API - -Implements a sorted dictionary (actually backed by a radix tree) with -the usual get / set / del / num-items API, together with an iterator -capable of going back and forth. - - - -### `ValkeyModule_CreateDict` - - ValkeyModuleDict *ValkeyModule_CreateDict(ValkeyModuleCtx *ctx); - -**Available since:** 5.0.0 - -Create a new dictionary. The 'ctx' pointer can be the current module context -or NULL, depending on what you want. Please follow the following rules: - -1. Use a NULL context if you plan to retain a reference to this dictionary - that will survive the time of the module callback where you created it. -2. Use a NULL context if no context is available at the time you are creating - the dictionary (of course...). -3. However use the current callback context as 'ctx' argument if the - dictionary time to live is just limited to the callback scope. In this - case, if enabled, you can enjoy the automatic memory management that will - reclaim the dictionary memory, as well as the strings returned by the - Next / Prev dictionary iterator calls. - - - -### `ValkeyModule_FreeDict` - - void ValkeyModule_FreeDict(ValkeyModuleCtx *ctx, ValkeyModuleDict *d); - -**Available since:** 5.0.0 - -Free a dictionary created with [`ValkeyModule_CreateDict()`](#ValkeyModule_CreateDict). You need to pass the -context pointer 'ctx' only if the dictionary was created using the -context instead of passing NULL. - - - -### `ValkeyModule_DictSize` - - uint64_t ValkeyModule_DictSize(ValkeyModuleDict *d); - -**Available since:** 5.0.0 - -Return the size of the dictionary (number of keys). - - - -### `ValkeyModule_DictSetC` - - int ValkeyModule_DictSetC(ValkeyModuleDict *d, - void *key, - size_t keylen, - void *ptr); - -**Available since:** 5.0.0 - -Store the specified key into the dictionary, setting its value to the -pointer 'ptr'. If the key was added with success, since it did not -already exist, `VALKEYMODULE_OK` is returned. Otherwise, if the key already -exists the function returns `VALKEYMODULE_ERR`. - - - -### `ValkeyModule_DictReplaceC` - - int ValkeyModule_DictReplaceC(ValkeyModuleDict *d, - void *key, - size_t keylen, - void *ptr); - -**Available since:** 5.0.0 - -Like [`ValkeyModule_DictSetC()`](#ValkeyModule_DictSetC) but will replace the key with the new -value if the key already exists. - - - -### `ValkeyModule_DictSet` - - int ValkeyModule_DictSet(ValkeyModuleDict *d, - ValkeyModuleString *key, - void *ptr); - -**Available since:** 5.0.0 - -Like [`ValkeyModule_DictSetC()`](#ValkeyModule_DictSetC) but takes the key as a `ValkeyModuleString`. - - - -### `ValkeyModule_DictReplace` - - int ValkeyModule_DictReplace(ValkeyModuleDict *d, - ValkeyModuleString *key, - void *ptr); - -**Available since:** 5.0.0 - -Like [`ValkeyModule_DictReplaceC()`](#ValkeyModule_DictReplaceC) but takes the key as a `ValkeyModuleString`. - - - -### `ValkeyModule_DictGetC` - - void *ValkeyModule_DictGetC(ValkeyModuleDict *d, - void *key, - size_t keylen, - int *nokey); - -**Available since:** 5.0.0 - -Return the value stored at the specified key. The function returns NULL -both in the case the key does not exist, or if you actually stored -NULL at key. So, optionally, if the 'nokey' pointer is not NULL, it will -be set by reference to 1 if the key does not exist, or to 0 if the key -exists. - - - -### `ValkeyModule_DictGet` - - void *ValkeyModule_DictGet(ValkeyModuleDict *d, - ValkeyModuleString *key, - int *nokey); - -**Available since:** 5.0.0 - -Like [`ValkeyModule_DictGetC()`](#ValkeyModule_DictGetC) but takes the key as a `ValkeyModuleString`. - - - -### `ValkeyModule_DictDelC` - - int ValkeyModule_DictDelC(ValkeyModuleDict *d, - void *key, - size_t keylen, - void *oldval); - -**Available since:** 5.0.0 - -Remove the specified key from the dictionary, returning `VALKEYMODULE_OK` if -the key was found and deleted, or `VALKEYMODULE_ERR` if instead there was -no such key in the dictionary. When the operation is successful, if -'oldval' is not NULL, then '*oldval' is set to the value stored at the -key before it was deleted. Using this feature it is possible to get -a pointer to the value (for instance in order to release it), without -having to call [`ValkeyModule_DictGet()`](#ValkeyModule_DictGet) before deleting the key. - - - -### `ValkeyModule_DictDel` - - int ValkeyModule_DictDel(ValkeyModuleDict *d, - ValkeyModuleString *key, - void *oldval); - -**Available since:** 5.0.0 - -Like [`ValkeyModule_DictDelC()`](#ValkeyModule_DictDelC) but gets the key as a `ValkeyModuleString`. - - - -### `ValkeyModule_DictIteratorStartC` - - ValkeyModuleDictIter *ValkeyModule_DictIteratorStartC(ValkeyModuleDict *d, - const char *op, - void *key, - size_t keylen); - -**Available since:** 5.0.0 - -Return an iterator, setup in order to start iterating from the specified -key by applying the operator 'op', which is just a string specifying the -comparison operator to use in order to seek the first element. The -operators available are: - -* `^` – Seek the first (lexicographically smaller) key. -* `$` – Seek the last (lexicographically bigger) key. -* `>` – Seek the first element greater than the specified key. -* `>=` – Seek the first element greater or equal than the specified key. -* `<` – Seek the first element smaller than the specified key. -* `<=` – Seek the first element smaller or equal than the specified key. -* `==` – Seek the first element matching exactly the specified key. - -Note that for `^` and `$` the passed key is not used, and the user may -just pass NULL with a length of 0. - -If the element to start the iteration cannot be seeked based on the -key and operator passed, [`ValkeyModule_DictNext()`](#ValkeyModule_DictNext) / Prev() will just return -`VALKEYMODULE_ERR` at the first call; otherwise, they'll produce elements. - - - -### `ValkeyModule_DictIteratorStart` - - ValkeyModuleDictIter *ValkeyModule_DictIteratorStart(ValkeyModuleDict *d, - const char *op, - ValkeyModuleString *key); - -**Available since:** 5.0.0 - -Exactly like [`ValkeyModule_DictIteratorStartC`](#ValkeyModule_DictIteratorStartC), but the key is passed as a -`ValkeyModuleString`. - - - -### `ValkeyModule_DictIteratorStop` - - void ValkeyModule_DictIteratorStop(ValkeyModuleDictIter *di); - -**Available since:** 5.0.0 - -Release the iterator created with [`ValkeyModule_DictIteratorStart()`](#ValkeyModule_DictIteratorStart). This call -is mandatory otherwise a memory leak is introduced in the module. - - - -### `ValkeyModule_DictIteratorReseekC` - - int ValkeyModule_DictIteratorReseekC(ValkeyModuleDictIter *di, - const char *op, - void *key, - size_t keylen); - -**Available since:** 5.0.0 - -After its creation with [`ValkeyModule_DictIteratorStart()`](#ValkeyModule_DictIteratorStart), it is possible to -change the currently selected element of the iterator by using this -API call. The result based on the operator and key is exactly like -the function [`ValkeyModule_DictIteratorStart()`](#ValkeyModule_DictIteratorStart), however in this case the -return value is just `VALKEYMODULE_OK` in case the seeked element was found, -or `VALKEYMODULE_ERR` in case it was not possible to seek the specified -element. It is possible to reseek an iterator as many times as you want. - - - -### `ValkeyModule_DictIteratorReseek` - - int ValkeyModule_DictIteratorReseek(ValkeyModuleDictIter *di, - const char *op, - ValkeyModuleString *key); - -**Available since:** 5.0.0 - -Like [`ValkeyModule_DictIteratorReseekC()`](#ValkeyModule_DictIteratorReseekC) but takes the key as a -`ValkeyModuleString`. - - - -### `ValkeyModule_DictNextC` - - void *ValkeyModule_DictNextC(ValkeyModuleDictIter *di, - size_t *keylen, - void **dataptr); - -**Available since:** 5.0.0 - -Return the current item of the dictionary iterator `di` and steps to the -next element. If the iterator already yield the last element and there -are no other elements to return, NULL is returned; otherwise, a pointer -to a string representing the key is provided, and the `*keylen` length -is set by reference (if keylen is not NULL). The `*dataptr`, if not NULL -is set to the value of the pointer stored at the returned key as auxiliary -data (as set by the [`ValkeyModule_DictSet`](#ValkeyModule_DictSet) API). - -Usage example: - - ... create the iterator here ... - char *key; - void *data; - while((key = ValkeyModule_DictNextC(iter,&keylen,&data)) != NULL) { - printf("%.*s %p\n", (int)keylen, key, data); - } - -The returned pointer is of type void because sometimes it makes sense -to cast it to a `char*` sometimes to an unsigned `char*` depending on the -fact it contains or not binary data, so this API ends being more -comfortable to use. - -The validity of the returned pointer is until the next call to the -next/prev iterator step. Also the pointer is no longer valid once the -iterator is released. - - - -### `ValkeyModule_DictPrevC` - - void *ValkeyModule_DictPrevC(ValkeyModuleDictIter *di, - size_t *keylen, - void **dataptr); - -**Available since:** 5.0.0 - -This function is exactly like [`ValkeyModule_DictNext()`](#ValkeyModule_DictNext) but after returning -the currently selected element in the iterator, it selects the previous -element (lexicographically smaller) instead of the next one. - - - -### `ValkeyModule_DictNext` - - ValkeyModuleString *ValkeyModule_DictNext(ValkeyModuleCtx *ctx, - ValkeyModuleDictIter *di, - void **dataptr); - -**Available since:** 5.0.0 - -Like `ValkeyModuleNextC()`, but instead of returning an internally allocated -buffer and key length, it returns directly a module string object allocated -in the specified context 'ctx' (that may be NULL exactly like for the main -API [`ValkeyModule_CreateString`](#ValkeyModule_CreateString)). - -The returned string object should be deallocated after use, either manually -or by using a context that has automatic memory management active. - - - -### `ValkeyModule_DictPrev` - - ValkeyModuleString *ValkeyModule_DictPrev(ValkeyModuleCtx *ctx, - ValkeyModuleDictIter *di, - void **dataptr); - -**Available since:** 5.0.0 - -Like [`ValkeyModule_DictNext()`](#ValkeyModule_DictNext) but after returning the currently selected -element in the iterator, it selects the previous element (lexicographically -smaller) instead of the next one. - - - -### `ValkeyModule_DictCompareC` - - int ValkeyModule_DictCompareC(ValkeyModuleDictIter *di, - const char *op, - void *key, - size_t keylen); - -**Available since:** 5.0.0 - -Compare the element currently pointed by the iterator to the specified -element given by key/keylen, according to the operator 'op' (the set of -valid operators are the same valid for [`ValkeyModule_DictIteratorStart`](#ValkeyModule_DictIteratorStart)). -If the comparison is successful the command returns `VALKEYMODULE_OK` -otherwise `VALKEYMODULE_ERR` is returned. - -This is useful when we want to just emit a lexicographical range, so -in the loop, as we iterate elements, we can also check if we are still -on range. - -The function return `VALKEYMODULE_ERR` if the iterator reached the -end of elements condition as well. - - - -### `ValkeyModule_DictCompare` - - int ValkeyModule_DictCompare(ValkeyModuleDictIter *di, - const char *op, - ValkeyModuleString *key); - -**Available since:** 5.0.0 - -Like [`ValkeyModule_DictCompareC`](#ValkeyModule_DictCompareC) but gets the key to compare with the current -iterator key as a `ValkeyModuleString`. - - - -## Modules Info fields - - - -### `ValkeyModule_InfoAddSection` - - int ValkeyModule_InfoAddSection(ValkeyModuleInfoCtx *ctx, const char *name); - -**Available since:** 6.0.0 - -Used to start a new section, before adding any fields. the section name will -be prefixed by `_` and must only include A-Z,a-z,0-9. -NULL or empty string indicates the default section (only ``) is used. -When return value is `VALKEYMODULE_ERR`, the section should and will be skipped. - - - -### `ValkeyModule_InfoBeginDictField` - - int ValkeyModule_InfoBeginDictField(ValkeyModuleInfoCtx *ctx, const char *name); - -**Available since:** 6.0.0 - -Starts a dict field, similar to the ones in INFO KEYSPACE. Use normal -`ValkeyModule_InfoAddField`* functions to add the items to this field, and -terminate with [`ValkeyModule_InfoEndDictField`](#ValkeyModule_InfoEndDictField). - - - -### `ValkeyModule_InfoEndDictField` - - int ValkeyModule_InfoEndDictField(ValkeyModuleInfoCtx *ctx); - -**Available since:** 6.0.0 - -Ends a dict field, see [`ValkeyModule_InfoBeginDictField`](#ValkeyModule_InfoBeginDictField) - - - -### `ValkeyModule_InfoAddFieldString` - - int ValkeyModule_InfoAddFieldString(ValkeyModuleInfoCtx *ctx, - const char *field, - ValkeyModuleString *value); - -**Available since:** 6.0.0 - -Used by `ValkeyModuleInfoFunc` to add info fields. -Each field will be automatically prefixed by `_`. -Field names or values must not include `\r\n` or `:`. - - - -### `ValkeyModule_InfoAddFieldCString` - - int ValkeyModule_InfoAddFieldCString(ValkeyModuleInfoCtx *ctx, - const char *field, - const char *value); - -**Available since:** 6.0.0 - -See [`ValkeyModule_InfoAddFieldString()`](#ValkeyModule_InfoAddFieldString). - - - -### `ValkeyModule_InfoAddFieldDouble` - - int ValkeyModule_InfoAddFieldDouble(ValkeyModuleInfoCtx *ctx, - const char *field, - double value); - -**Available since:** 6.0.0 - -See [`ValkeyModule_InfoAddFieldString()`](#ValkeyModule_InfoAddFieldString). - - - -### `ValkeyModule_InfoAddFieldLongLong` - - int ValkeyModule_InfoAddFieldLongLong(ValkeyModuleInfoCtx *ctx, - const char *field, - long long value); - -**Available since:** 6.0.0 - -See [`ValkeyModule_InfoAddFieldString()`](#ValkeyModule_InfoAddFieldString). - - - -### `ValkeyModule_InfoAddFieldULongLong` - - int ValkeyModule_InfoAddFieldULongLong(ValkeyModuleInfoCtx *ctx, - const char *field, - unsigned long long value); - -**Available since:** 6.0.0 - -See [`ValkeyModule_InfoAddFieldString()`](#ValkeyModule_InfoAddFieldString). - - - -### `ValkeyModule_RegisterInfoFunc` - - int ValkeyModule_RegisterInfoFunc(ValkeyModuleCtx *ctx, - ValkeyModuleInfoFunc cb); - -**Available since:** 6.0.0 - -Registers callback for the INFO command. The callback should add INFO fields -by calling the `ValkeyModule_InfoAddField*()` functions. - - - -### `ValkeyModule_GetServerInfo` - - ValkeyModuleServerInfoData *ValkeyModule_GetServerInfo(ValkeyModuleCtx *ctx, - const char *section); - -**Available since:** 6.0.0 - -Get information about the server similar to the one that returns from the -INFO command. This function takes an optional 'section' argument that may -be NULL. The return value holds the output and can be used with -[`ValkeyModule_ServerInfoGetField`](#ValkeyModule_ServerInfoGetField) and alike to get the individual fields. -When done, it needs to be freed with [`ValkeyModule_FreeServerInfo`](#ValkeyModule_FreeServerInfo) or with the -automatic memory management mechanism if enabled. - - - -### `ValkeyModule_FreeServerInfo` - - void ValkeyModule_FreeServerInfo(ValkeyModuleCtx *ctx, - ValkeyModuleServerInfoData *data); - -**Available since:** 6.0.0 - -Free data created with [`ValkeyModule_GetServerInfo()`](#ValkeyModule_GetServerInfo). You need to pass the -context pointer 'ctx' only if the dictionary was created using the -context instead of passing NULL. - - - -### `ValkeyModule_ServerInfoGetField` - - ValkeyModuleString *ValkeyModule_ServerInfoGetField(ValkeyModuleCtx *ctx, - ValkeyModuleServerInfoData *data, - const char *field); - -**Available since:** 6.0.0 - -Get the value of a field from data collected with [`ValkeyModule_GetServerInfo()`](#ValkeyModule_GetServerInfo). You -need to pass the context pointer 'ctx' only if you want to use auto memory -mechanism to release the returned string. Return value will be NULL if the -field was not found. - - - -### `ValkeyModule_ServerInfoGetFieldC` - - const char *ValkeyModule_ServerInfoGetFieldC(ValkeyModuleServerInfoData *data, - const char *field); - -**Available since:** 6.0.0 - -Similar to [`ValkeyModule_ServerInfoGetField`](#ValkeyModule_ServerInfoGetField), but returns a char* which should not be freed but the caller. - - - -### `ValkeyModule_ServerInfoGetFieldSigned` - - long long ValkeyModule_ServerInfoGetFieldSigned(ValkeyModuleServerInfoData *data, - const char *field, - int *out_err); - -**Available since:** 6.0.0 - -Get the value of a field from data collected with [`ValkeyModule_GetServerInfo()`](#ValkeyModule_GetServerInfo). If the -field is not found, or is not numerical or out of range, return value will be -0, and the optional `out_err` argument will be set to `VALKEYMODULE_ERR`. - - - -### `ValkeyModule_ServerInfoGetFieldUnsigned` - - unsigned long long ValkeyModule_ServerInfoGetFieldUnsigned(ValkeyModuleServerInfoData *data, - const char *field, - int *out_err); - -**Available since:** 6.0.0 - -Get the value of a field from data collected with [`ValkeyModule_GetServerInfo()`](#ValkeyModule_GetServerInfo). If the -field is not found, or is not numerical or out of range, return value will be -0, and the optional `out_err` argument will be set to `VALKEYMODULE_ERR`. - - - -### `ValkeyModule_ServerInfoGetFieldDouble` - - double ValkeyModule_ServerInfoGetFieldDouble(ValkeyModuleServerInfoData *data, - const char *field, - int *out_err); - -**Available since:** 6.0.0 - -Get the value of a field from data collected with [`ValkeyModule_GetServerInfo()`](#ValkeyModule_GetServerInfo). If the -field is not found, or is not a double, return value will be 0, and the -optional `out_err` argument will be set to `VALKEYMODULE_ERR`. - - - -## Modules utility APIs - - - -### `ValkeyModule_GetRandomBytes` - - void ValkeyModule_GetRandomBytes(unsigned char *dst, size_t len); - -**Available since:** 5.0.0 - -Return random bytes using SHA1 in counter mode with a /dev/urandom -initialized seed. This function is fast so can be used to generate -many bytes without any effect on the operating system entropy pool. -Currently this function is not thread safe. - - - -### `ValkeyModule_GetRandomHexChars` - - void ValkeyModule_GetRandomHexChars(char *dst, size_t len); - -**Available since:** 5.0.0 - -Like [`ValkeyModule_GetRandomBytes()`](#ValkeyModule_GetRandomBytes) but instead of setting the string to -random bytes the string is set to random characters in the in the -hex charset [0-9a-f]. - - - -## Modules API exporting / importing - - - -### `ValkeyModule_ExportSharedAPI` - - int ValkeyModule_ExportSharedAPI(ValkeyModuleCtx *ctx, - const char *apiname, - void *func); - -**Available since:** 5.0.4 - -This function is called by a module in order to export some API with a -given name. Other modules will be able to use this API by calling the -symmetrical function [`ValkeyModule_GetSharedAPI()`](#ValkeyModule_GetSharedAPI) and casting the return value to -the right function pointer. - -The function will return `VALKEYMODULE_OK` if the name is not already taken, -otherwise `VALKEYMODULE_ERR` will be returned and no operation will be -performed. - -IMPORTANT: the apiname argument should be a string literal with static -lifetime. The API relies on the fact that it will always be valid in -the future. - - - -### `ValkeyModule_GetSharedAPI` - - void *ValkeyModule_GetSharedAPI(ValkeyModuleCtx *ctx, const char *apiname); - -**Available since:** 5.0.4 - -Request an exported API pointer. The return value is just a void pointer -that the caller of this function will be required to cast to the right -function pointer, so this is a private contract between modules. - -If the requested API is not available then NULL is returned. Because -modules can be loaded at different times with different order, this -function calls should be put inside some module generic API registering -step, that is called every time a module attempts to execute a -command that requires external APIs: if some API cannot be resolved, the -command should return an error. - -Here is an example: - - int ... myCommandImplementation(void) { - if (getExternalAPIs() == 0) { - reply with an error here if we cannot have the APIs - } - // Use the API: - myFunctionPointer(foo); - } - -And the function registerAPI() is: - - int getExternalAPIs(void) { - static int api_loaded = 0; - if (api_loaded != 0) return 1; // APIs already resolved. - - myFunctionPointer = ValkeyModule_GetSharedAPI("..."); - if (myFunctionPointer == NULL) return 0; - - return 1; - } - - - -## Module Command Filter API - - - -### `ValkeyModule_RegisterCommandFilter` - - ValkeyModuleCommandFilter *ValkeyModule_RegisterCommandFilter(ValkeyModuleCtx *ctx, - ValkeyModuleCommandFilterFunc callback, - int flags); - -**Available since:** 5.0.5 - -Register a new command filter function. - -Command filtering makes it possible for modules to extend the server by plugging -into the execution flow of all commands. - -A registered filter gets called before the server executes *any* command. This -includes both core server commands and commands registered by any module. The -filter applies in all execution paths including: - -1. Invocation by a client. -2. Invocation through [`ValkeyModule_Call()`](#ValkeyModule_Call) by any module. -3. Invocation through Lua `server.call()`. -4. Replication of a command from a primary. - -The filter executes in a special filter context, which is different and more -limited than a `ValkeyModuleCtx`. Because the filter affects any command, it -must be implemented in a very efficient way to reduce the performance impact -on the server. All Module API calls that require a valid context (such as -[`ValkeyModule_Call()`](#ValkeyModule_Call), [`ValkeyModule_OpenKey()`](#ValkeyModule_OpenKey), etc.) are not supported in a -filter context. - -The `ValkeyModuleCommandFilterCtx` can be used to inspect or modify the -executed command and its arguments. As the filter executes before the server -begins processing the command, any change will affect the way the command is -processed. For example, a module can override server commands this way: - -1. Register a `MODULE.SET` command which implements an extended version of - the `SET` command. -2. Register a command filter which detects invocation of `SET` on a specific - pattern of keys. Once detected, the filter will replace the first - argument from `SET` to `MODULE.SET`. -3. When filter execution is complete, the server considers the new command name - and therefore executes the module's own command. - -Note that in the above use case, if `MODULE.SET` itself uses -[`ValkeyModule_Call()`](#ValkeyModule_Call) the filter will be applied on that call as well. If -that is not desired, the `VALKEYMODULE_CMDFILTER_NOSELF` flag can be set when -registering the filter. - -The `VALKEYMODULE_CMDFILTER_NOSELF` flag prevents execution flows that -originate from the module's own [`ValkeyModule_Call()`](#ValkeyModule_Call) from reaching the filter. This -flag is effective for all execution flows, including nested ones, as long as -the execution begins from the module's command context or a thread-safe -context that is associated with a blocking command. - -Detached thread-safe contexts are *not* associated with the module and cannot -be protected by this flag. - -If multiple filters are registered (by the same or different modules), they -are executed in the order of registration. - - - -### `ValkeyModule_UnregisterCommandFilter` - - int ValkeyModule_UnregisterCommandFilter(ValkeyModuleCtx *ctx, - ValkeyModuleCommandFilter *filter); - -**Available since:** 5.0.5 - -Unregister a command filter. - - - -### `ValkeyModule_CommandFilterArgsCount` - - int ValkeyModule_CommandFilterArgsCount(ValkeyModuleCommandFilterCtx *fctx); - -**Available since:** 5.0.5 - -Return the number of arguments a filtered command has. The number of -arguments include the command itself. - - - -### `ValkeyModule_CommandFilterArgGet` - - ValkeyModuleString *ValkeyModule_CommandFilterArgGet(ValkeyModuleCommandFilterCtx *fctx, - int pos); - -**Available since:** 5.0.5 - -Return the specified command argument. The first argument (position 0) is -the command itself, and the rest are user-provided args. - - - -### `ValkeyModule_CommandFilterArgInsert` - - int ValkeyModule_CommandFilterArgInsert(ValkeyModuleCommandFilterCtx *fctx, - int pos, - ValkeyModuleString *arg); - -**Available since:** 5.0.5 - -Modify the filtered command by inserting a new argument at the specified -position. The specified `ValkeyModuleString` argument may be used by the server -after the filter context is destroyed, so it must not be auto-memory -allocated, freed or used elsewhere. - - - -### `ValkeyModule_CommandFilterArgReplace` - - int ValkeyModule_CommandFilterArgReplace(ValkeyModuleCommandFilterCtx *fctx, - int pos, - ValkeyModuleString *arg); - -**Available since:** 5.0.5 - -Modify the filtered command by replacing an existing argument with a new one. -The specified `ValkeyModuleString` argument may be used by the server after the -filter context is destroyed, so it must not be auto-memory allocated, freed -or used elsewhere. - - - -### `ValkeyModule_CommandFilterArgDelete` - - int ValkeyModule_CommandFilterArgDelete(ValkeyModuleCommandFilterCtx *fctx, - int pos); - -**Available since:** 5.0.5 - -Modify the filtered command by deleting an argument at the specified -position. - - - -### `ValkeyModule_CommandFilterGetClientId` - - unsigned long long ValkeyModule_CommandFilterGetClientId(ValkeyModuleCommandFilterCtx *fctx); - -**Available since:** 7.2.0 - -Get Client ID for client that issued the command we are filtering - - - -## Module Command Result Event - - - -### `ValkeyModule_MallocSize` - - size_t ValkeyModule_MallocSize(void *ptr); - -**Available since:** 6.0.0 - -For a given pointer allocated via [`ValkeyModule_Alloc()`](#ValkeyModule_Alloc) or -[`ValkeyModule_Realloc()`](#ValkeyModule_Realloc), return the amount of memory allocated for it. -Note that this may be different (larger) than the memory we allocated -with the allocation calls, since sometimes the underlying allocator -will allocate more memory. - - - -### `ValkeyModule_MallocUsableSize` - - size_t ValkeyModule_MallocUsableSize(void *ptr); - -**Available since:** 7.0.1 - -Similar to [`ValkeyModule_MallocSize`](#ValkeyModule_MallocSize), the difference is that [`ValkeyModule_MallocUsableSize`](#ValkeyModule_MallocUsableSize) -returns the usable size of memory by the module. - - - -### `ValkeyModule_MallocSizeString` - - size_t ValkeyModule_MallocSizeString(ValkeyModuleString *str); - -**Available since:** 7.0.0 - -Same as [`ValkeyModule_MallocSize`](#ValkeyModule_MallocSize), except it works on `ValkeyModuleString` pointers. - - - -### `ValkeyModule_MallocSizeDict` - - size_t ValkeyModule_MallocSizeDict(ValkeyModuleDict *dict); - -**Available since:** 7.0.0 - -Same as [`ValkeyModule_MallocSize`](#ValkeyModule_MallocSize), except it works on `ValkeyModuleDict` pointers. -Note that the returned value is only the overhead of the underlying structures, -it does not include the allocation size of the keys and values. - - - -### `ValkeyModule_GetUsedMemoryRatio` - - float ValkeyModule_GetUsedMemoryRatio(void); - -**Available since:** 6.0.0 - -Return a number between 0 to 1 indicating the amount of memory -currently used, relative to the server "maxmemory" configuration. - -* 0 - No memory limit configured. -* Between 0 and 1 - The percentage of the memory used normalized in 0-1 range. -* Exactly 1 - Memory limit reached. -* Greater 1 - More memory used than the configured limit. - - - -## Scanning keyspace and hashes - - - -### `ValkeyModule_ScanCursorCreate` - - ValkeyModuleScanCursor *ValkeyModule_ScanCursorCreate(void); - -**Available since:** 6.0.0 - -Create a new cursor to be used with [`ValkeyModule_Scan`](#ValkeyModule_Scan) - - - -### `ValkeyModule_ScanCursorRestart` - - void ValkeyModule_ScanCursorRestart(ValkeyModuleScanCursor *cursor); - -**Available since:** 6.0.0 - -Restart an existing cursor. The keys will be rescanned. - - - -### `ValkeyModule_ScanCursorDestroy` - - void ValkeyModule_ScanCursorDestroy(ValkeyModuleScanCursor *cursor); - -**Available since:** 6.0.0 - -Destroy the cursor struct. - - - -### `ValkeyModule_Scan` - - int ValkeyModule_Scan(ValkeyModuleCtx *ctx, - ValkeyModuleScanCursor *cursor, - ValkeyModuleScanCB fn, - void *privdata); - -**Available since:** 6.0.0 - -Scan API that allows a module to scan all the keys and value in -the selected db. - -Callback for scan implementation. - - void scan_callback(ValkeyModuleCtx *ctx, ValkeyModuleString *keyname, - ValkeyModuleKey *key, void *privdata); - -- `ctx`: the module context provided for the scan. -- `keyname`: owned by the caller and need to be retained if used after this - function. -- `key`: holds info on the key and value, it is provided as best effort, in - some cases it might be NULL, in which case the user should (can) use - [`ValkeyModule_OpenKey()`](#ValkeyModule_OpenKey) (and CloseKey too). - when it is provided, it is owned by the caller and will be free when the - callback returns. -- `privdata`: the user data provided to [`ValkeyModule_Scan()`](#ValkeyModule_Scan). - -The way it should be used: - - ValkeyModuleScanCursor *c = ValkeyModule_ScanCursorCreate(); - while(ValkeyModule_Scan(ctx, c, callback, privateData)); - ValkeyModule_ScanCursorDestroy(c); - -It is also possible to use this API from another thread while the lock -is acquired during the actual call to [`ValkeyModule_Scan`](#ValkeyModule_Scan): - - ValkeyModuleScanCursor *c = ValkeyModule_ScanCursorCreate(); - ValkeyModule_ThreadSafeContextLock(ctx); - while(ValkeyModule_Scan(ctx, c, callback, privateData)){ - ValkeyModule_ThreadSafeContextUnlock(ctx); - // do some background job - ValkeyModule_ThreadSafeContextLock(ctx); - } - ValkeyModule_ScanCursorDestroy(c); - -The function will return 1 if there are more elements to scan and -0 otherwise, possibly setting errno if the call failed. - -It is also possible to restart an existing cursor using [`ValkeyModule_ScanCursorRestart`](#ValkeyModule_ScanCursorRestart). - -IMPORTANT: This API is very similar to the SCAN command from the -point of view of the guarantees it provides. This means that the API -may report duplicated keys, but guarantees to report at least one time -every key that was there from the start to the end of the scanning process. - -NOTE: If you do database changes within the callback, you should be aware -that the internal state of the database may change. For instance it is safe -to delete or modify the current key, but may not be safe to delete any -other key. -Moreover playing with the keyspace while iterating may have the -effect of returning more duplicates. A safe pattern is to store the keys -names you want to modify elsewhere, and perform the actions on the keys -later when the iteration is complete. However this can cost a lot of -memory, so it may make sense to just operate on the current key when -possible during the iteration, given that this is safe. - - - -### `ValkeyModule_ScanKey` - - int ValkeyModule_ScanKey(ValkeyModuleKey *key, - ValkeyModuleScanCursor *cursor, - ValkeyModuleScanKeyCB fn, - void *privdata); - -**Available since:** 6.0.0 - -Scan api that allows a module to scan the elements in a hash, set or sorted set key - -Callback for scan implementation. - - void scan_callback(ValkeyModuleKey *key, ValkeyModuleString* field, ValkeyModuleString* value, void *privdata); - -- key - the key context provided for the scan. -- field - field name, owned by the caller and need to be retained if used - after this function. -- value - value string or NULL for set type, owned by the caller and need to - be retained if used after this function. -- privdata - the user data provided to [`ValkeyModule_ScanKey`](#ValkeyModule_ScanKey). - -The way it should be used: - - ValkeyModuleScanCursor *c = ValkeyModule_ScanCursorCreate(); - ValkeyModuleKey *key = ValkeyModule_OpenKey(...) - while(ValkeyModule_ScanKey(key, c, callback, privateData)); - ValkeyModule_CloseKey(key); - ValkeyModule_ScanCursorDestroy(c); - -It is also possible to use this API from another thread while the lock is acquired during -the actual call to [`ValkeyModule_ScanKey`](#ValkeyModule_ScanKey), and re-opening the key each time: - - ValkeyModuleScanCursor *c = ValkeyModule_ScanCursorCreate(); - ValkeyModule_ThreadSafeContextLock(ctx); - ValkeyModuleKey *key = ValkeyModule_OpenKey(...) - while(ValkeyModule_ScanKey(ctx, c, callback, privateData)){ - ValkeyModule_CloseKey(key); - ValkeyModule_ThreadSafeContextUnlock(ctx); - // do some background job - ValkeyModule_ThreadSafeContextLock(ctx); - ValkeyModuleKey *key = ValkeyModule_OpenKey(...) - } - ValkeyModule_CloseKey(key); - ValkeyModule_ScanCursorDestroy(c); - -The function will return 1 if there are more elements to scan and 0 otherwise. -On a return value of 0, errno is set to distinguish the cases: - - 0 - the scan completed successfully. - - EINVAL - the key is NULL or not a hash, set or sorted set. - - ENOENT - the cursor is already exhausted (a previous call returned 0). -It is also possible to restart an existing cursor using [`ValkeyModule_ScanCursorRestart`](#ValkeyModule_ScanCursorRestart). - -NOTE: Certain operations are unsafe while iterating the object. For instance -while the API guarantees to return at least one time all the elements that -are present in the data structure consistently from the start to the end -of the iteration (see HSCAN and similar commands documentation), the more -you play with the elements, the more duplicates you may get. In general -deleting the current element of the data structure is safe, while removing -the key you are iterating is not safe. - - - -### `ValkeyModule_ScanKeyRawBorrowed` - - int ValkeyModule_ScanKeyRawBorrowed(ValkeyModuleKey *key, - ValkeyModuleScanCursor *cursor, - ValkeyModuleScanKeyRawBorrowedCB fn, - void *privdata); - -**Available since:** 9.2.0 - -Like [`ValkeyModule_ScanKey`](#ValkeyModule_ScanKey), but each element is delivered to the callback as -borrowed `(const char *, `size_t`)` byte ranges instead of allocating a -`ValkeyModuleString` per element. This avoids a per-element allocation on the -hot reply path. Works on the same key types as [`ValkeyModule_ScanKey`](#ValkeyModule_ScanKey): hash, -set and sorted set. - - void scan_callback(ValkeyModuleKey *key, const char *field, size_t field_len, - const char *value, size_t value_len, void *privdata); - -Per element the callback receives (field, `field_len`, value, `value_len`): - - HASH: field = field name, value = field value. - - SET: field = member, value = NULL, `value_len` = 0 (sets have no value). - - ZSET: field = member, value = score as a decimal string. - -The score string uses the same form as `ZRANGE ... WITHSCORES`: e.g. the score -1.5 is delivered as "1.5" and 2.0 as "2". ([`ValkeyModule_ScanKey`](#ValkeyModule_ScanKey) instead -delivers a `%.17Lg`-style rendering for sorted-set scores.) - -POINTER LIFETIME: the field and value pointers are only guaranteed to be valid -for the duration of the callback invocation. A typical use is to reply to the -calling client from within the callback with [`ValkeyModule_ReplyWithStringBuffer`](#ValkeyModule_ReplyWithStringBuffer). -To keep a field or value beyond the callback, copy it (for example into a -`ValkeyModuleString` with [`ValkeyModule_CreateString`](#ValkeyModule_CreateString)). - -The usage pattern, return value, errno semantics and iteration-safety notes -are identical to [`ValkeyModule_ScanKey`](#ValkeyModule_ScanKey). - - - -## Module fork API - - - -### `ValkeyModule_Fork` - - int ValkeyModule_Fork(ValkeyModuleForkDoneHandler cb, void *user_data); - -**Available since:** 6.0.0 - -Create a background child process with the current frozen snapshot of the -main process where you can do some processing in the background without -affecting / freezing the traffic and no need for threads and GIL locking. -Note that the server allows for only one concurrent fork. -When the child wants to exit, it should call [`ValkeyModule_ExitFromChild`](#ValkeyModule_ExitFromChild). -If the parent wants to kill the child it should call [`ValkeyModule_KillForkChild`](#ValkeyModule_KillForkChild) -The done handler callback will be executed on the parent process when the -child existed (but not when killed) -Return: -1 on failure, on success the parent process will get a positive PID -of the child, and the child process will get 0. - - - -### `ValkeyModule_SendChildHeartbeat` - - void ValkeyModule_SendChildHeartbeat(double progress); - -**Available since:** 6.2.0 - -The module is advised to call this function from the fork child once in a while, -so that it can report progress and COW memory to the parent which will be -reported in INFO. -The `progress` argument should between 0 and 1, or -1 when not available. - - - -### `ValkeyModule_ExitFromChild` - - int ValkeyModule_ExitFromChild(int retcode); - -**Available since:** 6.0.0 - -Call from the child process when you want to terminate it. -retcode will be provided to the done handler executed on the parent process. - - - -### `ValkeyModule_KillForkChild` - - int ValkeyModule_KillForkChild(int child_pid); - -**Available since:** 6.0.0 - -Can be used to kill the forked child process from the parent process. -`child_pid` would be the return value of [`ValkeyModule_Fork`](#ValkeyModule_Fork). - - - -## Server hooks implementation - - - -### `ValkeyModule_SubscribeToServerEvent` - - int ValkeyModule_SubscribeToServerEvent(ValkeyModuleCtx *ctx, - ValkeyModuleEvent event, - ValkeyModuleEventCallback callback); - -**Available since:** 6.0.0 - -Register to be notified, via a callback, when the specified server event -happens. The callback is called with the event as argument, and an additional -argument which is a void pointer and should be cased to a specific type -that is event-specific (but many events will just use NULL since they do not -have additional information to pass to the callback). - -If the callback is NULL and there was a previous subscription, the module -will be unsubscribed. If there was a previous subscription and the callback -is not null, the old callback will be replaced with the new one. - -The callback must be of this type: - - int (*ValkeyModuleEventCallback)(ValkeyModuleCtx *ctx, - ValkeyModuleEvent eid, - uint64_t subevent, - void *data); - -The 'ctx' is a normal module context that the callback can use in -order to call other modules APIs. The 'eid' is the event itself, this -is only useful in the case the module subscribed to multiple events: using -the 'id' field of this structure it is possible to check if the event -is one of the events we registered with this callback. The 'subevent' field -depends on the event that fired. - -Finally the 'data' pointer may be populated, only for certain events, with -more relevant data. - -Here is a list of events you can use as 'eid' and related sub events: - -* `ValkeyModuleEvent_ReplicationRoleChanged`: - - This event is called when the instance switches from primary - to replica or the other way around, however the event is - also called when the replica remains a replica but starts to - replicate with a different primary. - - The following sub events are available: - - * `VALKEYMODULE_SUBEVENT_REPLROLECHANGED_NOW_PRIMARY` - * `VALKEYMODULE_SUBEVENT_REPLROLECHANGED_NOW_REPLICA` - - The 'data' field can be casted by the callback to a - `ValkeyModuleReplicationInfo` structure with the following fields: - - int primary; // true if primary, false if replica - char *primary_host; // primary instance hostname for NOW_REPLICA - int primary_port; // primary instance port for NOW_REPLICA - char *replid1; // Main replication ID - char *replid2; // Secondary replication ID - uint64_t repl1_offset; // Main replication offset - uint64_t repl2_offset; // Offset of replid2 validity - -* `ValkeyModuleEvent_Persistence` - - This event is called when RDB saving or AOF rewriting starts - and ends. The following sub events are available: - - * `VALKEYMODULE_SUBEVENT_PERSISTENCE_RDB_START` - * `VALKEYMODULE_SUBEVENT_PERSISTENCE_AOF_START` - * `VALKEYMODULE_SUBEVENT_PERSISTENCE_SYNC_RDB_START` - * `VALKEYMODULE_SUBEVENT_PERSISTENCE_SYNC_AOF_START` - * `VALKEYMODULE_SUBEVENT_PERSISTENCE_ENDED` - * `VALKEYMODULE_SUBEVENT_PERSISTENCE_FAILED` - - The above events are triggered not just when the user calls the - relevant commands like BGSAVE, but also when a saving operation - or AOF rewriting occurs because of internal server triggers. - The SYNC_RDB_START sub events are happening in the foreground due to - SAVE command, FLUSHALL, or server shutdown, and the other RDB and - AOF sub events are executed in a background fork child, so any - action the module takes can only affect the generated AOF or RDB, - but will not be reflected in the parent process and affect connected - clients and commands. Also note that the AOF_START sub event may end - up saving RDB content in case of an AOF with rdb-preamble. - -* `ValkeyModuleEvent_FlushDB` - - The FLUSHALL, FLUSHDB or an internal flush (for instance - because of replication, after the replica synchronization) - happened. The following sub events are available: - - * `VALKEYMODULE_SUBEVENT_FLUSHDB_START` - * `VALKEYMODULE_SUBEVENT_FLUSHDB_END` - - The data pointer can be casted to a ValkeyModuleFlushInfo - structure with the following fields: - - int32_t async; // True if the flush is done in a thread. - // See for instance FLUSHALL ASYNC. - // In this case the END callback is invoked - // immediately after the database is put - // in the free list of the thread. - int32_t dbnum; // Flushed database number, -1 for all the DBs - // in the case of the FLUSHALL operation. - - The start event is called *before* the operation is initiated, thus - allowing the callback to call DBSIZE or other operation on the - yet-to-free keyspace. - -* `ValkeyModuleEvent_Loading` - - Called on loading operations: at startup when the server is - started, but also after a first synchronization when the - replica is loading the RDB file from the primary. - The following sub events are available: - - * `VALKEYMODULE_SUBEVENT_LOADING_RDB_START` - * `VALKEYMODULE_SUBEVENT_LOADING_AOF_START` - * `VALKEYMODULE_SUBEVENT_LOADING_REPL_START` - * `VALKEYMODULE_SUBEVENT_LOADING_ENDED` - * `VALKEYMODULE_SUBEVENT_LOADING_FAILED` - - Note that AOF loading may start with an RDB data in case of - rdb-preamble, in which case you'll only receive an AOF_START event. - -* `ValkeyModuleEvent_ClientChange` - - Called when a client connects or disconnects. - The data pointer can be casted to a ValkeyModuleClientInfo - structure, documented in ValkeyModule_GetClientInfoById(). - The following sub events are available: - - * `VALKEYMODULE_SUBEVENT_CLIENT_CHANGE_CONNECTED` - * `VALKEYMODULE_SUBEVENT_CLIENT_CHANGE_DISCONNECTED` - -* `ValkeyModuleEvent_Shutdown` - - The server is shutting down. No subevents are available. - -* `ValkeyModuleEvent_ReplicaChange` - - This event is called when the instance (that can be both a - primary or a replica) get a new online replica, or lose a - replica since it gets disconnected. - The following sub events are available: - - * `VALKEYMODULE_SUBEVENT_REPLICA_CHANGE_ONLINE` - * `VALKEYMODULE_SUBEVENT_REPLICA_CHANGE_OFFLINE` - - No additional information is available so far: future versions - of the server will have an API in order to enumerate the replicas - connected and their state. - -* `ValkeyModuleEvent_CronLoop` - - This event is called every time the server calls the serverCron() - function in order to do certain bookkeeping. Modules that are - required to do operations from time to time may use this callback. - Normally the server calls this function 10 times per second, but - this changes depending on the "hz" configuration. - No sub events are available. - - The data pointer can be casted to a ValkeyModuleCronLoop - structure with the following fields: - - int32_t hz; // Approximate number of events per second. - -* `ValkeyModuleEvent_PrimaryLinkChange` - - This is called for replicas in order to notify when the - replication link becomes functional (up) with our primary, - or when it goes down. Note that the link is not considered - up when we just connected to the primary, but only if the - replication is happening correctly. - The following sub events are available: - - * `VALKEYMODULE_SUBEVENT_PRIMARY_LINK_UP` - * `VALKEYMODULE_SUBEVENT_PRIMARY_LINK_DOWN` - -* `ValkeyModuleEvent_ModuleChange` - - This event is called when a new module is loaded or one is unloaded. - The following sub events are available: - - * `VALKEYMODULE_SUBEVENT_MODULE_LOADED` - * `VALKEYMODULE_SUBEVENT_MODULE_UNLOADED` - - The data pointer can be casted to a ValkeyModuleModuleChange - structure with the following fields: - - const char* module_name; // Name of module loaded or unloaded. - int32_t module_version; // Module version. - -* `ValkeyModuleEvent_LoadingProgress` - - This event is called repeatedly called while an RDB or AOF file - is being loaded. - The following sub events are available: - - * `VALKEYMODULE_SUBEVENT_LOADING_PROGRESS_RDB` - * `VALKEYMODULE_SUBEVENT_LOADING_PROGRESS_AOF` - - The data pointer can be casted to a ValkeyModuleLoadingProgress - structure with the following fields: - - int32_t hz; // Approximate number of events per second. - int32_t progress; // Approximate progress between 0 and 1024, - // or -1 if unknown. - -* `ValkeyModuleEvent_SwapDB` - - This event is called when a SWAPDB command has been successfully - Executed. - For this event call currently there is no subevents available. - - The data pointer can be casted to a ValkeyModuleSwapDbInfo - structure with the following fields: - - int32_t dbnum_first; // Swap Db first dbnum - int32_t dbnum_second; // Swap Db second dbnum - -* `ValkeyModuleEvent_ReplBackup` - - WARNING: Replication Backup events are deprecated since Redis OSS 7.0 and are never fired. - See ValkeyModuleEvent_ReplAsyncLoad for understanding how Async Replication Loading events - are now triggered when repl-diskless-load is set to swapdb. - - Called when repl-diskless-load config is set to swapdb, - And the server needs to backup the current database for the - possibility to be restored later. A module with global data and - maybe with aux_load and aux_save callbacks may need to use this - notification to backup / restore / discard its globals. - The following sub events are available: - - * `VALKEYMODULE_SUBEVENT_REPL_BACKUP_CREATE` - * `VALKEYMODULE_SUBEVENT_REPL_BACKUP_RESTORE` - * `VALKEYMODULE_SUBEVENT_REPL_BACKUP_DISCARD` - -* `ValkeyModuleEvent_ReplAsyncLoad` - - Called when repl-diskless-load config is set to swapdb and a replication with a primary of same - data set history (matching replication ID) occurs. - In which case the server serves current data set while loading new database in memory from socket. - Modules must have declared they support this mechanism in order to activate it, through - VALKEYMODULE_OPTIONS_HANDLE_REPL_ASYNC_LOAD flag. - The following sub events are available: - - * `VALKEYMODULE_SUBEVENT_REPL_ASYNC_LOAD_STARTED` - * `VALKEYMODULE_SUBEVENT_REPL_ASYNC_LOAD_ABORTED` - * `VALKEYMODULE_SUBEVENT_REPL_ASYNC_LOAD_COMPLETED` - -* `ValkeyModuleEvent_ForkChild` - - Called when a fork child (AOFRW, RDBSAVE, module fork...) is born/dies - The following sub events are available: - - * `VALKEYMODULE_SUBEVENT_FORK_CHILD_BORN` - * `VALKEYMODULE_SUBEVENT_FORK_CHILD_DIED` - -* `ValkeyModuleEvent_EventLoop` - - Called on each event loop iteration, once just before the event loop goes - to sleep or just after it wakes up. - The following sub events are available: - - * `VALKEYMODULE_SUBEVENT_EVENTLOOP_BEFORE_SLEEP` - * `VALKEYMODULE_SUBEVENT_EVENTLOOP_AFTER_SLEEP` - -* `ValkeyModuleEvent_Config` - - Called when a configuration event happens - The following sub events are available: - - * `VALKEYMODULE_SUBEVENT_CONFIG_CHANGE` - - The data pointer can be casted to a ValkeyModuleConfigChange - structure with the following fields: - - const char **config_names; // An array of C string pointers containing the - // name of each modified configuration item - uint32_t num_changes; // The number of elements in the config_names array - -* `ValkeyModuleEvent_Key` - - Called when a key is removed from the keyspace. We can't modify any key in - the event. - The following sub events are available: - - * `VALKEYMODULE_SUBEVENT_KEY_DELETED` - * `VALKEYMODULE_SUBEVENT_KEY_EXPIRED` - * `VALKEYMODULE_SUBEVENT_KEY_EVICTED` - * `VALKEYMODULE_SUBEVENT_KEY_OVERWRITTEN` - - The data pointer can be casted to a ValkeyModuleKeyInfo - structure with the following fields: - - ValkeyModuleKey *key; // Key name - -* `ValkeyModuleEvent_AuthenticationAttempt` - - Called when an authentication attempt is made, either successful or not. - - The data pointer can be casted to a ValkeyModuleAuthenticationInfo - structure with the following fields: - - uint64_t client_id; // Client ID. - const char *username; // Username used for authentication. - const char *module_name; // Name of the module that is handling the - // authentication. It is NULL if the - // authentication is handled by the core. - ValkeyModuleAuthenticationResult result; // Result of the authentication: - // VALKEYMODULE_AUTH_RESULT_GRANTED or - // VALKEYMODULE_AUTH_RESULT_DENIED - -* `ValkeyModuleEvent_AtomicSlotMigration` - - Called when an atomic slot migration (CLUSTER MIGRATESLOTS) is started or - ended in this node. This node may be a target or a source node, or the - target or source might be this node's primary. The following sub events - are available: - - * `VALKEYMODULE_SUBEVENT_ATOMIC_SLOT_MIGRATION_IMPORT_STARTED` - * `VALKEYMODULE_SUBEVENT_ATOMIC_SLOT_MIGRATION_EXPORT_STARTED` - * `VALKEYMODULE_SUBEVENT_ATOMIC_SLOT_MIGRATION_IMPORT_ABORTED` - * `VALKEYMODULE_SUBEVENT_ATOMIC_SLOT_MIGRATION_EXPORT_ABORTED` - * `VALKEYMODULE_SUBEVENT_ATOMIC_SLOT_MIGRATION_IMPORT_COMPLETED` - * `VALKEYMODULE_SUBEVENT_ATOMIC_SLOT_MIGRATION_EXPORT_COMPLETED` - - The data pointer can be casted to `ValkeyModuleAtomicSlotMigrationInfo` - structure with the following fields: - - char *job_name; // Unique ID for the operation (40 chars) - ValkeyModuleSlotRange *slot_ranges; // Array of slot ranges involved in the operation - uint32_t num_slot_ranges; // Number of slot ranges in slot_ranges array - - The `ValkeyModuleSlotRange` structure has the following fields: - - int start; // First slot in this range, inclusive - int end; // Last slot in this range, inclusive - - Modules can use these notifications to track the start and end of slot - migrations. Slot migrations will start with a STARTED subevent and end - with a COMPLETED subevent if they are successful and ownership is - transferred, or an ABORTED subevent if they were not successful and no - ownership change was made. While a slot migration is active, modules will - see incoming commands and keyspace notifications for importing keys. - Importing keys will not be accessible to clients unless the slot migration - is COMPLETED. - -* `ValkeyModuleEvent_CommandResultSuccess` - - Called after a command completes successfully. This event fires for every - successful command execution, including commands called via RM_Call. - Modules can subscribe to this event to monitor command execution, collect - metrics, or implement audit logging. - - The data pointer can be casted to a ValkeyModuleCommandResultInfo - structure with the following fields: - - const char *command_name; // Full command name (e.g., "SET", "CLIENT|LIST") - long long duration_us; // Command execution time in microseconds - long long dirty; // Number of keys modified by the command - unsigned long long client_id; // Client ID that executed the command - int is_module_client; // 1 if called via RM_Call, 0 otherwise - int argc; // Number of command arguments - ValkeyModuleString **argv; // Command arguments (read-only, zero-copy) - - Performance note: Subscribe only to ValkeyModuleEvent_CommandResultFailure - if you only need to track failures, as this avoids the overhead of firing - callbacks for successful commands. - -* `ValkeyModuleEvent_CommandResultFailure` - - Called after a command fails (returns an error). This event fires for every - failed command execution, including commands called via RM_Call. - Modules can subscribe to this event to monitor errors, implement alerting, - or track client misbehavior. - - The data pointer can be casted to a ValkeyModuleCommandResultInfo - structure with the same fields as ValkeyModuleEvent_CommandResultSuccess. - - This event is useful for monitoring command failures without the overhead - of receiving callbacks for all successful commands. - -* `ValkeyModuleEvent_CommandResultRejected` - - Called when a command is rejected before execution for non-ACL reasons - (unknown command, wrong arity, OOM, cluster redirect, loading, - busy script/module, read-only replica, Pub/Sub context, etc.). - - The subevent is always 0 for this event — there is no subevent breakdown. - - duration_us and dirty are always 0 for this event — the command never ran. - - The data pointer can be casted to a ValkeyModuleCommandResultInfo structure. - The `rejection_context` field carries the full error reply string that was - sent to the client (e.g. "-OOM command not allowed when used memory > - 'maxmemory'", "-ERR Command 'multi' not allowed inside a transaction"). - -* `ValkeyModuleEvent_CommandResultACLRejected` - - Called when a command is rejected before execution due to an ACL check - failure, or when an unauthenticated client sends a command (NOAUTH). - - For NOAUTH, see also ValkeyModuleEvent_AuthenticationAttempt - which covers AUTH/HELLO command outcomes. - - The subevent is a ValkeyModuleACLLogEntryReason value: - - VALKEYMODULE_ACL_LOG_AUTH (0): NOAUTH — client not yet authenticated - - VALKEYMODULE_ACL_LOG_CMD (1): NOPERM — command not permitted - - VALKEYMODULE_ACL_LOG_KEY (2): NOPERM — key access denied - - VALKEYMODULE_ACL_LOG_CHANNEL (3): NOPERM — channel access denied - - VALKEYMODULE_ACL_LOG_DB (4): NOPERM — database access denied - - duration_us and dirty are always 0 for this event — the command never ran. - - The data pointer can be casted to a ValkeyModuleCommandResultInfo structure. - The `rejection_context` field carries subevent-specific context: - - VALKEYMODULE_ACL_LOG_KEY / VALKEYMODULE_ACL_LOG_CHANNEL: - the denied key or channel name from argv - - All other ACL subevents: NULL - -The function returns `VALKEYMODULE_OK` if the module was successfully subscribed -for the specified event. If the API is called from a wrong context or unsupported event -is given then `VALKEYMODULE_ERR` is returned. - - - -### `ValkeyModule_IsSubEventSupported` - - int ValkeyModule_IsSubEventSupported(ValkeyModuleEvent event, int64_t subevent); - -**Available since:** 6.0.9 - - -For a given server event and subevent, return zero if the -subevent is not supported and non-zero otherwise. - - - -## Module Configurations API - - - -### `ValkeyModule_RegisterStringConfig` - - int ValkeyModule_RegisterStringConfig(ValkeyModuleCtx *ctx, - const char *name, - const char *default_val, - unsigned int flags, - ValkeyModuleConfigGetStringFunc getfn, - ValkeyModuleConfigSetStringFunc setfn, - ValkeyModuleConfigApplyFunc applyfn, - void *privdata); - -**Available since:** 7.0.0 - -Create a string config that users can interact with via the server config file, -`CONFIG SET`, `CONFIG GET`, and `CONFIG REWRITE` commands. - -The actual config value is owned by the module, and the `getfn`, `setfn` and optional -`applyfn` callbacks that are provided to the server in order to access or manipulate the -value. The `getfn` callback retrieves the value from the module, while the `setfn` -callback provides a value to be stored into the module config. -The optional `applyfn` callback is called after a `CONFIG SET` command modified one or -more configs using the `setfn` callback and can be used to atomically apply a config -after several configs were changed together. -If there are multiple configs with `applyfn` callbacks set by a single `CONFIG SET` -command, they will be deduplicated if their `applyfn` function and `privdata` pointers -are identical, and the callback will only be run once. -Both the `setfn` and `applyfn` can return an error if the provided value is invalid or -cannot be used. -The config also declares a type for the value that is validated by the server and -provided to the module. The config system provides the following types: - -* String: Binary safe string data. -* Enum: One of a finite number of string tokens, provided during registration. -* Numeric: 64 bit signed integer, which also supports min and max values. -* Bool: Yes or no value. - -The `setfn` callback is expected to return `VALKEYMODULE_OK` when the value is successfully -applied. It can also return `VALKEYMODULE_ERR` if the value can't be applied, and the -*err pointer can be set with a `ValkeyModuleString` error message to provide to the client. -This `ValkeyModuleString` will be freed by the server after returning from the set callback. - -All configs are registered with a name, a type, a default value, private data that is made -available in the callbacks, as well as several flags that modify the behavior of the config. -The name must only contain alphanumeric characters or dashes. The supported flags are: - -* `VALKEYMODULE_CONFIG_DEFAULT`: The default flags for a config. This creates a config that can be modified after -startup. -* `VALKEYMODULE_CONFIG_IMMUTABLE`: This config can only be provided loading time. -* `VALKEYMODULE_CONFIG_SENSITIVE`: The value stored in this config is redacted from all logging. -* `VALKEYMODULE_CONFIG_HIDDEN`: The name is hidden from `CONFIG GET` with pattern matching. -* `VALKEYMODULE_CONFIG_PROTECTED`: This config will be only be modifiable based off the value of -enable-protected-configs. -* `VALKEYMODULE_CONFIG_DENY_LOADING`: This config is not modifiable while the server is loading data. -* `VALKEYMODULE_CONFIG_MEMORY`: For numeric configs, this config will convert data unit notations into their byte -equivalent. -* `VALKEYMODULE_CONFIG_BITFLAGS`: For enum configs, this config will allow multiple entries to be combined as bit -flags. - -Default values are used on startup to set the value if it is not provided via the config file -or command line. Default values are also used to compare to on a config rewrite. - -Notes: - - 1. On string config sets that the string passed to the set callback will be freed after execution and the module -must retain it. - 2. On string config gets the string will not be consumed and will be valid after execution. - -Example implementation: - - ValkeyModuleString *strval; - int adjustable = 1; - ValkeyModuleString *getStringConfigCommand(const char *name, void *privdata) { - return strval; - } - - int setStringConfigCommand(const char *name, ValkeyModuleString *new, void *privdata, ValkeyModuleString **err) { - if (adjustable) { - ValkeyModule_Free(strval); - ValkeyModule_RetainString(NULL, new); - strval = new; - return VALKEYMODULE_OK; - } - *err = ValkeyModule_CreateString(NULL, "Not adjustable.", 15); - return VALKEYMODULE_ERR; - } - ... - ValkeyModule_RegisterStringConfig(ctx, "string", NULL, VALKEYMODULE_CONFIG_DEFAULT, getStringConfigCommand, -setStringConfigCommand, NULL, NULL); - -If the registration fails, `VALKEYMODULE_ERR` is returned and one of the following -errno is set: -* EBUSY: Registering the Config outside of `ValkeyModule_OnLoad`. -* EINVAL: The provided flags are invalid for the registration or the name of the config contains invalid characters. -* EALREADY: The provided configuration name is already used. - - - -### `ValkeyModule_RegisterBoolConfig` - - int ValkeyModule_RegisterBoolConfig(ValkeyModuleCtx *ctx, - const char *name, - int default_val, - unsigned int flags, - ValkeyModuleConfigGetBoolFunc getfn, - ValkeyModuleConfigSetBoolFunc setfn, - ValkeyModuleConfigApplyFunc applyfn, - void *privdata); - -**Available since:** 7.0.0 - -Create a bool config that server clients can interact with via the -`CONFIG SET`, `CONFIG GET`, and `CONFIG REWRITE` commands. See -[`ValkeyModule_RegisterStringConfig`](#ValkeyModule_RegisterStringConfig) for detailed information about configs. - - - -### `ValkeyModule_RegisterEnumConfig` - - int ValkeyModule_RegisterEnumConfig(ValkeyModuleCtx *ctx, - const char *name, - int default_val, - unsigned int flags, - const char **enum_values, - const int *int_values, - int num_enum_vals, - ValkeyModuleConfigGetEnumFunc getfn, - ValkeyModuleConfigSetEnumFunc setfn, - ValkeyModuleConfigApplyFunc applyfn, - void *privdata); - -**Available since:** 7.0.0 - - -Create an enum config that server clients can interact with via the -`CONFIG SET`, `CONFIG GET`, and `CONFIG REWRITE` commands. -Enum configs are a set of string tokens to corresponding integer values, where -the string value is exposed to clients but the inter value is passed to the server -and the module. These values are defined in `enum_values`, an array -of null-terminated c strings, and `int_vals`, an array of enum values who has an -index partner in `enum_values`. -Example Implementation: - const char *enum_vals[3] = {"first", "second", "third"}; - const int int_vals[3] = {0, 2, 4}; - int enum_val = 0; - - int getEnumConfigCommand(const char *name, void *privdata) { - return enum_val; - } - - int setEnumConfigCommand(const char *name, int val, void *privdata, const char **err) { - enum_val = val; - return VALKEYMODULE_OK; - } - ... - ValkeyModule_RegisterEnumConfig(ctx, "enum", 0, VALKEYMODULE_CONFIG_DEFAULT, enum_vals, int_vals, 3, -getEnumConfigCommand, setEnumConfigCommand, NULL, NULL); - -Note that you can use `VALKEYMODULE_CONFIG_BITFLAGS` so that multiple enum string -can be combined into one integer as bit flags, in which case you may want to -sort your enums so that the preferred combinations are present first. - -See [`ValkeyModule_RegisterStringConfig`](#ValkeyModule_RegisterStringConfig) for detailed general information about configs. - - - -### `ValkeyModule_RegisterNumericConfig` - - int ValkeyModule_RegisterNumericConfig(ValkeyModuleCtx *ctx, - const char *name, - long long default_val, - unsigned int flags, - long long min, - long long max, - ValkeyModuleConfigGetNumericFunc getfn, - ValkeyModuleConfigSetNumericFunc setfn, - ValkeyModuleConfigApplyFunc applyfn, - void *privdata); - -**Available since:** 7.0.0 - - -Create an integer config that server clients can interact with via the -`CONFIG SET`, `CONFIG GET`, and `CONFIG REWRITE` commands. See -[`ValkeyModule_RegisterStringConfig`](#ValkeyModule_RegisterStringConfig) for detailed information about configs. - - - -### `ValkeyModule_RegisterUnsignedNumericConfig` - - int ValkeyModule_RegisterUnsignedNumericConfig(ValkeyModuleCtx *ctx, - const char *name, - unsigned long long default_val, - unsigned int flags, - unsigned long long min, - unsigned long long max, - ValkeyModuleConfigGetUnsignedNumericFunc getfn, - ValkeyModuleConfigSetUnsignedNumericFunc setfn, - ValkeyModuleConfigApplyFunc applyfn, - void *privdata); - -**Available since:** 9.1.0 - - -Create an unsigned integer config that server clients can interact with via the -`CONFIG SET`, `CONFIG GET`, and `CONFIG REWRITE` commands. See -[`ValkeyModule_RegisterStringConfig`](#ValkeyModule_RegisterStringConfig) for detailed information about configs. - - - -### `ValkeyModule_LoadConfigs` - - int ValkeyModule_LoadConfigs(ValkeyModuleCtx *ctx); - -**Available since:** 7.0.0 - -Applies all pending configurations on the module load. This should be called -after all of the configurations have been registered for the module inside of `ValkeyModule_OnLoad`. -This will return `VALKEYMODULE_ERR` if it is called outside `ValkeyModule_OnLoad`. -This API needs to be called when configurations are provided in either `MODULE LOADEX` -or provided as startup arguments. - - - -## RDB load/save API - - - -### `ValkeyModule_RdbStreamCreateFromFile` - - ValkeyModuleRdbStream *ValkeyModule_RdbStreamCreateFromFile(const char *filename); - -**Available since:** 7.2.0 - -Create a stream object to save/load RDB to/from a file. - -This function returns a pointer to `ValkeyModuleRdbStream` which is owned -by the caller. It requires a call to [`ValkeyModule_RdbStreamFree()`](#ValkeyModule_RdbStreamFree) to free -the object. - - - -### `ValkeyModule_RdbStreamFree` - - void ValkeyModule_RdbStreamFree(ValkeyModuleRdbStream *stream); - -**Available since:** 7.2.0 - -Release an RDB stream object. - - - -### `ValkeyModule_RdbLoad` - - int ValkeyModule_RdbLoad(ValkeyModuleCtx *ctx, - ValkeyModuleRdbStream *stream, - int flags); - -**Available since:** 7.2.0 - -Load RDB file from the `stream`. Dataset will be cleared first and then RDB -file will be loaded. - -`flags` must be zero. This parameter is for future use. - -On success `VALKEYMODULE_OK` is returned; otherwise, `VALKEYMODULE_ERR` is returned -and errno is set accordingly. - -Example: - - ValkeyModuleRdbStream *s = ValkeyModule_RdbStreamCreateFromFile("exp.rdb"); - ValkeyModule_RdbLoad(ctx, s, 0); - ValkeyModule_RdbStreamFree(s); - - - -### `ValkeyModule_RdbSave` - - int ValkeyModule_RdbSave(ValkeyModuleCtx *ctx, - ValkeyModuleRdbStream *stream, - int flags); - -**Available since:** 7.2.0 - -Save dataset to the RDB stream. - -`flags` must be zero. This parameter is for future use. - -On success `VALKEYMODULE_OK` is returned; otherwise, `VALKEYMODULE_ERR` is returned -and errno is set accordingly. - -Example: - - ValkeyModuleRdbStream *s = ValkeyModule_RdbStreamCreateFromFile("exp.rdb"); - ValkeyModule_RdbSave(ctx, s, 0); - ValkeyModule_RdbStreamFree(s); - - - -## Scripting Engine API - - - -### `ValkeyModule_RegisterScriptingEngine` - - int ValkeyModule_RegisterScriptingEngine(ValkeyModuleCtx *module_ctx, - const char *engine_name, - ValkeyModuleScriptingEngineCtx *engine_ctx, - ValkeyModuleScriptingEngineMethods *engine_methods); - -**Available since:** 8.1.0 - -Registers a new scripting engine in the server. - -- `module_ctx`: the module context object. - -- `engine_name`: the name of the scripting engine. This name will match - against the engine name specified in the script header using a shebang. - -- `engine_ctx`: engine specific context pointer. - -- `engine_methods`: the struct with the scripting engine callback functions - pointers. - -Returns `VALKEYMODULE_OK` if the engine is successfully registered, and -`VALKEYMODULE_ERR` in case some failure occurs. In case of a failure, an error -message is logged. - - - -### `ValkeyModule_UnregisterScriptingEngine` - - int ValkeyModule_UnregisterScriptingEngine(ValkeyModuleCtx *ctx, - const char *engine_name); - -**Available since:** 8.1.0 - -Removes the scripting engine from the server. - -`engine_name` is the name of the scripting engine. - -Returns `VALKEYMODULE_OK`. - - - -### `ValkeyModule_GetFunctionExecutionState` - - ValkeyModuleScriptingEngineExecutionState ValkeyModule_GetFunctionExecutionState( ValkeyModuleScriptingEngineServerRuntimeCtx *server_ctx); - -**Available since:** 8.1.0 - -Returns the state of the current function being executed by the scripting -engine. - -`server_ctx` is the server runtime context. - -It will return `VMSE_STATE_KILLED` if the function was already killed either by -a `SCRIPT KILL`, or `FUNCTION KILL`. - - - -### `ValkeyModule_ScriptingEngineDebuggerLog` - - void ValkeyModule_ScriptingEngineDebuggerLog(ValkeyModuleString *msg, - int truncate); - -**Available since:** 9.1.0 - -Function to send string messages to the client during a debug session. -These messages are buffered in memory, and are only sent to the client when -`ValkeyModule_VM_ScriptingEngineDebuggerFlushLogs` is called. - -- `msg`: the message to send. Ownership of `msg` is transferred to the - debugger log. The caller must not free it or access it after this call. - -- `truncate`: if set to 1, the message will be truncated to the maximum length - configured in the debugger settings. - - - -### `ValkeyModule_ScriptingEngineDebuggerLogRespReplyStr` - - void ValkeyModule_ScriptingEngineDebuggerLogRespReplyStr(const char *reply); - -**Available since:** 9.1.0 - -Function to log a RESP reply C string as debugger output, in a human readable -format. - -If the resulting string is longer than the maximum text length, configured in -the debugger settings, plus a few more chars used as prefix, it gets truncated. - - - -### `ValkeyModule_ScriptingEngineDebuggerLogRespReply` - - void ValkeyModule_ScriptingEngineDebuggerLogRespReply(ValkeyModuleCallReply *reply); - -**Available since:** 9.1.0 - -Function to log a RESP reply as debugger output, in a human readable format. - -If the resulting string is longer than the maximum text length, configured in -the debugger settings, plus a few more chars used as prefix, it gets truncated. - - - -### `ValkeyModule_ScriptingEngineDebuggerFlushLogs` - - void ValkeyModule_ScriptingEngineDebuggerFlushLogs(void); - -**Available since:** 9.1.0 - -Function to send all debugger messages in the memory buffer written with the -[`ValkeyModule_ScriptingEngineDebuggerLog`](#ValkeyModule_ScriptingEngineDebuggerLog) function. - - - -### `ValkeyModule_ScriptingEngineDebuggerProcessCommands` - - void ValkeyModule_ScriptingEngineDebuggerProcessCommands(int *client_disconnected, - ValkeyModuleString **err); - -**Available since:** 9.1.0 - -Function used to process debugger commands sent by the client. - -This function in conjunction with [`ValkeyModule_ScriptingEngineDebuggerLog`](#ValkeyModule_ScriptingEngineDebuggerLog) and -[`ValkeyModule_ScriptingEngineDebuggerFlushLogs`](#ValkeyModule_ScriptingEngineDebuggerFlushLogs) allows to implement an -interactive debugging session for scripts executed by the scripting engine. - - - -## Key eviction API - - - -### `ValkeyModule_SetLRU` - - int ValkeyModule_SetLRU(ValkeyModuleKey *key, mstime_t lru_idle); - -**Available since:** 6.0.0 - -Set the key last access time for LRU based eviction. not relevant if the -servers's maxmemory policy is LFU based. Value is idle time in milliseconds. -returns `VALKEYMODULE_OK` if the LRU was updated, `VALKEYMODULE_ERR` otherwise. - - - -### `ValkeyModule_GetLRU` - - int ValkeyModule_GetLRU(ValkeyModuleKey *key, mstime_t *lru_idle); - -**Available since:** 6.0.0 - -Gets the key last access time. -Value is idletime in milliseconds or -1 if the server's eviction policy is -LFU based. -returns `VALKEYMODULE_OK` if when key is valid. - - - -### `ValkeyModule_SetLFU` - - int ValkeyModule_SetLFU(ValkeyModuleKey *key, long long lfu_freq); - -**Available since:** 6.0.0 - -Set the key access frequency. only relevant if the server's maxmemory policy -is LFU based. -The frequency is a logarithmic counter that provides an indication of -the access frequency (must be <= 255). -returns `VALKEYMODULE_OK` if the LFU was updated, `VALKEYMODULE_ERR` otherwise. - - - -### `ValkeyModule_GetLFU` - - int ValkeyModule_GetLFU(ValkeyModuleKey *key, long long *lfu_freq); - -**Available since:** 6.0.0 - -Gets the key access frequency or -1 if the server's eviction policy is not -LFU based. -returns `VALKEYMODULE_OK` if when key is valid. - - - -## Miscellaneous APIs - - - -### `ValkeyModule_GetModuleOptionsAll` - - int ValkeyModule_GetModuleOptionsAll(void); - -**Available since:** 7.2.0 - - -Returns the full module options flags mask, using the return value -the module can check if a certain set of module options are supported -by the server version in use. -Example: - - int supportedFlags = ValkeyModule_GetModuleOptionsAll(); - if (supportedFlags & VALKEYMODULE_OPTIONS_ALLOW_NESTED_KEYSPACE_NOTIFICATIONS) { - // VALKEYMODULE_OPTIONS_ALLOW_NESTED_KEYSPACE_NOTIFICATIONS is supported - } else{ - // VALKEYMODULE_OPTIONS_ALLOW_NESTED_KEYSPACE_NOTIFICATIONS is not supported - } - - - -### `ValkeyModule_GetContextFlagsAll` - - int ValkeyModule_GetContextFlagsAll(void); - -**Available since:** 6.0.9 - - -Returns the full ContextFlags mask, using the return value -the module can check if a certain set of flags are supported -by the server version in use. -Example: - - int supportedFlags = ValkeyModule_GetContextFlagsAll(); - if (supportedFlags & VALKEYMODULE_CTX_FLAGS_MULTI) { - // VALKEYMODULE_CTX_FLAGS_MULTI is supported - } else{ - // VALKEYMODULE_CTX_FLAGS_MULTI is not supported - } - - - -### `ValkeyModule_GetKeyspaceNotificationFlagsAll` - - int ValkeyModule_GetKeyspaceNotificationFlagsAll(void); - -**Available since:** 6.0.9 - - -Returns the full KeyspaceNotification mask, using the return value -the module can check if a certain set of flags are supported -by the server version in use. -Example: - - int supportedFlags = ValkeyModule_GetKeyspaceNotificationFlagsAll(); - if (supportedFlags & VALKEYMODULE_NOTIFY_LOADED) { - // VALKEYMODULE_NOTIFY_LOADED is supported - } else{ - // VALKEYMODULE_NOTIFY_LOADED is not supported - } - - - -### `ValkeyModule_GetServerVersion` - - int ValkeyModule_GetServerVersion(void); - -**Available since:** 6.0.9 - - -Return the server version in format of 0x00MMmmpp. -Example for 6.0.7 the return value will be 0x00060007. - - - -### `ValkeyModule_GetTypeMethodVersion` - - int ValkeyModule_GetTypeMethodVersion(void); - -**Available since:** 6.2.0 - - -Return the current server runtime value of `VALKEYMODULE_TYPE_METHOD_VERSION`. -You can use that when calling [`ValkeyModule_CreateDataType`](#ValkeyModule_CreateDataType) to know which fields of -`ValkeyModuleTypeMethods` are gonna be supported and which will be ignored. - - - -### `ValkeyModule_ModuleTypeReplaceValue` - - int ValkeyModule_ModuleTypeReplaceValue(ValkeyModuleKey *key, - moduleType *mt, - void *new_value, - void **old_value); - -**Available since:** 6.0.0 - -Replace the value assigned to a module type. - -The key must be open for writing, have an existing value, and have a moduleType -that matches the one specified by the caller. - -Unlike [`ValkeyModule_ModuleTypeSetValue()`](#ValkeyModule_ModuleTypeSetValue) which will free the old value, this function -simply swaps the old value with the new value. - -The function returns `VALKEYMODULE_OK` on success, `VALKEYMODULE_ERR` on errors -such as: - -1. Key is not opened for writing. -2. Key is not a module data type key. -3. Key is a module datatype other than 'mt'. - -If `old_value` is non-NULL, the old value is returned by reference. - - - -### `ValkeyModule_GetCommandKeysWithFlags` - - int *ValkeyModule_GetCommandKeysWithFlags(ValkeyModuleCtx *ctx, - ValkeyModuleString **argv, - int argc, - int *num_keys, - int **out_flags); - -**Available since:** 7.0.0 - -For a specified command, parse its arguments and return an array that -contains the indexes of all key name arguments. This function is -essentially a more efficient way to do `COMMAND GETKEYS`. - -The `out_flags` argument is optional, and can be set to NULL. -When provided it is filled with `VALKEYMODULE_CMD_KEY_` flags in matching -indexes with the key indexes of the returned array. - -A NULL return value indicates the specified command has no keys, or -an error condition. Error conditions are indicated by setting errno -as follows: - -* ENOENT: Specified command does not exist. -* EINVAL: Invalid command arity specified. - -NOTE: The returned array is not a Module object so it does not -get automatically freed even when auto-memory is used. The caller -must explicitly call [`ValkeyModule_Free()`](#ValkeyModule_Free) to free it, same as the `out_flags` pointer if -used. - - - -### `ValkeyModule_GetCommandKeys` - - int *ValkeyModule_GetCommandKeys(ValkeyModuleCtx *ctx, - ValkeyModuleString **argv, - int argc, - int *num_keys); - -**Available since:** 6.0.9 - -Identical to [`ValkeyModule_GetCommandKeysWithFlags`](#ValkeyModule_GetCommandKeysWithFlags) when flags are not needed. - - - -### `ValkeyModule_GetCurrentCommandName` - - const char *ValkeyModule_GetCurrentCommandName(ValkeyModuleCtx *ctx); - -**Available since:** 6.2.5 - -Return the name of the command currently running - - - -## Defrag API - - - -### `ValkeyModule_RegisterDefragFunc` - - int ValkeyModule_RegisterDefragFunc(ValkeyModuleCtx *ctx, - ValkeyModuleDefragFunc cb); - -**Available since:** 6.2.0 - -Register a defrag callback for global data, i.e. anything that the module -may allocate that is not tied to a specific data type. - -The callback is invoked with a time limit: it should call [`ValkeyModule_DefragShouldStop()`](#ValkeyModule_DefragShouldStop) periodically, and -save its position with [`ValkeyModule_DefragCursorSet()`](#ValkeyModule_DefragCursorSet) so a later invocation can resume (using [`ValkeyModule_DefragCursorGet`](#ValkeyModule_DefragCursorGet)). - -If a non-zero cursor is set ([`ValkeyModule_DefragCursorSet`](#ValkeyModule_DefragCursorSet)) the function will be invoked repeatedly until a zero -cursor is returned. - - - -### `ValkeyModule_DefragShouldStop` - - int ValkeyModule_DefragShouldStop(ValkeyModuleDefragCtx *ctx); - -**Available since:** 6.2.0 - -When a defrag callback iterates complex structures, this -function should be called periodically. A zero (false) return -indicates the callback may continue its work. A non-zero value (true) -indicates it should stop. - -When stopped, the callback may use [`ValkeyModule_DefragCursorSet()`](#ValkeyModule_DefragCursorSet) to store its -position so it can later use [`ValkeyModule_DefragCursorGet()`](#ValkeyModule_DefragCursorGet) to resume defragging. - -When stopped and more work is left to be done, the data type callback -should return 1. Otherwise, it should return 0. The global callback has no -return value and reports this through its cursor instead. - -NOTE: Modules should consider the frequency in which this function is called, -so it generally makes sense to do small batches of work in between calls. - - - -### `ValkeyModule_DefragCursorSet` - - int ValkeyModule_DefragCursorSet(ValkeyModuleDefragCtx *ctx, - unsigned long cursor); - -**Available since:** 6.2.0 - -Store an arbitrary cursor value for future re-use. - -For a data type callback, this should only be called if [`ValkeyModule_DefragShouldStop()`](#ValkeyModule_DefragShouldStop) -has returned a non-zero value and the defrag callback is about to exit without -fully iterating its data type. - -This behavior is reserved to cases where late defrag is performed. Late -defrag is selected for keys that implement the `free_effort` callback and -return a `free_effort` value that is larger than the defrag -'active-defrag-max-scan-fields' configuration directive. - -Smaller keys and keys that do not implement `free_effort` are not called in -late-defrag mode. In those cases, a call to this function will return -`VALKEYMODULE_ERR`. - -The cursor may be used by the module to represent some progress into the -module's data type. Modules may also store additional cursor-related -information locally and use the cursor as a flag that indicates when -traversal of a new key begins. This is possible because the API makes -a guarantee that concurrent defragmentation of multiple keys will -not be performed. - -A global callback (registered with [`ValkeyModule_RegisterDefragFunc`](#ValkeyModule_RegisterDefragFunc)) always has a cursor -available, and the cursor is also how it reports completion: 0, the value a -fresh pass starts from, means done, and non-zero means it will be invoked -again. The server discards the cursor once the callback completes or the pass -is interrupted, so a cursor saved before an interruption is never handed -back. A flush or a database swap does not end defragmentation, so a -module must still be able to restart when its cursor may be invalid, -usually just returning a 0 cursor, indicating done. - - - -### `ValkeyModule_DefragCursorGet` - - int ValkeyModule_DefragCursorGet(ValkeyModuleDefragCtx *ctx, - unsigned long *cursor); - -**Available since:** 6.2.0 - -Fetch a cursor value that has been previously stored using [`ValkeyModule_DefragCursorSet()`](#ValkeyModule_DefragCursorSet). - -If no cursor is available, `VALKEYMODULE_ERR` will be returned and -the cursor should be ignored. See [`ValkeyModule_DefragCursorSet()`](#ValkeyModule_DefragCursorSet) for more details on -defrag cursors. - - - -### `ValkeyModule_DefragAlloc` - - void *ValkeyModule_DefragAlloc(ValkeyModuleDefragCtx *ctx, void *ptr); - -**Available since:** 6.2.0 - -Defrag a memory allocation previously allocated by [`ValkeyModule_Alloc`](#ValkeyModule_Alloc), [`ValkeyModule_Calloc`](#ValkeyModule_Calloc), etc. -The defragmentation process involves allocating a new memory block and copying -the contents to it, like `realloc()`. - -If defragmentation was not necessary, NULL is returned and the operation has -no other effect. - -If a non-NULL value is returned, the caller should use the new pointer instead -of the old one and update any reference to the old pointer, which must not -be used again. - - - -### `ValkeyModule_DefragValkeyModuleString` - - ValkeyModuleString *ValkeyModule_DefragValkeyModuleString(ValkeyModuleDefragCtx *ctx, - ValkeyModuleString *str); - -**Available since:** 7.2.4 - -Defrag a `ValkeyModuleString` previously allocated by [`ValkeyModule_Alloc`](#ValkeyModule_Alloc), [`ValkeyModule_Calloc`](#ValkeyModule_Calloc), etc. -See [`ValkeyModule_DefragAlloc()`](#ValkeyModule_DefragAlloc) for more information on how the defragmentation process -works. - -NOTE: It is only possible to defrag strings that have a single reference. -Typically this means strings retained with [`ValkeyModule_RetainString`](#ValkeyModule_RetainString) or [`ValkeyModule_HoldString`](#ValkeyModule_HoldString) -may not be defragmentable. One exception is command argvs which, if retained -by the module, will end up with a single reference (because the reference -on the server side is dropped as soon as the command callback returns). - - - -### `ValkeyModule_GetKeyNameFromDefragCtx` - - const ValkeyModuleString *ValkeyModule_GetKeyNameFromDefragCtx(ValkeyModuleDefragCtx *ctx); - -**Available since:** 7.0.0 - -Returns the name of the key currently being processed. -There is no guarantee that the key name is always available, so this may return NULL. - - - -### `ValkeyModule_GetDbIdFromDefragCtx` - - int ValkeyModule_GetDbIdFromDefragCtx(ValkeyModuleDefragCtx *ctx); - -**Available since:** 7.0.0 - -Returns the database id of the key currently being processed. -There is no guarantee that this info is always available, so this may return -1. - - - -### `ValkeyModule_ACLCheckKeyPrefixPermissions` - - int ValkeyModule_ACLCheckKeyPrefixPermissions(ValkeyModuleUser *user, - const char *key, - size_t len, - unsigned int flags); - -**Available since:** 9.1.0 - -This function verifies that the user is authorized to carry out the operations indicated in the -`flags` parameter on keys that begin with the specified prefix. - -This function validates that the supplied ACL flags are a subset of the allowed key‑access flags -(`VALKEYMODULE_CMD_KEY_ACCESS`,`VALKEYMODULE_CMD_KEY_INSERT`, `VALKEYMODULE_CMD_KEY_DELETE`, -`VALKEYMODULE_CMD_KEY_UPDATE`). It then converts the flags into key‑specification flags (`CMD_KEY_*`) and calls -`ACLUserCheckKeyPerm` to ensure the user has permission for the specified key prefix. - -If any check fails, returns `VALKEYMODULE_ERR` and sets `errno` to the appropriate error code: - -- `EINVAL` for invalid flags or NULL user -- `EACCES` for insufficient permissions - - Otherwise it returns `VALKEYMODULE_OK`. - - - -## Function index - -* [`ValkeyModule_ACLAddLogEntry`](#ValkeyModule_ACLAddLogEntry) -* [`ValkeyModule_ACLAddLogEntryByUserName`](#ValkeyModule_ACLAddLogEntryByUserName) -* [`ValkeyModule_ACLCheckChannelPermissions`](#ValkeyModule_ACLCheckChannelPermissions) -* [`ValkeyModule_ACLCheckCommandPermissions`](#ValkeyModule_ACLCheckCommandPermissions) -* [`ValkeyModule_ACLCheckKeyPermissions`](#ValkeyModule_ACLCheckKeyPermissions) -* [`ValkeyModule_ACLCheckKeyPrefixPermissions`](#ValkeyModule_ACLCheckKeyPrefixPermissions) -* [`ValkeyModule_ACLCheckPermissions`](#ValkeyModule_ACLCheckPermissions) -* [`ValkeyModule_AbortBlock`](#ValkeyModule_AbortBlock) -* [`ValkeyModule_AddACLCategory`](#ValkeyModule_AddACLCategory) -* [`ValkeyModule_AddPostNotificationJob`](#ValkeyModule_AddPostNotificationJob) -* [`ValkeyModule_Alloc`](#ValkeyModule_Alloc) -* [`ValkeyModule_AuthenticateClientWithACLUser`](#ValkeyModule_AuthenticateClientWithACLUser) -* [`ValkeyModule_AuthenticateClientWithUser`](#ValkeyModule_AuthenticateClientWithUser) -* [`ValkeyModule_AutoMemory`](#ValkeyModule_AutoMemory) -* [`ValkeyModule_AvoidReplicaTraffic`](#ValkeyModule_AvoidReplicaTraffic) -* [`ValkeyModule_BlockClient`](#ValkeyModule_BlockClient) -* [`ValkeyModule_BlockClientGetPrivateData`](#ValkeyModule_BlockClientGetPrivateData) -* [`ValkeyModule_BlockClientOnAuth`](#ValkeyModule_BlockClientOnAuth) -* [`ValkeyModule_BlockClientOnKeys`](#ValkeyModule_BlockClientOnKeys) -* [`ValkeyModule_BlockClientOnKeysWithFlags`](#ValkeyModule_BlockClientOnKeysWithFlags) -* [`ValkeyModule_BlockClientSetPrivateData`](#ValkeyModule_BlockClientSetPrivateData) -* [`ValkeyModule_BlockedClientDisconnected`](#ValkeyModule_BlockedClientDisconnected) -* [`ValkeyModule_BlockedClientMeasureTimeEnd`](#ValkeyModule_BlockedClientMeasureTimeEnd) -* [`ValkeyModule_BlockedClientMeasureTimeStart`](#ValkeyModule_BlockedClientMeasureTimeStart) -* [`ValkeyModule_CachedMicroseconds`](#ValkeyModule_CachedMicroseconds) -* [`ValkeyModule_Call`](#ValkeyModule_Call) -* [`ValkeyModule_CallArgv`](#ValkeyModule_CallArgv) -* [`ValkeyModule_CallReplyArrayElement`](#ValkeyModule_CallReplyArrayElement) -* [`ValkeyModule_CallReplyAttribute`](#ValkeyModule_CallReplyAttribute) -* [`ValkeyModule_CallReplyAttributeElement`](#ValkeyModule_CallReplyAttributeElement) -* [`ValkeyModule_CallReplyBigNumber`](#ValkeyModule_CallReplyBigNumber) -* [`ValkeyModule_CallReplyBool`](#ValkeyModule_CallReplyBool) -* [`ValkeyModule_CallReplyDouble`](#ValkeyModule_CallReplyDouble) -* [`ValkeyModule_CallReplyInteger`](#ValkeyModule_CallReplyInteger) -* [`ValkeyModule_CallReplyLength`](#ValkeyModule_CallReplyLength) -* [`ValkeyModule_CallReplyMapElement`](#ValkeyModule_CallReplyMapElement) -* [`ValkeyModule_CallReplyPromiseAbort`](#ValkeyModule_CallReplyPromiseAbort) -* [`ValkeyModule_CallReplyPromiseSetUnblockHandler`](#ValkeyModule_CallReplyPromiseSetUnblockHandler) -* [`ValkeyModule_CallReplyProto`](#ValkeyModule_CallReplyProto) -* [`ValkeyModule_CallReplySetElement`](#ValkeyModule_CallReplySetElement) -* [`ValkeyModule_CallReplyStringPtr`](#ValkeyModule_CallReplyStringPtr) -* [`ValkeyModule_CallReplyType`](#ValkeyModule_CallReplyType) -* [`ValkeyModule_CallReplyVerbatim`](#ValkeyModule_CallReplyVerbatim) -* [`ValkeyModule_Calloc`](#ValkeyModule_Calloc) -* [`ValkeyModule_ChannelAtPosWithFlags`](#ValkeyModule_ChannelAtPosWithFlags) -* [`ValkeyModule_CloseKey`](#ValkeyModule_CloseKey) -* [`ValkeyModule_ClusterCanonicalKeyNameInSlot`](#ValkeyModule_ClusterCanonicalKeyNameInSlot) -* [`ValkeyModule_ClusterKeySlot`](#ValkeyModule_ClusterKeySlot) -* [`ValkeyModule_ClusterKeySlotC`](#ValkeyModule_ClusterKeySlotC) -* [`ValkeyModule_CommandFilterArgDelete`](#ValkeyModule_CommandFilterArgDelete) -* [`ValkeyModule_CommandFilterArgGet`](#ValkeyModule_CommandFilterArgGet) -* [`ValkeyModule_CommandFilterArgInsert`](#ValkeyModule_CommandFilterArgInsert) -* [`ValkeyModule_CommandFilterArgReplace`](#ValkeyModule_CommandFilterArgReplace) -* [`ValkeyModule_CommandFilterArgsCount`](#ValkeyModule_CommandFilterArgsCount) -* [`ValkeyModule_CommandFilterGetClientId`](#ValkeyModule_CommandFilterGetClientId) -* [`ValkeyModule_CreateCommand`](#ValkeyModule_CreateCommand) -* [`ValkeyModule_CreateDataType`](#ValkeyModule_CreateDataType) -* [`ValkeyModule_CreateDict`](#ValkeyModule_CreateDict) -* [`ValkeyModule_CreateModuleUser`](#ValkeyModule_CreateModuleUser) -* [`ValkeyModule_CreateString`](#ValkeyModule_CreateString) -* [`ValkeyModule_CreateStringFromCallReply`](#ValkeyModule_CreateStringFromCallReply) -* [`ValkeyModule_CreateStringFromDouble`](#ValkeyModule_CreateStringFromDouble) -* [`ValkeyModule_CreateStringFromLongDouble`](#ValkeyModule_CreateStringFromLongDouble) -* [`ValkeyModule_CreateStringFromLongLong`](#ValkeyModule_CreateStringFromLongLong) -* [`ValkeyModule_CreateStringFromStreamID`](#ValkeyModule_CreateStringFromStreamID) -* [`ValkeyModule_CreateStringFromString`](#ValkeyModule_CreateStringFromString) -* [`ValkeyModule_CreateStringFromULongLong`](#ValkeyModule_CreateStringFromULongLong) -* [`ValkeyModule_CreateStringPrintf`](#ValkeyModule_CreateStringPrintf) -* [`ValkeyModule_CreateSubcommand`](#ValkeyModule_CreateSubcommand) -* [`ValkeyModule_CreateTimer`](#ValkeyModule_CreateTimer) -* [`ValkeyModule_DbSize`](#ValkeyModule_DbSize) -* [`ValkeyModule_DeauthenticateAndCloseClient`](#ValkeyModule_DeauthenticateAndCloseClient) -* [`ValkeyModule_DecrExternalMemory`](#ValkeyModule_DecrExternalMemory) -* [`ValkeyModule_DefragAlloc`](#ValkeyModule_DefragAlloc) -* [`ValkeyModule_DefragCursorGet`](#ValkeyModule_DefragCursorGet) -* [`ValkeyModule_DefragCursorSet`](#ValkeyModule_DefragCursorSet) -* [`ValkeyModule_DefragShouldStop`](#ValkeyModule_DefragShouldStop) -* [`ValkeyModule_DefragValkeyModuleString`](#ValkeyModule_DefragValkeyModuleString) -* [`ValkeyModule_DeleteKey`](#ValkeyModule_DeleteKey) -* [`ValkeyModule_DictCompare`](#ValkeyModule_DictCompare) -* [`ValkeyModule_DictCompareC`](#ValkeyModule_DictCompareC) -* [`ValkeyModule_DictDel`](#ValkeyModule_DictDel) -* [`ValkeyModule_DictDelC`](#ValkeyModule_DictDelC) -* [`ValkeyModule_DictGet`](#ValkeyModule_DictGet) -* [`ValkeyModule_DictGetC`](#ValkeyModule_DictGetC) -* [`ValkeyModule_DictIteratorReseek`](#ValkeyModule_DictIteratorReseek) -* [`ValkeyModule_DictIteratorReseekC`](#ValkeyModule_DictIteratorReseekC) -* [`ValkeyModule_DictIteratorStart`](#ValkeyModule_DictIteratorStart) -* [`ValkeyModule_DictIteratorStartC`](#ValkeyModule_DictIteratorStartC) -* [`ValkeyModule_DictIteratorStop`](#ValkeyModule_DictIteratorStop) -* [`ValkeyModule_DictNext`](#ValkeyModule_DictNext) -* [`ValkeyModule_DictNextC`](#ValkeyModule_DictNextC) -* [`ValkeyModule_DictPrev`](#ValkeyModule_DictPrev) -* [`ValkeyModule_DictPrevC`](#ValkeyModule_DictPrevC) -* [`ValkeyModule_DictReplace`](#ValkeyModule_DictReplace) -* [`ValkeyModule_DictReplaceC`](#ValkeyModule_DictReplaceC) -* [`ValkeyModule_DictSet`](#ValkeyModule_DictSet) -* [`ValkeyModule_DictSetC`](#ValkeyModule_DictSetC) -* [`ValkeyModule_DictSize`](#ValkeyModule_DictSize) -* [`ValkeyModule_DigestAddLongLong`](#ValkeyModule_DigestAddLongLong) -* [`ValkeyModule_DigestAddStringBuffer`](#ValkeyModule_DigestAddStringBuffer) -* [`ValkeyModule_DigestEndSequence`](#ValkeyModule_DigestEndSequence) -* [`ValkeyModule_EmitAOF`](#ValkeyModule_EmitAOF) -* [`ValkeyModule_EventLoopAdd`](#ValkeyModule_EventLoopAdd) -* [`ValkeyModule_EventLoopAddOneShot`](#ValkeyModule_EventLoopAddOneShot) -* [`ValkeyModule_EventLoopDel`](#ValkeyModule_EventLoopDel) -* [`ValkeyModule_ExitFromChild`](#ValkeyModule_ExitFromChild) -* [`ValkeyModule_ExportSharedAPI`](#ValkeyModule_ExportSharedAPI) -* [`ValkeyModule_Fork`](#ValkeyModule_Fork) -* [`ValkeyModule_Free`](#ValkeyModule_Free) -* [`ValkeyModule_FreeCallReply`](#ValkeyModule_FreeCallReply) -* [`ValkeyModule_FreeClusterNodesList`](#ValkeyModule_FreeClusterNodesList) -* [`ValkeyModule_FreeDict`](#ValkeyModule_FreeDict) -* [`ValkeyModule_FreeModuleUser`](#ValkeyModule_FreeModuleUser) -* [`ValkeyModule_FreeServerInfo`](#ValkeyModule_FreeServerInfo) -* [`ValkeyModule_FreeString`](#ValkeyModule_FreeString) -* [`ValkeyModule_FreeThreadSafeContext`](#ValkeyModule_FreeThreadSafeContext) -* [`ValkeyModule_GetAbsExpire`](#ValkeyModule_GetAbsExpire) -* [`ValkeyModule_GetBlockedClientHandle`](#ValkeyModule_GetBlockedClientHandle) -* [`ValkeyModule_GetBlockedClientPrivateData`](#ValkeyModule_GetBlockedClientPrivateData) -* [`ValkeyModule_GetBlockedClientReadyKey`](#ValkeyModule_GetBlockedClientReadyKey) -* [`ValkeyModule_GetClientCertificate`](#ValkeyModule_GetClientCertificate) -* [`ValkeyModule_GetClientId`](#ValkeyModule_GetClientId) -* [`ValkeyModule_GetClientInfoById`](#ValkeyModule_GetClientInfoById) -* [`ValkeyModule_GetClientNameById`](#ValkeyModule_GetClientNameById) -* [`ValkeyModule_GetClientUserNameById`](#ValkeyModule_GetClientUserNameById) -* [`ValkeyModule_GetClusterNodeInfo`](#ValkeyModule_GetClusterNodeInfo) -* [`ValkeyModule_GetClusterNodeInfoForClient`](#ValkeyModule_GetClusterNodeInfoForClient) -* [`ValkeyModule_GetClusterNodesList`](#ValkeyModule_GetClusterNodesList) -* [`ValkeyModule_GetClusterSize`](#ValkeyModule_GetClusterSize) -* [`ValkeyModule_GetCommand`](#ValkeyModule_GetCommand) -* [`ValkeyModule_GetCommandKeys`](#ValkeyModule_GetCommandKeys) -* [`ValkeyModule_GetCommandKeysWithFlags`](#ValkeyModule_GetCommandKeysWithFlags) -* [`ValkeyModule_GetContextFlags`](#ValkeyModule_GetContextFlags) -* [`ValkeyModule_GetContextFlagsAll`](#ValkeyModule_GetContextFlagsAll) -* [`ValkeyModule_GetCurrentCommandName`](#ValkeyModule_GetCurrentCommandName) -* [`ValkeyModule_GetCurrentUserName`](#ValkeyModule_GetCurrentUserName) -* [`ValkeyModule_GetDbIdFromDefragCtx`](#ValkeyModule_GetDbIdFromDefragCtx) -* [`ValkeyModule_GetDbIdFromDigest`](#ValkeyModule_GetDbIdFromDigest) -* [`ValkeyModule_GetDbIdFromIO`](#ValkeyModule_GetDbIdFromIO) -* [`ValkeyModule_GetDbIdFromModuleKey`](#ValkeyModule_GetDbIdFromModuleKey) -* [`ValkeyModule_GetDbIdFromOptCtx`](#ValkeyModule_GetDbIdFromOptCtx) -* [`ValkeyModule_GetDetachedThreadSafeContext`](#ValkeyModule_GetDetachedThreadSafeContext) -* [`ValkeyModule_GetExpire`](#ValkeyModule_GetExpire) -* [`ValkeyModule_GetFunctionExecutionState`](#ValkeyModule_GetFunctionExecutionState) -* [`ValkeyModule_GetKeyNameFromDefragCtx`](#ValkeyModule_GetKeyNameFromDefragCtx) -* [`ValkeyModule_GetKeyNameFromDigest`](#ValkeyModule_GetKeyNameFromDigest) -* [`ValkeyModule_GetKeyNameFromIO`](#ValkeyModule_GetKeyNameFromIO) -* [`ValkeyModule_GetKeyNameFromModuleKey`](#ValkeyModule_GetKeyNameFromModuleKey) -* [`ValkeyModule_GetKeyNameFromOptCtx`](#ValkeyModule_GetKeyNameFromOptCtx) -* [`ValkeyModule_GetKeyspaceNotificationFlagsAll`](#ValkeyModule_GetKeyspaceNotificationFlagsAll) -* [`ValkeyModule_GetLFU`](#ValkeyModule_GetLFU) -* [`ValkeyModule_GetLRU`](#ValkeyModule_GetLRU) -* [`ValkeyModule_GetModuleOptionsAll`](#ValkeyModule_GetModuleOptionsAll) -* [`ValkeyModule_GetModuleUserACLString`](#ValkeyModule_GetModuleUserACLString) -* [`ValkeyModule_GetModuleUserFromUserName`](#ValkeyModule_GetModuleUserFromUserName) -* [`ValkeyModule_GetMyClusterID`](#ValkeyModule_GetMyClusterID) -* [`ValkeyModule_GetNotifyKeyspaceEvents`](#ValkeyModule_GetNotifyKeyspaceEvents) -* [`ValkeyModule_GetOpenKeyModesAll`](#ValkeyModule_GetOpenKeyModesAll) -* [`ValkeyModule_GetRandomBytes`](#ValkeyModule_GetRandomBytes) -* [`ValkeyModule_GetRandomHexChars`](#ValkeyModule_GetRandomHexChars) -* [`ValkeyModule_GetSelectedDb`](#ValkeyModule_GetSelectedDb) -* [`ValkeyModule_GetServerInfo`](#ValkeyModule_GetServerInfo) -* [`ValkeyModule_GetServerVersion`](#ValkeyModule_GetServerVersion) -* [`ValkeyModule_GetSharedAPI`](#ValkeyModule_GetSharedAPI) -* [`ValkeyModule_GetThreadSafeContext`](#ValkeyModule_GetThreadSafeContext) -* [`ValkeyModule_GetTimerInfo`](#ValkeyModule_GetTimerInfo) -* [`ValkeyModule_GetToDbIdFromOptCtx`](#ValkeyModule_GetToDbIdFromOptCtx) -* [`ValkeyModule_GetToKeyNameFromOptCtx`](#ValkeyModule_GetToKeyNameFromOptCtx) -* [`ValkeyModule_GetTypeMethodVersion`](#ValkeyModule_GetTypeMethodVersion) -* [`ValkeyModule_GetUsedMemoryRatio`](#ValkeyModule_GetUsedMemoryRatio) -* [`ValkeyModule_HashGet`](#ValkeyModule_HashGet) -* [`ValkeyModule_HashHasStringRef`](#ValkeyModule_HashHasStringRef) -* [`ValkeyModule_HashSet`](#ValkeyModule_HashSet) -* [`ValkeyModule_HashSetStringRef`](#ValkeyModule_HashSetStringRef) -* [`ValkeyModule_HoldString`](#ValkeyModule_HoldString) -* [`ValkeyModule_IncrExternalMemory`](#ValkeyModule_IncrExternalMemory) -* [`ValkeyModule_InfoAddFieldCString`](#ValkeyModule_InfoAddFieldCString) -* [`ValkeyModule_InfoAddFieldDouble`](#ValkeyModule_InfoAddFieldDouble) -* [`ValkeyModule_InfoAddFieldLongLong`](#ValkeyModule_InfoAddFieldLongLong) -* [`ValkeyModule_InfoAddFieldString`](#ValkeyModule_InfoAddFieldString) -* [`ValkeyModule_InfoAddFieldULongLong`](#ValkeyModule_InfoAddFieldULongLong) -* [`ValkeyModule_InfoAddSection`](#ValkeyModule_InfoAddSection) -* [`ValkeyModule_InfoBeginDictField`](#ValkeyModule_InfoBeginDictField) -* [`ValkeyModule_InfoEndDictField`](#ValkeyModule_InfoEndDictField) -* [`ValkeyModule_IsBlockedReplyRequest`](#ValkeyModule_IsBlockedReplyRequest) -* [`ValkeyModule_IsBlockedTimeoutRequest`](#ValkeyModule_IsBlockedTimeoutRequest) -* [`ValkeyModule_IsChannelsPositionRequest`](#ValkeyModule_IsChannelsPositionRequest) -* [`ValkeyModule_IsIOError`](#ValkeyModule_IsIOError) -* [`ValkeyModule_IsKeysPositionRequest`](#ValkeyModule_IsKeysPositionRequest) -* [`ValkeyModule_IsModuleNameBusy`](#ValkeyModule_IsModuleNameBusy) -* [`ValkeyModule_IsSubEventSupported`](#ValkeyModule_IsSubEventSupported) -* [`ValkeyModule_KeyAtPos`](#ValkeyModule_KeyAtPos) -* [`ValkeyModule_KeyAtPosWithFlags`](#ValkeyModule_KeyAtPosWithFlags) -* [`ValkeyModule_KeyExists`](#ValkeyModule_KeyExists) -* [`ValkeyModule_KeyType`](#ValkeyModule_KeyType) -* [`ValkeyModule_KillForkChild`](#ValkeyModule_KillForkChild) -* [`ValkeyModule_LatencyAddSample`](#ValkeyModule_LatencyAddSample) -* [`ValkeyModule_ListDelete`](#ValkeyModule_ListDelete) -* [`ValkeyModule_ListGet`](#ValkeyModule_ListGet) -* [`ValkeyModule_ListInsert`](#ValkeyModule_ListInsert) -* [`ValkeyModule_ListPop`](#ValkeyModule_ListPop) -* [`ValkeyModule_ListPush`](#ValkeyModule_ListPush) -* [`ValkeyModule_ListSet`](#ValkeyModule_ListSet) -* [`ValkeyModule_LoadConfigs`](#ValkeyModule_LoadConfigs) -* [`ValkeyModule_LoadDataTypeFromString`](#ValkeyModule_LoadDataTypeFromString) -* [`ValkeyModule_LoadDataTypeFromStringEncver`](#ValkeyModule_LoadDataTypeFromStringEncver) -* [`ValkeyModule_LoadDouble`](#ValkeyModule_LoadDouble) -* [`ValkeyModule_LoadFloat`](#ValkeyModule_LoadFloat) -* [`ValkeyModule_LoadLongDouble`](#ValkeyModule_LoadLongDouble) -* [`ValkeyModule_LoadSigned`](#ValkeyModule_LoadSigned) -* [`ValkeyModule_LoadString`](#ValkeyModule_LoadString) -* [`ValkeyModule_LoadStringBuffer`](#ValkeyModule_LoadStringBuffer) -* [`ValkeyModule_LoadUnsigned`](#ValkeyModule_LoadUnsigned) -* [`ValkeyModule_Log`](#ValkeyModule_Log) -* [`ValkeyModule_LogIOError`](#ValkeyModule_LogIOError) -* [`ValkeyModule_MallocSize`](#ValkeyModule_MallocSize) -* [`ValkeyModule_MallocSizeDict`](#ValkeyModule_MallocSizeDict) -* [`ValkeyModule_MallocSizeString`](#ValkeyModule_MallocSizeString) -* [`ValkeyModule_MallocUsableSize`](#ValkeyModule_MallocUsableSize) -* [`ValkeyModule_Microseconds`](#ValkeyModule_Microseconds) -* [`ValkeyModule_Milliseconds`](#ValkeyModule_Milliseconds) -* [`ValkeyModule_ModuleTypeGetType`](#ValkeyModule_ModuleTypeGetType) -* [`ValkeyModule_ModuleTypeGetValue`](#ValkeyModule_ModuleTypeGetValue) -* [`ValkeyModule_ModuleTypeReplaceValue`](#ValkeyModule_ModuleTypeReplaceValue) -* [`ValkeyModule_ModuleTypeSetValue`](#ValkeyModule_ModuleTypeSetValue) -* [`ValkeyModule_MonotonicMicroseconds`](#ValkeyModule_MonotonicMicroseconds) -* [`ValkeyModule_MustObeyClient`](#ValkeyModule_MustObeyClient) -* [`ValkeyModule_NotifyKeyspaceEvent`](#ValkeyModule_NotifyKeyspaceEvent) -* [`ValkeyModule_OpenKey`](#ValkeyModule_OpenKey) -* [`ValkeyModule_PoolAlloc`](#ValkeyModule_PoolAlloc) -* [`ValkeyModule_PublishMessage`](#ValkeyModule_PublishMessage) -* [`ValkeyModule_PublishMessageShard`](#ValkeyModule_PublishMessageShard) -* [`ValkeyModule_RandomKey`](#ValkeyModule_RandomKey) -* [`ValkeyModule_RdbLoad`](#ValkeyModule_RdbLoad) -* [`ValkeyModule_RdbSave`](#ValkeyModule_RdbSave) -* [`ValkeyModule_RdbStreamCreateFromFile`](#ValkeyModule_RdbStreamCreateFromFile) -* [`ValkeyModule_RdbStreamFree`](#ValkeyModule_RdbStreamFree) -* [`ValkeyModule_Realloc`](#ValkeyModule_Realloc) -* [`ValkeyModule_RedactClientCommandArgument`](#ValkeyModule_RedactClientCommandArgument) -* [`ValkeyModule_RegisterAuthCallback`](#ValkeyModule_RegisterAuthCallback) -* [`ValkeyModule_RegisterBoolConfig`](#ValkeyModule_RegisterBoolConfig) -* [`ValkeyModule_RegisterClusterMessageReceiver`](#ValkeyModule_RegisterClusterMessageReceiver) -* [`ValkeyModule_RegisterCommandFilter`](#ValkeyModule_RegisterCommandFilter) -* [`ValkeyModule_RegisterDefragFunc`](#ValkeyModule_RegisterDefragFunc) -* [`ValkeyModule_RegisterEnumConfig`](#ValkeyModule_RegisterEnumConfig) -* [`ValkeyModule_RegisterInfoFunc`](#ValkeyModule_RegisterInfoFunc) -* [`ValkeyModule_RegisterNumericConfig`](#ValkeyModule_RegisterNumericConfig) -* [`ValkeyModule_RegisterScriptingEngine`](#ValkeyModule_RegisterScriptingEngine) -* [`ValkeyModule_RegisterStringConfig`](#ValkeyModule_RegisterStringConfig) -* [`ValkeyModule_RegisterUnsignedNumericConfig`](#ValkeyModule_RegisterUnsignedNumericConfig) -* [`ValkeyModule_Replicate`](#ValkeyModule_Replicate) -* [`ValkeyModule_ReplicateVerbatim`](#ValkeyModule_ReplicateVerbatim) -* [`ValkeyModule_ReplySetArrayLength`](#ValkeyModule_ReplySetArrayLength) -* [`ValkeyModule_ReplySetAttributeLength`](#ValkeyModule_ReplySetAttributeLength) -* [`ValkeyModule_ReplySetMapLength`](#ValkeyModule_ReplySetMapLength) -* [`ValkeyModule_ReplySetSetLength`](#ValkeyModule_ReplySetSetLength) -* [`ValkeyModule_ReplyWithArray`](#ValkeyModule_ReplyWithArray) -* [`ValkeyModule_ReplyWithAttribute`](#ValkeyModule_ReplyWithAttribute) -* [`ValkeyModule_ReplyWithBigNumber`](#ValkeyModule_ReplyWithBigNumber) -* [`ValkeyModule_ReplyWithBool`](#ValkeyModule_ReplyWithBool) -* [`ValkeyModule_ReplyWithCString`](#ValkeyModule_ReplyWithCString) -* [`ValkeyModule_ReplyWithCallReply`](#ValkeyModule_ReplyWithCallReply) -* [`ValkeyModule_ReplyWithCustomErrorFormat`](#ValkeyModule_ReplyWithCustomErrorFormat) -* [`ValkeyModule_ReplyWithDouble`](#ValkeyModule_ReplyWithDouble) -* [`ValkeyModule_ReplyWithEmptyArray`](#ValkeyModule_ReplyWithEmptyArray) -* [`ValkeyModule_ReplyWithEmptyString`](#ValkeyModule_ReplyWithEmptyString) -* [`ValkeyModule_ReplyWithError`](#ValkeyModule_ReplyWithError) -* [`ValkeyModule_ReplyWithErrorFormat`](#ValkeyModule_ReplyWithErrorFormat) -* [`ValkeyModule_ReplyWithLongDouble`](#ValkeyModule_ReplyWithLongDouble) -* [`ValkeyModule_ReplyWithLongLong`](#ValkeyModule_ReplyWithLongLong) -* [`ValkeyModule_ReplyWithMap`](#ValkeyModule_ReplyWithMap) -* [`ValkeyModule_ReplyWithNull`](#ValkeyModule_ReplyWithNull) -* [`ValkeyModule_ReplyWithNullArray`](#ValkeyModule_ReplyWithNullArray) -* [`ValkeyModule_ReplyWithSet`](#ValkeyModule_ReplyWithSet) -* [`ValkeyModule_ReplyWithSimpleString`](#ValkeyModule_ReplyWithSimpleString) -* [`ValkeyModule_ReplyWithString`](#ValkeyModule_ReplyWithString) -* [`ValkeyModule_ReplyWithStringBuffer`](#ValkeyModule_ReplyWithStringBuffer) -* [`ValkeyModule_ReplyWithVerbatimString`](#ValkeyModule_ReplyWithVerbatimString) -* [`ValkeyModule_ReplyWithVerbatimStringType`](#ValkeyModule_ReplyWithVerbatimStringType) -* [`ValkeyModule_ResetDataset`](#ValkeyModule_ResetDataset) -* [`ValkeyModule_RetainString`](#ValkeyModule_RetainString) -* [`ValkeyModule_SaveDataTypeToString`](#ValkeyModule_SaveDataTypeToString) -* [`ValkeyModule_SaveDouble`](#ValkeyModule_SaveDouble) -* [`ValkeyModule_SaveFloat`](#ValkeyModule_SaveFloat) -* [`ValkeyModule_SaveLongDouble`](#ValkeyModule_SaveLongDouble) -* [`ValkeyModule_SaveSigned`](#ValkeyModule_SaveSigned) -* [`ValkeyModule_SaveString`](#ValkeyModule_SaveString) -* [`ValkeyModule_SaveStringBuffer`](#ValkeyModule_SaveStringBuffer) -* [`ValkeyModule_SaveUnsigned`](#ValkeyModule_SaveUnsigned) -* [`ValkeyModule_Scan`](#ValkeyModule_Scan) -* [`ValkeyModule_ScanCursorCreate`](#ValkeyModule_ScanCursorCreate) -* [`ValkeyModule_ScanCursorDestroy`](#ValkeyModule_ScanCursorDestroy) -* [`ValkeyModule_ScanCursorRestart`](#ValkeyModule_ScanCursorRestart) -* [`ValkeyModule_ScanKey`](#ValkeyModule_ScanKey) -* [`ValkeyModule_ScanKeyRawBorrowed`](#ValkeyModule_ScanKeyRawBorrowed) -* [`ValkeyModule_ScriptingEngineDebuggerFlushLogs`](#ValkeyModule_ScriptingEngineDebuggerFlushLogs) -* [`ValkeyModule_ScriptingEngineDebuggerLog`](#ValkeyModule_ScriptingEngineDebuggerLog) -* [`ValkeyModule_ScriptingEngineDebuggerLogRespReply`](#ValkeyModule_ScriptingEngineDebuggerLogRespReply) -* [`ValkeyModule_ScriptingEngineDebuggerLogRespReplyStr`](#ValkeyModule_ScriptingEngineDebuggerLogRespReplyStr) -* [`ValkeyModule_ScriptingEngineDebuggerProcessCommands`](#ValkeyModule_ScriptingEngineDebuggerProcessCommands) -* [`ValkeyModule_SelectDb`](#ValkeyModule_SelectDb) -* [`ValkeyModule_SendChildHeartbeat`](#ValkeyModule_SendChildHeartbeat) -* [`ValkeyModule_SendClusterMessage`](#ValkeyModule_SendClusterMessage) -* [`ValkeyModule_ServerInfoGetField`](#ValkeyModule_ServerInfoGetField) -* [`ValkeyModule_ServerInfoGetFieldC`](#ValkeyModule_ServerInfoGetFieldC) -* [`ValkeyModule_ServerInfoGetFieldDouble`](#ValkeyModule_ServerInfoGetFieldDouble) -* [`ValkeyModule_ServerInfoGetFieldSigned`](#ValkeyModule_ServerInfoGetFieldSigned) -* [`ValkeyModule_ServerInfoGetFieldUnsigned`](#ValkeyModule_ServerInfoGetFieldUnsigned) -* [`ValkeyModule_SetAbsExpire`](#ValkeyModule_SetAbsExpire) -* [`ValkeyModule_SetClientNameById`](#ValkeyModule_SetClientNameById) -* [`ValkeyModule_SetClusterFlags`](#ValkeyModule_SetClusterFlags) -* [`ValkeyModule_SetCommandACLCategories`](#ValkeyModule_SetCommandACLCategories) -* [`ValkeyModule_SetCommandInfo`](#ValkeyModule_SetCommandInfo) -* [`ValkeyModule_SetContextUser`](#ValkeyModule_SetContextUser) -* [`ValkeyModule_SetDisconnectCallback`](#ValkeyModule_SetDisconnectCallback) -* [`ValkeyModule_SetExpire`](#ValkeyModule_SetExpire) -* [`ValkeyModule_SetLFU`](#ValkeyModule_SetLFU) -* [`ValkeyModule_SetLRU`](#ValkeyModule_SetLRU) -* [`ValkeyModule_SetModuleOptions`](#ValkeyModule_SetModuleOptions) -* [`ValkeyModule_SetModuleUserACL`](#ValkeyModule_SetModuleUserACL) -* [`ValkeyModule_SetModuleUserACLString`](#ValkeyModule_SetModuleUserACLString) -* [`ValkeyModule_SignalKeyAsReady`](#ValkeyModule_SignalKeyAsReady) -* [`ValkeyModule_SignalModifiedKey`](#ValkeyModule_SignalModifiedKey) -* [`ValkeyModule_StopTimer`](#ValkeyModule_StopTimer) -* [`ValkeyModule_Strdup`](#ValkeyModule_Strdup) -* [`ValkeyModule_StreamAdd`](#ValkeyModule_StreamAdd) -* [`ValkeyModule_StreamDelete`](#ValkeyModule_StreamDelete) -* [`ValkeyModule_StreamIteratorDelete`](#ValkeyModule_StreamIteratorDelete) -* [`ValkeyModule_StreamIteratorNextField`](#ValkeyModule_StreamIteratorNextField) -* [`ValkeyModule_StreamIteratorNextID`](#ValkeyModule_StreamIteratorNextID) -* [`ValkeyModule_StreamIteratorStart`](#ValkeyModule_StreamIteratorStart) -* [`ValkeyModule_StreamIteratorStop`](#ValkeyModule_StreamIteratorStop) -* [`ValkeyModule_StreamTrimByID`](#ValkeyModule_StreamTrimByID) -* [`ValkeyModule_StreamTrimByLength`](#ValkeyModule_StreamTrimByLength) -* [`ValkeyModule_StringAppendBuffer`](#ValkeyModule_StringAppendBuffer) -* [`ValkeyModule_StringCompare`](#ValkeyModule_StringCompare) -* [`ValkeyModule_StringDMA`](#ValkeyModule_StringDMA) -* [`ValkeyModule_StringPtrLen`](#ValkeyModule_StringPtrLen) -* [`ValkeyModule_StringSet`](#ValkeyModule_StringSet) -* [`ValkeyModule_StringToDouble`](#ValkeyModule_StringToDouble) -* [`ValkeyModule_StringToLongDouble`](#ValkeyModule_StringToLongDouble) -* [`ValkeyModule_StringToLongLong`](#ValkeyModule_StringToLongLong) -* [`ValkeyModule_StringToStreamID`](#ValkeyModule_StringToStreamID) -* [`ValkeyModule_StringToULongLong`](#ValkeyModule_StringToULongLong) -* [`ValkeyModule_StringTruncate`](#ValkeyModule_StringTruncate) -* [`ValkeyModule_SubscribeToKeyspaceEvents`](#ValkeyModule_SubscribeToKeyspaceEvents) -* [`ValkeyModule_SubscribeToServerEvent`](#ValkeyModule_SubscribeToServerEvent) -* [`ValkeyModule_ThreadSafeContextLock`](#ValkeyModule_ThreadSafeContextLock) -* [`ValkeyModule_ThreadSafeContextTryLock`](#ValkeyModule_ThreadSafeContextTryLock) -* [`ValkeyModule_ThreadSafeContextUnlock`](#ValkeyModule_ThreadSafeContextUnlock) -* [`ValkeyModule_TrimStringAllocation`](#ValkeyModule_TrimStringAllocation) -* [`ValkeyModule_TryAlloc`](#ValkeyModule_TryAlloc) -* [`ValkeyModule_TryCalloc`](#ValkeyModule_TryCalloc) -* [`ValkeyModule_TryRealloc`](#ValkeyModule_TryRealloc) -* [`ValkeyModule_UnblockClient`](#ValkeyModule_UnblockClient) -* [`ValkeyModule_UnlinkKey`](#ValkeyModule_UnlinkKey) -* [`ValkeyModule_UnregisterCommandFilter`](#ValkeyModule_UnregisterCommandFilter) -* [`ValkeyModule_UnregisterScriptingEngine`](#ValkeyModule_UnregisterScriptingEngine) -* [`ValkeyModule_UpdateRuntimeArgs`](#ValkeyModule_UpdateRuntimeArgs) -* [`ValkeyModule_ValueLength`](#ValkeyModule_ValueLength) -* [`ValkeyModule_WrongArity`](#ValkeyModule_WrongArity) -* [`ValkeyModule_Yield`](#ValkeyModule_Yield) -* [`ValkeyModule_ZsetAdd`](#ValkeyModule_ZsetAdd) -* [`ValkeyModule_ZsetFirstInLexRange`](#ValkeyModule_ZsetFirstInLexRange) -* [`ValkeyModule_ZsetFirstInScoreRange`](#ValkeyModule_ZsetFirstInScoreRange) -* [`ValkeyModule_ZsetIncrby`](#ValkeyModule_ZsetIncrby) -* [`ValkeyModule_ZsetLastInLexRange`](#ValkeyModule_ZsetLastInLexRange) -* [`ValkeyModule_ZsetLastInScoreRange`](#ValkeyModule_ZsetLastInScoreRange) -* [`ValkeyModule_ZsetRangeCurrentElement`](#ValkeyModule_ZsetRangeCurrentElement) -* [`ValkeyModule_ZsetRangeEndReached`](#ValkeyModule_ZsetRangeEndReached) -* [`ValkeyModule_ZsetRangeNext`](#ValkeyModule_ZsetRangeNext) -* [`ValkeyModule_ZsetRangePrev`](#ValkeyModule_ZsetRangePrev) -* [`ValkeyModule_ZsetRangeStop`](#ValkeyModule_ZsetRangeStop) -* [`ValkeyModule_ZsetRem`](#ValkeyModule_ZsetRem) -* [`ValkeyModule_ZsetScore`](#ValkeyModule_ZsetScore) -* [`ValkeyModule__Assert`](#ValkeyModule__Assert) - diff --git a/topics/modules-blocking-ops.md b/topics/modules-blocking-ops.md deleted file mode 100644 index 3e276273..00000000 --- a/topics/modules-blocking-ops.md +++ /dev/null @@ -1,294 +0,0 @@ ---- -title: "Modules and blocking commands" -description: > - How to implement blocking commands in a Valkey module ---- - -Valkey has a few blocking commands among the built-in set of commands. -One of the most used is `BLPOP` (or the symmetric `BRPOP`) which blocks -waiting for elements arriving in a list. - -The interesting fact about blocking commands is that they do not block -the whole server, but just the client calling them. Usually the reason to -block is that we expect some external event to happen: this can be -some change in the Valkey data structures like in the `BLPOP` case, a -long computation happening in a thread, to receive some data from the -network, and so forth. - -Valkey modules have the ability to implement blocking commands as well, -this documentation shows how the API works and describes a few patterns -that can be used in order to model blocking commands. - - -How blocking and resuming works. ---- - -**Note:** You may want to check the `helloblock.c` example in the Valkey source tree -inside the `src/modules` directory, for a simple to understand example -on how the blocking API is applied. - -In Valkey modules, commands are implemented by callback functions that -are invoked by the Valkey core when the specific command is called -by the user. Normally the callback terminates its execution sending -some reply to the client. Using the following function instead, the -function implementing the module command may request that the client -is put into the blocked state: - -```C -ValkeyModuleBlockedClient *ValkeyModule_BlockClient(ValkeyModuleCtx *ctx, - ValkeyModuleCmdFunc reply_callback, - ValkeyModuleCmdFunc timeout_callback, - void (*free_privdata)(void*), - long long timeout_ms); -``` - -The function returns a `ValkeyModuleBlockedClient` object, which is later -used in order to unblock the client. The arguments have the following -meaning: - -* `ctx` is the command execution context as usually in the rest of the API. -* `reply_callback` is the callback, having the same prototype of a normal command function, that is called when the client is unblocked in order to return a reply to the client. -* `timeout_callback` is the callback, having the same prototype of a normal command function that is called when the client reached the `ms` timeout. -* `free_privdata` is the callback that is called in order to free the private data. Private data is a pointer to some data that is passed between the API used to unblock the client, to the callback that will send the reply to the client. We'll see how this mechanism works later in this document. -* `ms` is the timeout in milliseconds. When the timeout is reached, the timeout callback is called and the client is automatically aborted. - -Once a client is blocked, it can be unblocked with the following API: - -```C -int ValkeyModule_UnblockClient(ValkeyModuleBlockedClient *bc, void *privdata); -``` - -The function takes as argument the blocked client object returned by -the previous call to `ValkeyModule_BlockClient()`, and unblock the client. -Immediately before the client gets unblocked, the `reply_callback` function -specified when the client was blocked is called: this function will -have access to the `privdata` pointer used here. - -IMPORTANT: The above function is thread safe, and can be called from within -a thread doing some work in order to implement the command that blocked -the client. - -The `privdata` data will be freed automatically using the `free_privdata` -callback when the client is unblocked. This is useful **since the reply -callback may never be called** in case the client timeouts or disconnects -from the server, so it's important that it's up to an external function -to have the responsibility to free the data passed if needed. - -To better understand how the API works, we can imagine writing a command -that blocks a client for one second, and then send as reply "Hello!". - -Note: arity checks and other non important things are not implemented -int his command, in order to take the example simple. - -```C -int Example_ValkeyCommand(ValkeyModuleCtx *ctx, ValkeyModuleString **argv, - int argc) -{ - ValkeyModuleBlockedClient *bc = - ValkeyModule_BlockClient(ctx,reply_func,timeout_func,NULL,0); - - pthread_t tid; - pthread_create(&tid,NULL,threadmain,bc); - - return VALKEYMODULE_OK; -} - -void *threadmain(void *arg) { - ValkeyModuleBlockedClient *bc = arg; - - sleep(1); /* Wait one second and unblock. */ - ValkeyModule_UnblockClient(bc,NULL); -} -``` - -The above command blocks the client ASAP, spawning a thread that will -wait a second and will unblock the client. Let's check the reply and -timeout callbacks, which are in our case very similar, since they -just reply the client with a different reply type. - -```C -int reply_func(ValkeyModuleCtx *ctx, ValkeyModuleString **argv, - int argc) -{ - return ValkeyModule_ReplyWithSimpleString(ctx,"Hello!"); -} - -int timeout_func(ValkeyModuleCtx *ctx, ValkeyModuleString **argv, - int argc) -{ - return ValkeyModule_ReplyWithNull(ctx); -} -``` - -The reply callback just sends the "Hello!" string to the client. -The important bit here is that the reply callback is called when the -client is unblocked from the thread. - -The timeout command returns `NULL`, as it often happens with actual -Valkey blocking commands timing out. - -Passing reply data when unblocking ---- - -The above example is simple to understand but lacks an important -real world aspect of an actual blocking command implementation: often -the reply function will need to know what to reply to the client, -and this information is often provided as the client is unblocked. - -We could modify the above example so that the thread generates a -random number after waiting one second. You can think at it as an -actually expansive operation of some kind. Then this random number -can be passed to the reply function so that we return it to the command -caller. In order to make this working, we modify the functions as follow: - -```C -void *threadmain(void *arg) { - ValkeyModuleBlockedClient *bc = arg; - - sleep(1); /* Wait one second and unblock. */ - - long *mynumber = ValkeyModule_Alloc(sizeof(long)); - *mynumber = rand(); - ValkeyModule_UnblockClient(bc,mynumber); -} -``` - -As you can see, now the unblocking call is passing some private data, -that is the `mynumber` pointer, to the reply callback. In order to -obtain this private data, the reply callback will use the following -function: - -```C -void *ValkeyModule_GetBlockedClientPrivateData(ValkeyModuleCtx *ctx); -``` - -So our reply callback is modified like that: - -```C -int reply_func(ValkeyModuleCtx *ctx, ValkeyModuleString **argv, - int argc) -{ - long *mynumber = ValkeyModule_GetBlockedClientPrivateData(ctx); - /* IMPORTANT: don't free mynumber here, but in the - * free privdata callback. */ - return ValkeyModule_ReplyWithLongLong(ctx,mynumber); -} -``` - -Note that we also need to pass a `free_privdata` function when blocking -the client with `ValkeyModule_BlockClient()`, since the allocated -long value must be freed. Our callback will look like the following: - -```C -void free_privdata(void *privdata) { - ValkeyModule_Free(privdata); -} -``` - -NOTE: It is important to stress that the private data is best freed in the -`free_privdata` callback because the reply function may not be called -if the client disconnects or timeout. - -Also note that the private data is also accessible from the timeout -callback, always using the `GetBlockedClientPrivateData()` API. - -Aborting the blocking of a client ---- - -One problem that sometimes arises is that we need to allocate resources -in order to implement the non blocking command. So we block the client, -then, for example, try to create a thread, but the thread creation function -returns an error. What to do in such a condition in order to recover? We -don't want to take the client blocked, nor we want to call `UnblockClient()` -because this will trigger the reply callback to be called. - -In this case the best thing to do is to use the following function: - -```C -int ValkeyModule_AbortBlock(ValkeyModuleBlockedClient *bc); -``` - -Practically this is how to use it: - -```C -int Example_ValkeyCommand(ValkeyModuleCtx *ctx, ValkeyModuleString **argv, - int argc) -{ - ValkeyModuleBlockedClient *bc = - ValkeyModule_BlockClient(ctx,reply_func,timeout_func,NULL,0); - - pthread_t tid; - if (pthread_create(&tid,NULL,threadmain,bc) != 0) { - ValkeyModule_AbortBlock(bc); - ValkeyModule_ReplyWithError(ctx,"Sorry can't create a thread"); - } - - return VALKEYMODULE_OK; -} -``` - -The client will be unblocked but the reply callback will not be called. - -Implementing the command, reply and timeout callback using a single function ---- - -The following functions can be used in order to implement the reply and -callback with the same function that implements the primary command -function: - -```C -int ValkeyModule_IsBlockedReplyRequest(ValkeyModuleCtx *ctx); -int ValkeyModule_IsBlockedTimeoutRequest(ValkeyModuleCtx *ctx); -``` - -So I could rewrite the example command without using a separated -reply and timeout callback: - -```C -int Example_ValkeyCommand(ValkeyModuleCtx *ctx, ValkeyModuleString **argv, - int argc) -{ - if (ValkeyModule_IsBlockedReplyRequest(ctx)) { - long *mynumber = ValkeyModule_GetBlockedClientPrivateData(ctx); - return ValkeyModule_ReplyWithLongLong(ctx,mynumber); - } else if (ValkeyModule_IsBlockedTimeoutRequest) { - return ValkeyModule_ReplyWithNull(ctx); - } - - ValkeyModuleBlockedClient *bc = - ValkeyModule_BlockClient(ctx,reply_func,timeout_func,NULL,0); - - pthread_t tid; - if (pthread_create(&tid,NULL,threadmain,bc) != 0) { - ValkeyModule_AbortBlock(bc); - ValkeyModule_ReplyWithError(ctx,"Sorry can't create a thread"); - } - - return VALKEYMODULE_OK; -} -``` - -Functionally is the same but there are people that will prefer the less -verbose implementation that concentrates most of the command logic in a -single function. - -Working on copies of data inside a thread ---- - -An interesting pattern in order to work with threads implementing the -slow part of a command, is to work with a copy of the data, so that -while some operation is performed in a key, the user continues to see -the old version. However when the thread terminated its work, the -representations are swapped and the new, processed version, is used. - -An example of this approach is the -[Neural Redis module](https://github.com/antirez/neural-redis) -where neural networks are trained in different threads while the -user can still execute and inspect their older versions. - -Thread safe contexts ---- - -See [Thread Safe Contexts](modules-api-ref.md#section-thread-safe-contexts) in -the Modules API reference for how Valkey modules APIs can be called in a safe -way from threads. diff --git a/topics/modules-intro.md b/topics/modules-intro.md deleted file mode 100644 index 94b427db..00000000 --- a/topics/modules-intro.md +++ /dev/null @@ -1,975 +0,0 @@ ---- -title: "Modules Introduction" -description: > - Introduction to writing Valkey modules ---- - -The modules documentation is composed of the following pages: - -* Introduction to Valkey modules (this file). An overview about Valkey Modules system and API. It's a good idea to start your reading here. -* [Implementing native data types](modules-native-types.md) covers the implementation of native data types into modules. -* [Blocking operations](modules-blocking-ops.md) shows how to write blocking commands that will not reply immediately, but will block the client, without blocking the Valkey server, and will provide a reply whenever will be possible. -* [Valkey modules API reference](modules-api-ref.md) is generated from module.c top comments of ValkeyModule functions. It is a good reference in order to understand how each function works. - -Valkey modules make it possible to extend Valkey functionality using external -modules, rapidly implementing new Valkey commands with features -similar to what can be done inside the core itself. - -Valkey modules are dynamic libraries that can be loaded into Valkey at -startup, or using the `MODULE LOAD` command. Valkey exports a C API, in the -form of a single C header file called `valkeymodule.h`. Modules are meant -to be written in C, however it will be possible to use C++ or other languages -that have C binding functionalities. - -Modules are designed in order to be loaded into different versions of Valkey, -so a given module does not need to be designed, or recompiled, in order to -run with a specific version of Valkey. For this reason, the module will -register to the Valkey core using a specific API version. The current API -version is "1". - -## Loading modules - -In order to test the module you are developing, you can load the module -using the following `valkey.conf` configuration directive: - - loadmodule /path/to/mymodule.so - -It is also possible to load a module at runtime using the following command: - - MODULE LOAD /path/to/mymodule.so - -In order to list all loaded modules, use: - - MODULE LIST - -Finally, you can unload (and later reload if you wish) a module using the -following command: - - MODULE UNLOAD mymodule - -Note that `mymodule` above is not the filename without the `.so` suffix, but -instead, the name the module used to register itself into the Valkey core. -The name can be obtained using `MODULE LIST`. However it is good practice -that the filename of the dynamic library is the same as the name the module -uses to register itself into the Valkey core. - -## The simplest module you can write - -In order to show the different parts of a module, here we'll show a very -simple module that implements a command that outputs a random number. - -```C -#include "valkeymodule.h" -#include - -int HelloworldRand_ValkeyCommand(ValkeyModuleCtx *ctx, ValkeyModuleString **argv, int argc) { - ValkeyModule_ReplyWithLongLong(ctx,rand()); - return VALKEYMODULE_OK; -} - -int ValkeyModule_OnLoad(ValkeyModuleCtx *ctx, ValkeyModuleString **argv, int argc) { - if (ValkeyModule_Init(ctx,"helloworld",1,VALKEYMODULE_APIVER_1) - == VALKEYMODULE_ERR) return VALKEYMODULE_ERR; - - if (ValkeyModule_CreateCommand(ctx,"helloworld.rand", - HelloworldRand_ValkeyCommand, "fast random", - 0, 0, 0) == VALKEYMODULE_ERR) - return VALKEYMODULE_ERR; - - return VALKEYMODULE_OK; -} -``` - -The example module has two functions. One implements a command called -HELLOWORLD.RAND. This function is specific of that module. However the -other function called `ValkeyModule_OnLoad()` must be present in each -Valkey module. It is the entry point for the module to be initialized, -register its commands, and potentially other private data structures -it uses. - -Note that it is a good idea for modules to call commands with the -name of the module followed by a dot, and finally the command name, -like in the case of `HELLOWORLD.RAND`. This way it is less likely to -have collisions. - -Note that if different modules have colliding commands, they'll not be -able to work in Valkey at the same time, since the function -`ValkeyModule_CreateCommand` will fail in one of the modules, so the module -loading will abort returning an error condition. - -## Module initialization - -The above example shows the usage of the function `ValkeyModule_Init()`. -It should be the first function called by the module `OnLoad` function. -The following is the function prototype: - -```C -int ValkeyModule_Init(ValkeyModuleCtx *ctx, const char *modulename, - int module_version, int api_version); -``` - -The `Init` function announces the Valkey core that the module has a given -name, its version (that is reported by `MODULE LIST`), and that is willing -to use a specific version of the API. - -If the API version is wrong, the name is already taken, or there are other -similar errors, the function will return `VALKEYMODULE_ERR`, and the module -`OnLoad` function should return ASAP with an error. - -Before the `Init` function is called, no other API function can be called, -otherwise the module will segfault and the Valkey instance will crash. - -The second function called, `ValkeyModule_CreateCommand`, is used in order -to register commands into the Valkey core. The following is the prototype: - -```C -int ValkeyModule_CreateCommand(ValkeyModuleCtx *ctx, const char *name, - ValkeyModuleCmdFunc cmdfunc, const char *strflags, - int firstkey, int lastkey, int keystep); -``` - -As you can see, most Valkey modules API calls all take as first argument -the `context` of the module, so that they have a reference to the module -calling it, to the command and client executing a given command, and so forth. - -To create a new command, the above function needs the context, the command's -name, a pointer to the function implementing the command, the command's flags -and the positions of key names in the command's arguments. - -The function that implements the command must have the following prototype: - -```C -int mycommand(ValkeyModuleCtx *ctx, ValkeyModuleString **argv, int argc); -``` - -The command function arguments are just the context, that will be passed -to all the other API calls, the command argument vector, and total number -of arguments, as passed by the user. - -As you can see, the arguments are provided as pointers to a specific data -type, the `ValkeyModuleString`. This is an opaque data type you have API -functions to access and use, direct access to its fields is never needed. - -Zooming into the example command implementation, we can find another call: - -```C -int ValkeyModule_ReplyWithLongLong(ValkeyModuleCtx *ctx, long long integer); -``` - -This function returns an integer to the client that invoked the command, -exactly like other Valkey commands do, like for example `INCR` or `SCARD`. - -## Module cleanup - -In most cases, there is no need for special cleanup. -When a module is unloaded, Valkey will automatically unregister commands and -unsubscribe from notifications. -However in the case where a module contains some persistent memory or -configuration, a module may include an optional `ValkeyModule_OnUnload` -function. -If a module provides this function, it will be invoked during the module unload -process. -The following is the function prototype: - -```C -int ValkeyModule_OnUnload(ValkeyModuleCtx *ctx); -``` - -The `OnUnload` function may prevent module unloading by returning -`VALKEYMODULE_ERR`. -Otherwise, `VALKEYMODULE_OK` should be returned. - -## Setup and dependencies of a Valkey module - -Valkey modules don't depend on Valkey or some other library, nor they -need to be compiled with a specific `valkeymodule.h` file. In order -to create a new module, just copy a recent version of `valkeymodule.h` -in your source tree, link all the libraries you want, and create -a dynamic library having the `ValkeyModule_OnLoad()` function symbol -exported. - -The module will be able to load into different versions of Valkey. - -A module can be designed to support both newer and older Redis OSS versions where certain API functions are not available in all versions. -If an API function is not implemented in the currently running Redis OSS version, the function pointer is set to NULL. -This allows the module to check if a function exists before using it: - -```C -if (ValkeyModule_SetCommandInfo != NULL) { - ValkeyModule_SetCommandInfo(cmd, &info); -} -``` - -In recent versions of `valkeymodule.h`, a convenience macro `RMAPI_FUNC_SUPPORTED(funcname)` is defined. -Using the macro or just comparing with NULL is a matter of personal preference. - -# Passing configuration parameters to Valkey modules - -When the module is loaded with the `MODULE LOAD` command, or using the -`loadmodule` directive in the `valkey.conf` file, the user is able to pass -configuration parameters to the module by adding arguments after the module -file name: - - loadmodule mymodule.so foo bar 1234 - -In the above example the strings `foo`, `bar` and `1234` will be passed -to the module `OnLoad()` function in the `argv` argument as an array -of ValkeyModuleString pointers. The number of arguments passed is into `argc`. - -The way you can access those strings will be explained in the rest of this -document. Normally the module will store the module configuration parameters -in some `static` global variable that can be accessed module wide, so that -the configuration can change the behavior of different commands. - -## Working with ValkeyModuleString objects - -The command argument vector `argv` passed to module commands, and the -return value of other module APIs functions, are of type `ValkeyModuleString`. - -Usually you directly pass module strings to other API calls, however sometimes -you may need to directly access the string object. - -There are a few functions in order to work with string objects: - -```C -const char *ValkeyModule_StringPtrLen(ValkeyModuleString *string, size_t *len); -``` - -The above function accesses a string by returning its pointer and setting its -length in `len`. -You should never write to a string object pointer, as you can see from the -`const` pointer qualifier. - -However, if you want, you can create new string objects using the following -API: - -```C -ValkeyModuleString *ValkeyModule_CreateString(ValkeyModuleCtx *ctx, const char *ptr, size_t len); -``` - -The string returned by the above command must be freed using a corresponding -call to `ValkeyModule_FreeString()`: - -```C -void ValkeyModule_FreeString(ValkeyModuleString *str); -``` - -However if you want to avoid having to free strings, the automatic memory -management, covered later in this document, can be a good alternative, by -doing it for you. - -Note that the strings provided via the argument vector `argv` never need -to be freed. You only need to free new strings you create, or new strings -returned by other APIs, where it is specified that the returned string must -be freed. - -## Creating strings from numbers or parsing strings as numbers - -Creating a new string from an integer is a very common operation, so there -is a function to do this: - -```C -ValkeyModuleString *mystr = ValkeyModule_CreateStringFromLongLong(ctx,10); -``` - -Similarly in order to parse a string as a number: - -```C -long long myval; -if (ValkeyModule_StringToLongLong(ctx,argv[1],&myval) == VALKEYMODULE_OK) { - /* Do something with 'myval' */ -} -``` - -## Accessing Valkey keys from modules - -Most Valkey modules, in order to be useful, have to interact with the Valkey -data space (this is not always true, for example an ID generator may -never touch Valkey keys). Valkey modules have two different APIs in order to -access the Valkey data space, one is a low level API that provides very -fast access and a set of functions to manipulate Valkey data structures. -The other API is more high level, and allows to call Valkey commands and -fetch the result, similarly to how Lua scripts access Valkey. - -The high level API is also useful in order to access Valkey functionalities -that are not available as APIs. - -In general modules developers should prefer the low level API, because commands -implemented using the low level API run at a speed comparable to the speed -of native Valkey commands. However there are definitely use cases for the -higher level API. For example often the bottleneck could be processing the -data and not accessing it. - -Also note that sometimes using the low level API is not harder compared to -the higher level one. - -## Calling Valkey commands - -The high level API to access Valkey is the sum of the `ValkeyModule_Call()` -function, together with the functions needed in order to access the -reply object returned by `Call()`. - -`ValkeyModule_Call` uses a special calling convention, with a format specifier -that is used to specify what kind of objects you are passing as arguments -to the function. - -Valkey commands are invoked just using a command name and a list of arguments. -However when calling commands, the arguments may originate from different -kind of strings: null-terminated C strings, ValkeyModuleString objects as -received from the `argv` parameter in the command implementation, binary -safe C buffers with a pointer and a length, and so forth. - -For example if I want to call `INCRBY` using a first argument (the key) -a string received in the argument vector `argv`, which is an array -of ValkeyModuleString object pointers, and a C string representing the -number "10" as second argument (the increment), I'll use the following -function call: - -```C -ValkeyModuleCallReply *reply; -reply = ValkeyModule_Call(ctx,"INCRBY","sc",argv[1],"10"); -``` - -The first argument is the context, and the second is always a null terminated -C string with the command name. The third argument is the format specifier -where each character corresponds to the type of the arguments that will follow. -In the above case `"sc"` means a ValkeyModuleString object, and a null -terminated C string. The other arguments are just the two arguments as -specified. In fact `argv[1]` is a ValkeyModuleString and `"10"` is a null -terminated C string. - -This is the full list of format specifiers: - -* **c** -- Null terminated C string pointer. -* **b** -- C buffer, two arguments needed: C string pointer and `size_t` length. -* **s** -- ValkeyModuleString as received in `argv` or by other Valkey module APIs returning a ValkeyModuleString object. -* **l** -- Long long integer. -* **v** -- Array of ValkeyModuleString objects. -* **!** -- This modifier just tells the function to replicate the command to replicas and AOF. It is ignored from the point of view of arguments parsing. -* **A** -- This modifier, when `!` is given, tells to suppress AOF propagation: the command will be propagated only to replicas. -* **R** -- This modifier, when `!` is given, tells to suppress replicas propagation: the command will be propagated only to the AOF if enabled. - -The function returns a `ValkeyModuleCallReply` object on success, on -error NULL is returned. - -NULL is returned when the command name is invalid, the format specifier uses -characters that are not recognized, or when the command is called with the -wrong number of arguments. In the above cases the `errno` var is set to `EINVAL`. NULL is also returned when, in an instance with Cluster enabled, the target -keys are about non local hash slots. In this case `errno` is set to `EPERM`. - -## Working with ValkeyModuleCallReply objects. - -`ValkeyModuleCall` returns reply objects that can be accessed using the -`ValkeyModule_CallReply*` family of functions. - -In order to obtain the type or reply (corresponding to one of the data types -supported by the Valkey protocol), the function `ValkeyModule_CallReplyType()` -is used: - -```C -reply = ValkeyModule_Call(ctx,"INCRBY","sc",argv[1],"10"); -if (ValkeyModule_CallReplyType(reply) == VALKEYMODULE_REPLY_INTEGER) { - long long myval = ValkeyModule_CallReplyInteger(reply); - /* Do something with myval. */ -} -``` - -Valid reply types are: - -* `VALKEYMODULE_REPLY_STRING` Bulk string or status replies. -* `VALKEYMODULE_REPLY_ERROR` Errors. -* `VALKEYMODULE_REPLY_INTEGER` Signed 64 bit integers. -* `VALKEYMODULE_REPLY_ARRAY` Array of replies. -* `VALKEYMODULE_REPLY_NULL` NULL reply. - -Strings, errors and arrays have an associated length. For strings and errors -the length corresponds to the length of the string. For arrays the length -is the number of elements. To obtain the reply length the following function -is used: - -```C -size_t reply_len = ValkeyModule_CallReplyLength(reply); -``` - -In order to obtain the value of an integer reply, the following function is used, as already shown in the example above: - -```C -long long reply_integer_val = ValkeyModule_CallReplyInteger(reply); -``` - -Called with a reply object of the wrong type, the above function always -returns `LLONG_MIN`. - -Sub elements of array replies are accessed this way: - -```C -ValkeyModuleCallReply *subreply; -subreply = ValkeyModule_CallReplyArrayElement(reply,idx); -``` - -The above function returns NULL if you try to access out of range elements. - -Strings and errors (which are like strings but with a different type) can -be accessed using in the following way, making sure to never write to -the resulting pointer (that is returned as a `const` pointer so that -misusing must be pretty explicit): - -```C -size_t len; -char *ptr = ValkeyModule_CallReplyStringPtr(reply,&len); -``` - -If the reply type is not a string or an error, NULL is returned. - -ValkeyCallReply objects are not the same as module string objects -(ValkeyModuleString types). However sometimes you may need to pass replies -of type string or integer, to API functions expecting a module string. - -When this is the case, you may want to evaluate if using the low level -API could be a simpler way to implement your command, or you can use -the following function in order to create a new string object from a -call reply of type string, error or integer: - -```C -ValkeyModuleString *mystr = ValkeyModule_CreateStringFromCallReply(myreply); -``` - -If the reply is not of the right type, NULL is returned. -The returned string object should be released with `ValkeyModule_FreeString()` -as usually, or by enabling automatic memory management (see corresponding -section). - -## Releasing call reply objects - -Reply objects must be freed using `ValkeyModule_FreeCallReply`. For arrays, -you need to free only the top level reply, not the nested replies. -Currently the module implementation provides a protection in order to avoid -crashing if you free a nested reply object for error, however this feature -is not guaranteed to be here forever, so should not be considered part -of the API. - -If you use automatic memory management (explained later in this document) -you don't need to free replies (but you still could if you wish to release -memory ASAP). - -## Returning values from Valkey commands - -Like normal Valkey commands, new commands implemented via modules must be -able to return values to the caller. The API exports a set of functions for -this goal, in order to return the usual types of the Valkey protocol, and -arrays of such types as elements. Also errors can be returned with any -error string and code (the error code is the initial uppercase letters in -the error message, like the "BUSY" string in the "BUSY the sever is busy" error -message). - -All the functions to send a reply to the client are called -`ValkeyModule_ReplyWith`. - -To return an error, use: - -```C -ValkeyModule_ReplyWithError(ValkeyModuleCtx *ctx, const char *err); -``` - -There is a predefined error string for key of wrong type errors: - - VALKEYMODULE_ERRORMSG_WRONGTYPE - -Example usage: - -```C -ValkeyModule_ReplyWithError(ctx,"ERR invalid arguments"); -``` - -We already saw how to reply with a `long long` in the examples above: - -```C -ValkeyModule_ReplyWithLongLong(ctx,12345); -``` - -To reply with a simple string, that can't contain binary values or newlines, -(so it's suitable to send small words, like "OK") we use: - -```C -ValkeyModule_ReplyWithSimpleString(ctx,"OK"); -``` - -It's possible to reply with "bulk strings" that are binary safe, using -two different functions: - -```C -int ValkeyModule_ReplyWithStringBuffer(ValkeyModuleCtx *ctx, const char *buf, size_t len); - -int ValkeyModule_ReplyWithString(ValkeyModuleCtx *ctx, ValkeyModuleString *str); -``` - -The first function gets a C pointer and length. The second a ValkeyModuleString -object. Use one or the other depending on the source type you have at hand. - -In order to reply with an array, you just need to use a function to emit the -array length, followed by as many calls to the above functions as the number -of elements of the array are: - -```C -ValkeyModule_ReplyWithArray(ctx,2); -ValkeyModule_ReplyWithStringBuffer(ctx,"age",3); -ValkeyModule_ReplyWithLongLong(ctx,22); -``` - -To return nested arrays is easy, your nested array element just uses another -call to `ValkeyModule_ReplyWithArray()` followed by the calls to emit the -sub array elements. - -## Returning arrays with dynamic length - -Sometimes it is not possible to know beforehand the number of items of -an array. As an example, think of a Valkey module implementing a FACTOR -command that given a number outputs the prime factors. Instead of -factorializing the number, storing the prime factors into an array, and -later produce the command reply, a better solution is to start an array -reply where the length is not known, and set it later. This is accomplished -with a special argument to `ValkeyModule_ReplyWithArray()`: - -```C -ValkeyModule_ReplyWithArray(ctx, VALKEYMODULE_POSTPONED_LEN); -``` - -The above call starts an array reply so we can use other `ReplyWith` calls -in order to produce the array items. Finally in order to set the length, -use the following call: - -```C -ValkeyModule_ReplySetArrayLength(ctx, number_of_items); -``` - -In the case of the FACTOR command, this translates to some code similar -to this: - -```C -ValkeyModule_ReplyWithArray(ctx, VALKEYMODULE_POSTPONED_LEN); -number_of_factors = 0; -while(still_factors) { - ValkeyModule_ReplyWithLongLong(ctx, some_factor); - number_of_factors++; -} -ValkeyModule_ReplySetArrayLength(ctx, number_of_factors); -``` - -Another common use case for this feature is iterating over the arrays of -some collection and only returning the ones passing some kind of filtering. - -It is possible to have multiple nested arrays with postponed reply. -Each call to `SetArray()` will set the length of the latest corresponding -call to `ReplyWithArray()`: - -```C -ValkeyModule_ReplyWithArray(ctx, VALKEYMODULE_POSTPONED_LEN); -// ... generate 100 elements ... -ValkeyModule_ReplyWithArray(ctx, VALKEYMODULE_POSTPONED_LEN); -// ... generate 10 elements ... -ValkeyModule_ReplySetArrayLength(ctx, 10); -ValkeyModule_ReplySetArrayLength(ctx, 100); -``` - -This creates a 100 items array having as last element a 10 items array. - -## Arity and type checks - -Often commands need to check that the number of arguments and type of the key -is correct. In order to report a wrong arity, there is a specific function -called `ValkeyModule_WrongArity()`. The usage is trivial: - -```C -if (argc != 2) return ValkeyModule_WrongArity(ctx); -``` - -Checking for the wrong type involves opening the key and checking the type: - -```C -ValkeyModuleKey *key = ValkeyModule_OpenKey(ctx,argv[1], - VALKEYMODULE_READ|VALKEYMODULE_WRITE); - -int keytype = ValkeyModule_KeyType(key); -if (keytype != VALKEYMODULE_KEYTYPE_STRING && - keytype != VALKEYMODULE_KEYTYPE_EMPTY) -{ - ValkeyModule_CloseKey(key); - return ValkeyModule_ReplyWithError(ctx,VALKEYMODULE_ERRORMSG_WRONGTYPE); -} -``` - -Note that you often want to proceed with a command both if the key -is of the expected type, or if it's empty. - -## Low level access to keys - -Low level access to keys allow to perform operations on value objects associated -to keys directly, with a speed similar to what Valkey uses internally to -implement the built-in commands. - -Once a key is opened, a key pointer is returned that will be used with all the -other low level API calls in order to perform operations on the key or its -associated value. - -Because the API is meant to be very fast, it cannot do too many run-time -checks, so the user must be aware of certain rules to follow: - -* Opening the same key multiple times where at least one instance is opened for writing, is undefined and may lead to crashes. -* While a key is open, it should only be accessed via the low level key API. For example opening a key, then calling DEL on the same key using the `ValkeyModule_Call()` API will result into a crash. However it is safe to open a key, perform some operation with the low level API, closing it, then using other APIs to manage the same key, and later opening it again to do some more work. - -In order to open a key the `ValkeyModule_OpenKey` function is used. It returns -a key pointer, that we'll use with all the next calls to access and modify -the value: - -```C -ValkeyModuleKey *key; -key = ValkeyModule_OpenKey(ctx,argv[1],VALKEYMODULE_READ); -``` - -The second argument is the key name, that must be a `ValkeyModuleString` object. -The third argument is the mode: `VALKEYMODULE_READ` or `VALKEYMODULE_WRITE`. -It is possible to use `|` to bitwise OR the two modes to open the key in -both modes. Currently a key opened for writing can also be accessed for reading -but this is to be considered an implementation detail. The right mode should -be used in sane modules. - -You can open non existing keys for writing, since the keys will be created -when an attempt to write to the key is performed. However when opening keys -just for reading, `ValkeyModule_OpenKey` will return NULL if the key does not -exist. - -Once you are done using a key, you can close it with: - -```C -ValkeyModule_CloseKey(key); -``` - -Note that if automatic memory management is enabled, you are not forced to -close keys. When the module function returns, Valkey will take care to close -all the keys which are still open. - -## Getting the key type - -In order to obtain the value of a key, use the `ValkeyModule_KeyType()` function: - -```C -int keytype = ValkeyModule_KeyType(key); -``` - -It returns one of the following values: - - VALKEYMODULE_KEYTYPE_EMPTY - VALKEYMODULE_KEYTYPE_STRING - VALKEYMODULE_KEYTYPE_LIST - VALKEYMODULE_KEYTYPE_HASH - VALKEYMODULE_KEYTYPE_SET - VALKEYMODULE_KEYTYPE_ZSET - -The above are just the usual Valkey key types, with the addition of an empty -type, that signals the key pointer is associated with an empty key that -does not yet exists. - -## Creating new keys - -To create a new key, open it for writing and then write to it using one -of the key writing functions. Example: - -```C -ValkeyModuleKey *key; -key = ValkeyModule_OpenKey(ctx,argv[1],VALKEYMODULE_WRITE); -if (ValkeyModule_KeyType(key) == VALKEYMODULE_KEYTYPE_EMPTY) { - ValkeyModule_StringSet(key,argv[2]); -} -``` - -## Deleting keys - -Just use: - -```C -ValkeyModule_DeleteKey(key); -``` - -The function returns `VALKEYMODULE_ERR` if the key is not open for writing. -Note that after a key gets deleted, it is setup in order to be targeted -by new key commands. For example `ValkeyModule_KeyType()` will return it is -an empty key, and writing to it will create a new key, possibly of another -type (depending on the API used). - -## Managing key expires (TTLs) - -To control key expires two functions are provided, that are able to set, -modify, get, and unset the time to live associated with a key. - -One function is used in order to query the current expire of an open key: - -```C -mstime_t ValkeyModule_GetExpire(ValkeyModuleKey *key); -``` - -The function returns the time to live of the key in milliseconds, or -`VALKEYMODULE_NO_EXPIRE` as a special value to signal the key has no associated -expire or does not exist at all (you can differentiate the two cases checking -if the key type is `VALKEYMODULE_KEYTYPE_EMPTY`). - -In order to change the expire of a key the following function is used instead: - -```C -int ValkeyModule_SetExpire(ValkeyModuleKey *key, mstime_t expire); -``` - -When called on a non existing key, `VALKEYMODULE_ERR` is returned, because -the function can only associate expires to existing open keys (non existing -open keys are only useful in order to create new values with data type -specific write operations). - -Again the `expire` time is specified in milliseconds. If the key has currently -no expire, a new expire is set. If the key already have an expire, it is -replaced with the new value. - -If the key has an expire, and the special value `VALKEYMODULE_NO_EXPIRE` is -used as a new expire, the expire is removed, similarly to the Valkey -`PERSIST` command. In case the key was already persistent, no operation is -performed. - -## Obtaining the length of values - -There is a single function in order to retrieve the length of the value -associated to an open key. The returned length is value-specific, and is -the string length for strings, and the number of elements for the aggregated -data types (how many elements there is in a list, set, sorted set, hash). - -```C -size_t len = ValkeyModule_ValueLength(key); -``` - -If the key does not exist, 0 is returned by the function: - -## String type API - -Setting a new string value, like the Valkey `SET` command does, is performed -using: - -```C -int ValkeyModule_StringSet(ValkeyModuleKey *key, ValkeyModuleString *str); -``` - -The function works exactly like the Valkey `SET` command itself, that is, if -there is a prior value (of any type) it will be deleted. - -Accessing existing string values is performed using DMA (direct memory -access) for speed. The API will return a pointer and a length, so that's -possible to access and, if needed, modify the string directly. - -```C -size_t len, j; -char *myptr = ValkeyModule_StringDMA(key,&len,VALKEYMODULE_WRITE); -for (j = 0; j < len; j++) myptr[j] = 'A'; -``` - -In the above example we write directly on the string. Note that if you want -to write, you must be sure to ask for `WRITE` mode. - -DMA pointers are only valid if no other operations are performed with the key -before using the pointer, after the DMA call. - -Sometimes when we want to manipulate strings directly, we need to change -their size as well. For this scope, the `ValkeyModule_StringTruncate` function -is used. Example: - -```C -ValkeyModule_StringTruncate(mykey,1024); -``` - -The function truncates, or enlarges the string as needed, padding it with -zero bytes if the previous length is smaller than the new length we request. -If the string does not exist since `key` is associated to an open empty key, -a string value is created and associated to the key. - -Note that every time `StringTruncate()` is called, we need to re-obtain -the DMA pointer again, since the old may be invalid. - -For a complete list of string type functions, see [Key API for String -type](modules-api-ref.md#section-key-api-for-string-type) in the Modules API -reference. - -## List type API - -It's possible to push and pop values from list values: - -```C -int ValkeyModule_ListPush(ValkeyModuleKey *key, int where, ValkeyModuleString *ele); -ValkeyModuleString *ValkeyModule_ListPop(ValkeyModuleKey *key, int where); -``` - -In both the APIs the `where` argument specifies if to push or pop from tail -or head, using the following macros: - - VALKEYMODULE_LIST_HEAD - VALKEYMODULE_LIST_TAIL - -Elements returned by `ValkeyModule_ListPop()` are like strings created with -`ValkeyModule_CreateString()`, they must be released with -`ValkeyModule_FreeString()` or by enabling automatic memory management. - -For a complete list of set type functions, see [Key API for List -type](modules-api-ref.md#section-key-api-for-list-type) in the Modules API -reference. - -## Set type API - -A direct API to set type keys is not yet implemented. -Use the `ValkeyModule_Call` API with set commands like SADD to access keys of type set. - -## Sorted set type API - -See the [Key API for Sorted Set -type](modules-api-ref.md#section-key-api-for-sorted-set-type) section in the -Modules API reference. - -## Hash type API - -See [Key API for Hash type](modules-api-ref.md#section-key-api-for-hash-type) in -the Modules API reference. - -## Replicating commands - -If you want to use module commands exactly like normal Valkey commands, in the -context of replicated Valkey instances, or using the AOF file for persistence, -it is important for module commands to handle their replication in a consistent -way. - -When using the higher level APIs to invoke commands, replication happens -automatically if you use the "!" modifier in the format string of -`ValkeyModule_Call()` as in the following example: - -```C -reply = ValkeyModule_Call(ctx,"INCRBY","!sc",argv[1],"10"); -``` - -As you can see the format specifier is `"!sc"`. The bang is not parsed as a -format specifier, but it internally flags the command as "must replicate". - -If you use the above programming style, there are no problems. -However sometimes things are more complex than that, and you use the low level -API. In this case, if there are no side effects in the command execution, and -it consistently always performs the same work, what is possible to do is to -replicate the command verbatim as the user executed it. To do that, you just -need to call the following function: - -```C -ValkeyModule_ReplicateVerbatim(ctx); -``` - -When you use the above API, you should not use any other replication function -since they are not guaranteed to mix well. - -However this is not the only option. It's also possible to exactly tell -Valkey what commands to replicate as the effect of the command execution, using -an API similar to `ValkeyModule_Call()` but that instead of calling the command -sends it to the AOF / replicas stream. Example: - -```C -ValkeyModule_Replicate(ctx,"INCRBY","cl","foo",my_increment); -``` - -It's possible to call `ValkeyModule_Replicate` multiple times, and each -will emit a command. All the sequence emitted is wrapped between a -`MULTI/EXEC` transaction, so that the AOF and replication effects are the -same as executing a single command. - -Note that `Call()` replication and `Replicate()` replication have a rule, -in case you want to mix both forms of replication (not necessarily a good -idea if there are simpler approaches). Commands replicated with `Call()` -are always the first emitted in the final `MULTI/EXEC` block, while all -the commands emitted with `Replicate()` will follow. - -## Automatic memory management - -Normally when writing programs in the C language, programmers need to manage -memory manually. This is why the Valkey modules API has functions to release -strings, close open keys, free replies, and so forth. - -However given that commands are executed in a contained environment and -with a set of strict APIs, Valkey is able to provide automatic memory management -to modules, at the cost of some performance (most of the time, a very low -cost). - -When automatic memory management is enabled: - -1. You don't need to close open keys. -2. You don't need to free replies. -3. You don't need to free ValkeyModuleString objects. - -However you can still do it, if you want. For example, automatic memory -management may be active, but inside a loop allocating a lot of strings, -you may still want to free strings no longer used. - -In order to enable automatic memory management, just call the following -function at the start of the command implementation: - -```C -ValkeyModule_AutoMemory(ctx); -``` - -Automatic memory management is usually the way to go, however experienced -C programmers may not use it in order to gain some speed and memory usage -benefit. - -## Allocating memory into modules - -Normal C programs use `malloc()` and `free()` in order to allocate and -release memory dynamically. While in Valkey modules the use of malloc is -not technically forbidden, it is a lot better to use the Valkey Modules -specific functions, that are exact replacements for `malloc`, `free`, -`realloc` and `strdup`. These functions are: - -```C -void *ValkeyModule_Alloc(size_t bytes); -void* ValkeyModule_Realloc(void *ptr, size_t bytes); -void ValkeyModule_Free(void *ptr); -void ValkeyModule_Calloc(size_t nmemb, size_t size); -char *ValkeyModule_Strdup(const char *str); -``` - -They work exactly like their `libc` equivalent calls, however they use -the same allocator Valkey uses, and the memory allocated using these -functions is reported by the `INFO` command in the memory section, is -accounted when enforcing the `maxmemory` policy, and in general is -a first citizen of the Valkey executable. On the contrary, the method -allocated inside modules with libc `malloc()` is transparent to Valkey. - -Another reason to use the modules functions in order to allocate memory -is that, when creating native data types inside modules, the RDB loading -functions can return deserialized strings (from the RDB file) directly -as `ValkeyModule_Alloc()` allocations, so they can be used directly to -populate data structures after loading, instead of having to copy them -to the data structure. - -## Pool allocator - -Sometimes in commands implementations, it is required to perform many -small allocations that will be not retained at the end of the command -execution, but are just functional to execute the command itself. - -This work can be more easily accomplished using the Valkey pool allocator: - -```C -void *ValkeyModule_PoolAlloc(ValkeyModuleCtx *ctx, size_t bytes); -``` - -It works similarly to `malloc()`, and returns memory aligned to the -next power of two of greater or equal to `bytes` (for a maximum alignment -of 8 bytes). However it allocates memory in blocks, so it the overhead -of the allocations is small, and more important, the memory allocated -is automatically released when the command returns. - -So in general short living allocations are a good candidates for the pool -allocator. - -## Writing commands compatible with Valkey Cluster - -See the Modules API reference for the following commands: - -* [`ValkeyModule_IsKeysPositionRequest(ctx)`](modules-api-ref.md#ValkeyModule_IsKeysPositionRequest) -* [`ValkeyModule_KeyAtPos(ctx, pos)`](modules-api-ref.md#ValkeyModule_KeyAtPos) diff --git a/topics/modules-native-types.md b/topics/modules-native-types.md deleted file mode 100644 index 9009d167..00000000 --- a/topics/modules-native-types.md +++ /dev/null @@ -1,407 +0,0 @@ ---- -title: "Modules API for native types" -description: > - How to use native types in a Valkey module ---- - -Valkey modules can access Valkey built-in data structures both at high level, -by calling Valkey commands, and at low level, by manipulating the data structures -directly. - -By using these capabilities in order to build new abstractions on top of existing -Valkey data structures, or by using strings DMA in order to encode modules -data structures into Strings, it is possible to create modules that -*feel like* they are exporting new data types. However, for more complex -problems, this is not enough, and the implementation of new data structures -inside the module is needed. - -We call the ability of Valkey modules to implement new data structures that -feel like native Valkey ones **native types support**. This document describes -the API exported by the Valkey modules system in order to create new data -structures and handle the serialization in RDB files, the rewriting process -in AOF, the type reporting via the `TYPE` command, and so forth. - -Overview of native types ---- - -A module exporting a native type is composed of the following main parts: - -* The implementation of some kind of new data structure and of commands operating on the new data structure. -* A set of callbacks that handle: RDB saving, RDB loading, AOF rewriting, releasing of a value associated with a key, calculation of a value digest (hash) to be used with the `DEBUG DIGEST` command. -* A 9 characters name that is unique to each module native data type. -* An encoding version, used to persist into RDB files a module-specific data version, so that a module will be able to load older representations from RDB files. - -While to handle RDB loading, saving and AOF rewriting may look complex as a first glance, the modules API provide very high level function for handling all this, without requiring the user to handle read/write errors, so in practical terms, writing a new data structure for Valkey is a simple task. - -A **very easy** to understand but complete example of native type implementation -is available inside the Valkey distribution in the `/modules/hellotype.c` file. -The reader is encouraged to read the documentation by looking at this example -implementation to see how things are applied in the practice. - -Registering a new data type -=== - -In order to register a new native type into the Valkey core, the module needs -to declare a global variable that will hold a reference to the data type. -The API to register the data type will return a data type reference that will -be stored in the global variable. - -```C -static ValkeyModuleType *MyType; -#define MYTYPE_ENCODING_VERSION 0 - -int ValkeyModule_OnLoad(ValkeyModuleCtx *ctx) { -ValkeyModuleTypeMethods tm = { - .version = VALKEYMODULE_TYPE_METHOD_VERSION, - .rdb_load = MyTypeRDBLoad, - .rdb_save = MyTypeRDBSave, - .aof_rewrite = MyTypeAOFRewrite, - .free = MyTypeFree -}; - - MyType = ValkeyModule_CreateDataType(ctx, "MyType-AZ", - MYTYPE_ENCODING_VERSION, &tm); - if (MyType == NULL) return VALKEYMODULE_ERR; -} -``` - -As you can see from the example above, a single API call is needed in order to -register the new type. However a number of function pointers are passed as -arguments. Certain are optionals while some are mandatory. The above set -of methods *must* be passed, while `.digest` and `.mem_usage` are optional -and are currently not actually supported by the modules internals, so for -now you can just ignore them. - -The `ctx` argument is the context that we receive in the `OnLoad` function. -The type `name` is a 9 character name in the character set that includes -from `A-Z`, `a-z`, `0-9`, plus the underscore `_` and minus `-` characters. - -Note that **this name must be unique** for each data type in the Valkey -ecosystem, so be creative, use both lower-case and upper case if it makes -sense, and try to use the convention of mixing the type name with the name -of the author of the module, to create a 9 character unique name. - -**NOTE:** It is very important that the name is exactly 9 chars or the -registration of the type will fail. Read more to understand why. - -For example if I'm building a *b-tree* data structure and my name is *antirez* -I'll call my type **btree1-az**. The name, converted to a 64 bit integer, -is stored inside the RDB file when saving the type, and will be used when the -RDB data is loaded in order to resolve what module can load the data. If Valkey -finds no matching module, the integer is converted back to a name in order to -provide some clue to the user about what module is missing in order to load -the data. - -The type name is also used as a reply for the `TYPE` command when called -with a key holding the registered type. - -The `encver` argument is the encoding version used by the module to store data -inside the RDB file. For example I can start with an encoding version of 0, -but later when I release version 2.0 of my module, I can switch encoding to -something better. The new module will register with an encoding version of 1, -so when it saves new RDB files, the new version will be stored on disk. However -when loading RDB files, the module `rdb_load` method will be called even if -there is data found for a different encoding version (and the encoding version -is passed as argument to `rdb_load`), so that the module can still load old -RDB files. - -The last argument is a structure used in order to pass the type methods to the -registration function: `rdb_load`, `rdb_save`, `aof_rewrite`, `digest` and -`free` and `mem_usage` are all callbacks with the following prototypes and uses: - -```C -typedef void *(*ValkeyModuleTypeLoadFunc)(ValkeyModuleIO *rdb, int encver); -typedef void (*ValkeyModuleTypeSaveFunc)(ValkeyModuleIO *rdb, void *value); -typedef void (*ValkeyModuleTypeRewriteFunc)(ValkeyModuleIO *aof, ValkeyModuleString *key, void *value); -typedef size_t (*ValkeyModuleTypeMemUsageFunc)(void *value); -typedef void (*ValkeyModuleTypeDigestFunc)(ValkeyModuleDigest *digest, void *value); -typedef void (*ValkeyModuleTypeFreeFunc)(void *value); -``` - -* `rdb_load` is called when loading data from the RDB file. It loads data in the same format as `rdb_save` produces. -* `rdb_save` is called when saving data to the RDB file. -* `aof_rewrite` is called when the AOF is being rewritten, and the module needs to tell Valkey what is the sequence of commands to recreate the content of a given key. -* `digest` is called when `DEBUG DIGEST` is executed and a key holding this module type is found. Currently this is not yet implemented so the function ca be left empty. -* `mem_usage` is called when the `MEMORY` command asks for the total memory consumed by a specific key, and is used in order to get the amount of bytes used by the module value. -* `free` is called when a key with the module native type is deleted via `DEL` or in any other mean, in order to let the module reclaim the memory associated with such a value. - -Ok, but *why* modules types require a 9 characters name? ---- - -Oh, I understand you need to understand this, so here is a very specific -explanation. - -When Valkey persists to RDB files, modules specific data types require to -be persisted as well. Now RDB files are sequences of key-value pairs -like the following: - - [1 byte type] [key] [a type specific value] - -The 1 byte type identifies strings, lists, sets, and so forth. In the case -of modules data, it is set to a special value of `module data`, but of -course this is not enough, we need the information needed to link a specific -value with a specific module type that is able to load and handle it. - -So when we save a `type specific value` about a module, we prefix it with -a 64 bit integer. 64 bits is large enough to store the information needed -in order to lookup the module that can handle that specific type, but is -short enough that we can prefix each module value we store inside the RDB -without making the final RDB file too big. At the same time, this solution -of prefixing the value with a 64 bit *signature* does not require to do -strange things like defining in the RDB header a list of modules specific -types. Everything is pretty simple. - -So, what you can store in 64 bits in order to identify a given module in -a reliable way? Well if you build a character set of 64 symbols, you can -easily store 9 characters of 6 bits, and you are left with 10 bits, that -are used in order to store the *encoding version* of the type, so that -the same type can evolve in the future and provide a different and more -efficient or updated serialization format for RDB files. - -So the 64 bit prefix stored before each module value is like the following: - - 6|6|6|6|6|6|6|6|6|10 - -The first 9 elements are 6-bits characters, the final 10 bits is the -encoding version. - -When the RDB file is loaded back, it reads the 64 bit value, masks the final -10 bits, and searches for a matching module in the modules types cache. -When a matching one is found, the method to load the RDB file value is called -with the 10 bits encoding version as argument, so that the module knows -what version of the data layout to load, if it can support multiple versions. - -Now the interesting thing about all this is that, if instead the module type -cannot be resolved, since there is no loaded module having this signature, -we can convert back the 64 bit value into a 9 characters name, and print -an error to the user that includes the module type name! So that she or he -immediately realizes what's wrong. - -Setting and getting keys ---- - -After registering our new data type in the `ValkeyModule_OnLoad()` function, -we also need to be able to set Valkey keys having as value our native type. - -This normally happens in the context of commands that write data to a key. -The native types API allow to set and get keys to module native data types, -and to test if a given key is already associated to a value of a specific data -type. - -The API uses the normal modules `ValkeyModule_OpenKey()` low level key access -interface in order to deal with this. This is an example of setting a -native type private data structure to a Valkey key: - -```C -ValkeyModuleKey *key = ValkeyModule_OpenKey(ctx,keyname,VALKEYMODULE_WRITE); -struct some_private_struct *data = createMyDataStructure(); -ValkeyModule_ModuleTypeSetValue(key,MyType,data); -``` - -The function `ValkeyModule_ModuleTypeSetValue()` is used with a key handle open -for writing, and gets three arguments: the key handle, the reference to the -native type, as obtained during the type registration, and finally a `void*` -pointer that contains the private data implementing the module native type. - -Note that Valkey has no clues at all about what your data contains. It will -just call the callbacks you provided during the method registration in order -to perform operations on the type. - -Similarly we can retrieve the private data from a key using this function: - -``` -struct some_private_struct *data; -data = ValkeyModule_ModuleTypeGetValue(key); -``` - -We can also test for a key to have our native type as value: - -```C -if (ValkeyModule_ModuleTypeGetType(key) == MyType) { - /* ... do something ... */ -} -``` - -However for the calls to do the right thing, we need to check if the key -is empty, if it contains a value of the right kind, and so forth. So -the idiomatic code to implement a command writing to our native type -is along these lines: - -```C -ValkeyModuleKey *key = ValkeyModule_OpenKey(ctx,argv[1], - VALKEYMODULE_READ|VALKEYMODULE_WRITE); -int type = ValkeyModule_KeyType(key); -if (type != VALKEYMODULE_KEYTYPE_EMPTY && - ValkeyModule_ModuleTypeGetType(key) != MyType) -{ - return ValkeyModule_ReplyWithError(ctx,VALKEYMODULE_ERRORMSG_WRONGTYPE); -} -``` - -Then if we successfully verified the key is not of the wrong type, and -we are going to write to it, we usually want to create a new data structure if -the key is empty, or retrieve the reference to the value associated to the -key if there is already one: - -```C -/* Create an empty value object if the key is currently empty. */ -struct some_private_struct *data; -if (type == VALKEYMODULE_KEYTYPE_EMPTY) { - data = createMyDataStructure(); - ValkeyModule_ModuleTypeSetValue(key,MyTyke,data); -} else { - data = ValkeyModule_ModuleTypeGetValue(key); -} -/* Do something with 'data'... */ -``` - -Free method ---- - -As already mentioned, when Valkey needs to free a key holding a native type -value, it needs help from the module in order to release the memory. This -is the reason why we pass a `free` callback during the type registration: - -```C -typedef void (*ValkeyModuleTypeFreeFunc)(void *value); -``` - -A trivial implementation of the free method can be something like this, -assuming our data structure is composed of a single allocation: - -```C -void MyTypeFreeCallback(void *value) { - ValkeyModule_Free(value); -} -``` - -However a more real world one will call some function that performs a more -complex memory reclaiming, by casting the void pointer to some structure -and freeing all the resources composing the value. - -RDB load and save methods ---- - -The RDB saving and loading callbacks need to create (and load back) a -representation of the data type on disk. Valkey offers a high level API -that can automatically store inside the RDB file the following types: - -* Unsigned 64 bit integers. -* Signed 64 bit integers. -* Doubles. -* Strings. - -It is up to the module to find a viable representation using the above base -types. However note that while the integer and double values are stored -and loaded in an architecture and *endianness* agnostic way, if you use -the raw string saving API to, for example, save a structure on disk, you -have to care those details yourself. - -This is the list of functions performing RDB saving and loading: - -```C -void ValkeyModule_SaveUnsigned(ValkeyModuleIO *io, uint64_t value); -uint64_t ValkeyModule_LoadUnsigned(ValkeyModuleIO *io); -void ValkeyModule_SaveSigned(ValkeyModuleIO *io, int64_t value); -int64_t ValkeyModule_LoadSigned(ValkeyModuleIO *io); -void ValkeyModule_SaveString(ValkeyModuleIO *io, ValkeyModuleString *s); -void ValkeyModule_SaveStringBuffer(ValkeyModuleIO *io, const char *str, size_t len); -ValkeyModuleString *ValkeyModule_LoadString(ValkeyModuleIO *io); -char *ValkeyModule_LoadStringBuffer(ValkeyModuleIO *io, size_t *lenptr); -void ValkeyModule_SaveDouble(ValkeyModuleIO *io, double value); -double ValkeyModule_LoadDouble(ValkeyModuleIO *io); -``` - -The functions don't require any error checking from the module, that can -always assume calls succeed. - -As an example, imagine I've a native type that implements an array of -double values, with the following structure: - -```C -struct double_array { - size_t count; - double *values; -}; -``` - -My `rdb_save` method may look like the following: - -```C -void DoubleArrayRDBSave(ValkeyModuleIO *io, void *ptr) { - struct dobule_array *da = ptr; - ValkeyModule_SaveUnsigned(io,da->count); - for (size_t j = 0; j < da->count; j++) - ValkeyModule_SaveDouble(io,da->values[j]); -} -``` - -What we did was to store the number of elements followed by each double -value. So when later we'll have to load the structure in the `rdb_load` -method we'll do something like this: - -```C -void *DoubleArrayRDBLoad(ValkeyModuleIO *io, int encver) { - if (encver != DOUBLE_ARRAY_ENC_VER) { - /* We should actually log an error here, or try to implement - the ability to load older versions of our data structure. */ - return NULL; - } - - struct double_array *da; - da = ValkeyModule_Alloc(sizeof(*da)); - da->count = ValkeyModule_LoadUnsigned(io); - da->values = ValkeyModule_Alloc(da->count * sizeof(double)); - for (size_t j = 0; j < da->count; j++) - da->values[j] = ValkeyModule_LoadDouble(io); - return da; -} -``` - -The load callback just reconstruct back the data structure from the data -we stored in the RDB file. - -Note that while there is no error handling on the API that writes and reads -from disk, still the load callback can return NULL on errors in case what -it reads does not look correct. Valkey will just panic in that case. - -AOF rewriting ---- - -```C -void ValkeyModule_EmitAOF(ValkeyModuleIO *io, const char *cmdname, const char *fmt, ...); -``` - -Allocating memory ---- - -Modules data types should try to use `ValkeyModule_Alloc()` functions family -in order to allocate, reallocate and release heap memory used to implement the native data structures (see the other Valkey Modules documentation for detailed information). - -This is not just useful in order for Valkey to be able to account for the memory used by the module, but there are also more advantages: - -* Valkey uses the `jemalloc` allocator, that often prevents fragmentation problems that could be caused by using the libc allocator. -* When loading strings from the RDB file, the native types API is able to return strings allocated directly with `ValkeyModule_Alloc()`, so that the module can directly link this memory into the data structure representation, avoiding a useless copy of the data. - -Even if you are using external libraries implementing your data structures, the -allocation functions provided by the module API is exactly compatible with -`malloc()`, `realloc()`, `free()` and `strdup()`, so converting the libraries -in order to use these functions should be trivial. - -In case you have an external library that uses libc `malloc()`, and you want -to avoid replacing manually all the calls with the Valkey Modules API calls, -an approach could be to use simple macros in order to replace the libc calls -with the Valkey API calls. Something like this could work: - -```C -#define malloc ValkeyModule_Alloc -#define realloc ValkeyModule_Realloc -#define free ValkeyModule_Free -#define strdup ValkeyModule_Strdup -``` - -However take in mind that mixing libc calls with Valkey API calls will result -into troubles and crashes, so if you replace calls using macros, you need to -make sure that all the calls are correctly replaced, and that the code with -the substituted calls will never, for example, attempt to call -`ValkeyModule_Free()` with a pointer allocated using libc `malloc()`. diff --git a/topics/notifications.md b/topics/notifications.md deleted file mode 100644 index 8dfd42bb..00000000 --- a/topics/notifications.md +++ /dev/null @@ -1,179 +0,0 @@ ---- -title: "Keyspace notifications" -description: > - Monitor changes to Valkey keys and values in real time ---- - -Keyspace notifications allow clients to subscribe to Pub/Sub channels in order -to receive events affecting the Valkey data set in some way. - -Examples of events that can be received are: - -* All the commands affecting a given key. -* All the keys receiving an LPUSH operation. -* All the keys expiring in the database 0. - -Note: Valkey Pub/Sub is *fire and forget* that is, if your Pub/Sub client disconnects, -and reconnects later, all the events delivered during the time the client was -disconnected are lost. - -### Type of events - -Keyspace notifications are implemented by sending two distinct types of events -for every operation affecting the Valkey data space. For instance a `DEL` -operation targeting the key named `mykey` in database `0` will trigger -the delivering of two messages, exactly equivalent to the following two -`PUBLISH` commands: - - PUBLISH __keyspace@0__:mykey del - PUBLISH __keyevent@0__:del mykey - -The first channel listens to all the events targeting -the key `mykey` and the other channel listens only to `del` operation -events on the key `mykey` - -The first kind of event, with `keyspace` prefix in the channel is called -a **Key-space notification**, while the second, with the `keyevent` prefix, -is called a **Key-event notification**. - -In the previous example a `del` event was generated for the key `mykey` resulting -in two messages: - -* The Key-space channel receives as message the name of the event. -* The Key-event channel receives as message the name of the key. - -It is possible to enable only one kind of notification in order to deliver -just the subset of events we are interested in. - -### Configuration - -By default keyspace event notifications are disabled because while not -very sensible the feature uses some CPU power. Notifications are enabled -using the `notify-keyspace-events` of valkey.conf or via the **CONFIG SET**. - -Setting the parameter to the empty string disables notifications. -In order to enable the feature a non-empty string is used, composed of multiple -characters, where every character has a special meaning according to the -following table: - - K Keyspace events, published with __keyspace@__ prefix. - E Keyevent events, published with __keyevent@__ prefix. - g Generic commands (non-type specific) like DEL, EXPIRE, RENAME, ... - $ String commands - l List commands - s Set commands - h Hash commands - z Sorted set commands - t Stream commands - d Module key type events - x Expired events (events generated every time a key expires) - e Evicted events (events generated when a key is evicted for maxmemory) - m Key miss events (events generated when a key that doesn't exist is accessed) - n New key events (Note: not included in the 'A' class) - A Alias for "g$lshztxed", so that the "AKE" string means all the events except "m" and "n". - -At least `K` or `E` should be present in the string, otherwise no event -will be delivered regardless of the rest of the string. - -For instance to enable just Key-space events for lists, the configuration -parameter must be set to `Kl`, and so forth. - -You can use the string `KEA` to enable most types of events. - -### Events generated by different commands - -Different commands generate different kind of events according to the following list. - -* `DEL` generates a `del` event for every deleted key. -* `RENAME` generates two events, a `rename_from` event for the source key, and a `rename_to` event for the destination key. -* `MOVE` generates two events, a `move_from` event for the source key, and a `move_to` event for the destination key. -* `COPY` generates a `copy_to` event. -* `MIGRATE` generates a `del` event if the source key is removed. -* `RESTORE` generates a `restore` event for the key. -* `EXPIRE` and all its variants (`PEXPIRE`, `EXPIREAT`, `PEXPIREAT`) generate an `expire` event when called with a positive timeout (or a future timestamp). Note that when these commands are called with a negative timeout value or timestamp in the past, the key is deleted and only a `del` event is generated instead. -* `SORT` generates a `sortstore` event when `STORE` is used to set a new key. If the resulting list is empty, and the `STORE` option is used, and there was already an existing key with that name, the result is that the key is deleted, so a `del` event is generated in this condition. -* `SET` and all its variants (`SETEX`, `SETNX`,`GETSET`) generate `set` events. However `SETEX` will also generate an `expire` events. -* `MSET` generates a separate `set` event for every key. -* `SETRANGE` generates a `setrange` event. -* `INCR`, `DECR`, `INCRBY`, `DECRBY` commands all generate `incrby` events. -* `INCRBYFLOAT` generates an `incrbyfloat` events. -* `INCREX` generates an `incrby` event, or an `incrbyfloat` event with `BYFLOAT`. It also generates an `expire` event when it sets an expiration, and a `persist` event when `PERSIST` removes one. No events are generated when the call is skipped by `NX`/`XX` or rejected by a bound. -* `APPEND` generates an `append` event. -* `LPUSH` and `LPUSHX` generates a single `lpush` event, even in the variadic case. -* `RPUSH` and `RPUSHX` generates a single `rpush` event, even in the variadic case. -* `RPOP` generates an `rpop` event. Additionally a `del` event is generated if the key is removed because the last element from the list was popped. -* `LPOP` generates an `lpop` event. Additionally a `del` event is generated if the key is removed because the last element from the list was popped. -* `LINSERT` generates an `linsert` event. -* `LSET` generates an `lset` event. -* `LREM` generates an `lrem` event, and additionally a `del` event if the resulting list is empty and the key is removed. -* `LTRIM` generates an `ltrim` event, and additionally a `del` event if the resulting list is empty and the key is removed. -* `RPOPLPUSH` and `BRPOPLPUSH` generate an `rpop` event and an `lpush` event. In both cases the order is guaranteed (the `lpush` event will always be delivered after the `rpop` event). Additionally a `del` event will be generated if the resulting list is zero length and the key is removed. -* `LMOVE` and `BLMOVE` generate an `lpop`/`rpop` event (depending on the wherefrom argument) and an `lpush`/`rpush` event (depending on the whereto argument). In both cases the order is guaranteed (the `lpush`/`rpush` event will always be delivered after the `lpop`/`rpop` event). Additionally a `del` event will be generated if the resulting list is zero length and the key is removed. -* `HSET`, `HSETNX`, `HMSET` and `HSETEX` generate a single `hset` event if the specified fields were added or modified. -* `HINCRBY` generates an `hincrby` event. -* `HINCRBYFLOAT` generates an `hincrbyfloat` event. -* `HEXPIRE` and all its variants (`HPEXPIRE`, `HPEXPIRE`, `HEXPIREAT` and `HPEXPIREAT`) generate a single `hexpire` event when called with a positive timeout (or a future timestamp). Note that when these commands are called with a negative timeout value or timestamp in the past, only a single `hexpired` event is generated and if the hash object has no more items left it will be deleted and a `del` event is generated as well. -* `HSETEX` and `HGETEX` generate a single `hexpire` event when called with a positive timeout (or a future timestamp). Note that when these commands are called with a negative timeout value or timestamp in the past, only a single `hexpired` event is generated and if the hash object has no more items left it will be deleted and a `del` event is generated as well. -* `HPERSIST` and `HGETEX`, will generate an `hpersist` event if at least 1 hash field expiration time was removed. -* `HDEL` generates a single `hdel` event, and an additional `del` event if the resulting hash is empty and the key is removed. -* `SADD` generates a single `sadd` event, even in the variadic case. -* `SREM` generates a single `srem` event, and an additional `del` event if the resulting set is empty and the key is removed. -* `SMOVE` generates an `srem` event for the source key, and an `sadd` event for the destination key. -* `SPOP` generates an `spop` event, and an additional `del` event if the resulting set is empty and the key is removed. -* `SINTERSTORE`, `SUNIONSTORE`, `SDIFFSTORE` generate `sinterstore`, `sunionstore`, `sdiffstore` events respectively. In the special case the resulting set is empty, and the key where the result is stored already exists, a `del` event is generated since the key is removed. -* `ZINCR` generates a `zincr` event. -* `ZADD` generates a single `zadd` event even when multiple elements are added. -* `ZREM` generates a single `zrem` event even when multiple elements are deleted. When the resulting sorted set is empty and the key is generated, an additional `del` event is generated. -* `ZREMBYSCORE` generates a single `zrembyscore` event. When the resulting sorted set is empty and the key is generated, an additional `del` event is generated. -* `ZREMBYRANK` generates a single `zrembyrank` event. When the resulting sorted set is empty and the key is generated, an additional `del` event is generated. -* `ZDIFFSTORE`, `ZINTERSTORE` and `ZUNIONSTORE` respectively generate `zdiffstore`, `zinterstore` and `zunionstore` events. In the special case the resulting sorted set is empty, and the key where the result is stored already exists, a `del` event is generated since the key is removed. -* `XADD` generates an `xadd` event, possibly followed an `xtrim` event when used with the `MAXLEN` subcommand. -* `XDEL` generates a single `xdel` event even when multiple entries are deleted. -* `XGROUP CREATE` generates an `xgroup-create` event. -* `XGROUP CREATECONSUMER` generates an `xgroup-createconsumer` event. -* `XGROUP DELCONSUMER` generates an `xgroup-delconsumer` event. -* `XGROUP DESTROY` generates an `xgroup-destroy` event. -* `XGROUP SETID` generates an `xgroup-setid` event. -* `XSETID` generates an `xsetid` event. -* `XTRIM` generates an `xtrim` event. -* `PERSIST` generates a `persist` event if the expiry time associated with key has been successfully deleted. -* Every time a key with a time to live associated is removed from the data set because it expired, an `expired` event is generated. -* Every time a key is evicted from the data set in order to free memory as a result of the `maxmemory` policy, an `evicted` event is generated. -* Every time a new key is added to the data set, a `new` event is generated. - -**IMPORTANT** all the commands generate events only if the target key is really modified. For instance an `SREM` deleting a non-existing element from a Set will not actually change the value of the key, so no event will be generated. - -If in doubt about how events are generated for a given command, the simplest -thing to do is to watch yourself: - - $ valkey-cli config set notify-keyspace-events KEA - $ valkey-cli --csv psubscribe '__key*__:*' - Reading messages... (press Ctrl-C to quit) - "psubscribe","__key*__:*",1 - -At this point use `valkey-cli` in another terminal to send commands to the -Valkey server and watch the events generated: - - "pmessage","__key*__:*","__keyspace@0__:foo","set" - "pmessage","__key*__:*","__keyevent@0__:set","foo" - ... - -### Timing of expired events - -Keys with a time to live associated are expired by Valkey in two ways: - -* When the key is accessed by a command and is found to be expired. -* Via a background system that looks for expired keys in the background, incrementally, in order to be able to also collect keys that are never accessed. - -The `expired` events are generated when a key is accessed and is found to be expired by one of the above systems, as a result there are no guarantees that the Valkey server will be able to generate the `expired` event at the time the key time to live reaches the value of zero. - -Since Valkey 9.0, hash fields can also have an associated time to live. -Hash fields are deleted when explicitly provided an expiration time in the past or via the same background job which is also responsible to expire keys. For that reason, there are no guarantees that the Valkey server will be able to generate the `hexpired` event at the time the hash field time to live reaches the value of zero. - -Basically `expired` and `hexpired` events **are generated when the Valkey server deletes a key** and not when the time to live theoretically reaches the value of zero. -For that reason there can be a significant delay between the time the key time to live drops to zero, and the time the corresponding event is generated. - - -### Events in a cluster - -Every node of a Valkey cluster generates events about its own subset of the keyspace as described above. However, unlike regular Pub/Sub communication in a cluster, events' notifications **are not** broadcasted to all nodes. Put differently, keyspace events are node-specific. This means that to receive all keyspace events of a cluster, clients need to subscribe to each of the nodes. diff --git a/topics/performance-on-cpu.md b/topics/performance-on-cpu.md deleted file mode 100644 index 49adbc74..00000000 --- a/topics/performance-on-cpu.md +++ /dev/null @@ -1,230 +0,0 @@ ---- -title: "CPU profiling" -description: > - Performance engineering guide for on-CPU profiling and tracing ---- - -## Filling the performance checklist - -Valkey is developed with a great emphasis on performance. We do our best with -every release to make sure you'll experience a very stable and fast product. - -Nevertheless, if you're finding room to improve the efficiency of Valkey or -are pursuing a performance regression investigation you will need a concise -methodical way of monitoring and analyzing Valkey performance. - -To do so you can rely on different methodologies (some more suited than other -depending on the class of issues/analysis we intend to make). A curated list -of methodologies and their steps are enumerated by Brendan Greg at the -[following link](https://www.brendangregg.com/methodology.html). - -We recommend the Utilization Saturation and Errors (USE) Method for answering -the question of what is your bottleneck. Check the following mapping between -system resource, metric, and tools for a practical deep dive: -[USE method](https://www.brendangregg.com/USEmethod/use-rosetta.html). - -### Ensuring the CPU is your bottleneck - -This guide assumes you've followed one of the above methodologies to perform a -complete check of system health, and identified the bottleneck being the CPU. -**If you have identified that most of the time is spent blocked on I/O, locks, -timers, paging/swapping, etc., this guide is not for you**. - -### Build Prerequisites - -For a proper On-CPU analysis, Valkey (and any dynamically loaded library like -Valkey Modules) requires stack traces to be available to tracers, which you may -need to fix first. - -By default, Valkey is compiled with the `-O3` optimization flag (which we intent to keep -during profiling). This means that compiler optimizations are enabled which significantly -enhance the performance. Valkey is also compiled with the `-fno-omit-frame-pointer` flag -by default, ensuring that the frame pointer is preserved across function calls. -This combination allows for precise stack walking and call stack tracing, -which is essential for accurate profiling and debugging. Keeping the frame pointer -intact helps profiling tools like `perf`, `gdb`, and others correctly attribute on-CPU -time to deeper call stack frames, leading to more reliable insights into performance bottlenecks -and hotspots. This setup strikes a balance between maintaining a highly optimized executable -and ensuring that profiling and tracing tools provide accurate and actionable data. - -It's important that you ensure that: -- we still run with optimizations to get an accurate representation of production run times, meaning we will keep: `-O3` - -You can do it as follows within valkey main repo: - - $ make SERVER_CFLAGS="-g" - -## A set of instruments to identify performance regressions and/or potential **on-CPU performance** improvements - -This document focuses specifically on **on-CPU** resource bottlenecks analysis, -meaning we're interested in understanding where threads are spending CPU cycles -while running on-CPU and, as importantly, whether those cycles are effectively -being used for computation or stalled waiting (not blocked!) for memory I/O, -and cache misses, etc. - -For that we will rely on toolkits (perf, bcc tools), and hardware specific PMCs -(Performance Monitoring Counters), to proceed with: - -- Hotspot analysis (perf or bcc tools): to profile code execution and determine which functions are consuming the most time and thus are targets for optimization. We'll present two options to collect, report, and visualize hotspots either with perf or bcc/BPF tracing tools. - -- Call counts analysis: to count events including function calls, enabling us to correlate several calls/components at once, relying on bcc/BPF tracing tools. - -- Hardware event sampling: crucial for understanding CPU behavior, including memory I/O, stall cycles, and cache misses. - -### Tool prerequisites - -The following steps rely on Linux perf_events (aka ["perf"](https://man7.org/linux/man-pages/man1/perf.1.html)), [bcc/BPF tracing tools](https://github.com/iovisor/bcc), and Brendan Greg’s [FlameGraph repo](https://github.com/brendangregg/FlameGraph). - -We assume beforehand you have: - -- Installed the perf tool on your system. Most Linux distributions will likely package this as a package related to the kernel. More information about the perf tool can be found at perf [wiki](https://perf.wiki.kernel.org/). -- Followed the install [bcc/BPF](https://github.com/iovisor/bcc/blob/master/INSTALL.md#installing-bcc) instructions to install bcc toolkit on your machine. -- Cloned Brendan Greg’s [FlameGraph repo](https://github.com/brendangregg/FlameGraph) and made accessible the `difffolded.pl` and `flamegraph.pl` files, to generated the collapsed stack traces and Flame Graphs. - -## Hotspot analysis with perf or eBPF (stack traces sampling) - -Profiling CPU usage by sampling stack traces at a timed interval is a fast and -easy way to identify performance-critical code sections (hotspots). - -### Sampling stack traces using perf - -To profile both user- and kernel-level stacks of valkey-server for a specific -length of time, for example 60 seconds, at a sampling frequency of 999 samples -per second: - - $ perf record -g --pid $(pgrep valkey-server) -F 999 -- sleep 60 - -#### Displaying the recorded profile information using perf report - -By default perf record will generate a perf.data file in the current working -directory. - -You can then report with a call-graph output (call chain, stack backtrace), -with a minimum call graph inclusion threshold of 0.5%, with: - - $ perf report -g "graph,0.5,caller" - -See the [perf report](https://man7.org/linux/man-pages/man1/perf-report.1.html) -documentation for advanced filtering, sorting and aggregation capabilities. - -#### Visualizing the recorded profile information using Flame Graphs - -[Flame graphs](https://www.brendangregg.com/flamegraphs.html) allow for a quick -and accurate visualization of frequent code-paths. They can be generated using -Brendan Greg's open source programs on [github](https://github.com/brendangregg/FlameGraph), -which create interactive SVGs from folded stack files. - -Specifically, for perf we need to convert the generated perf.data into the -captured stacks, and fold each of them into single lines. You can then render -the on-CPU flame graph with: - - $ perf script > valkey.perf.stacks - $ stackcollapse-perf.pl valkey.perf.stacks > valkey.folded.stacks - $ flamegraph.pl valkey.folded.stacks > valkey.svg - -By default, perf script will generate a perf.data file in the current working -directory. See the [perf script](https://linux.die.net/man/1/perf-script) -documentation for advanced usage. - -See [FlameGraph usage options](https://github.com/brendangregg/FlameGraph#options) -for more advanced stack trace visualizations (like the differential one). - -#### Archiving and sharing recorded profile information - -So that analysis of the perf.data contents can be possible on a machine other -than the one on which collection happened, you need to export along with the -perf.data file all object files with build-ids found in the record data file. -This can be easily done with the help of -[perf-archive.sh](https://github.com/torvalds/linux/blob/master/tools/perf/perf-archive.sh) -script: - - $ perf-archive.sh perf.data - -Now please run: - - $ tar xvf perf.data.tar.bz2 -C ~/.debug - -on the machine where you need to run `perf report`. - -### Sampling stack traces using bcc/BPF's profile - -Similarly to perf, as of Linux kernel 4.9, BPF-optimized profiling is now fully -available with the promise of lower overhead on CPU (as stack traces are -frequency counted in kernel context) and disk I/O resources during profiling. - -Apart from that, and relying solely on bcc/BPF's profile tool, we have also -removed the perf.data and intermediate steps if stack traces analysis is our -main goal. You can use bcc's profile tool to output folded format directly, for -flame graph generation: - - $ /usr/share/bcc/tools/profile -F 999 -f --pid $(pgrep valkey-server) --duration 60 > valkey.folded.stacks - -In that manner, we've remove any preprocessing and can render the on-CPU flame -graph with a single command: - - $ flamegraph.pl valkey.folded.stacks > valkey.svg - -### Visualizing the recorded profile information using Flame Graphs - -## Call counts analysis with bcc/BPF - -A function may consume significant CPU cycles either because its code is slow -or because it's frequently called. To answer at what rate functions are being -called, you can rely upon call counts analysis using BCC's `funccount` tool: - - $ /usr/share/bcc/tools/funccount 'valkey-server:(call*|*Read*|*Write*)' --pid $(pgrep valkey-server) --duration 60 - Tracing 64 functions for "valkey-server:(call*|*Read*|*Write*)"... Hit Ctrl-C to end. - - FUNC COUNT - call 334 - handleClientsWithPendingWrites 388 - clientInstallWriteHandler 388 - postponeClientRead 514 - handleClientsWithPendingReadsUsingThreads 735 - handleClientsWithPendingWritesUsingThreads 735 - prepareClientToWrite 1442 - Detaching... - - -The above output shows that, while tracing, the Valkey's call() function was -called 334 times, handleClientsWithPendingWrites() 388 times, etc. - -## Hardware event counting with Performance Monitoring Counters (PMCs) - -Many modern processors contain a performance monitoring unit (PMU) exposing -Performance Monitoring Counters (PMCs). PMCs are crucial for understanding CPU -behavior, including memory I/O, stall cycles, and cache misses, and provide -low-level CPU performance statistics that aren't available anywhere else. - -The design and functionality of a PMU is CPU-specific and you should assess -your CPU supported counters and features by using `perf list`. - -To calculate the number of instructions per cycle, the number of micro ops -executed, the number of cycles during which no micro ops were dispatched, the -number stalled cycles on memory, including a per memory type stalls, for the -duration of 60s, specifically for the valkey-server process: - - $ perf stat -e "cpu-clock,cpu-cycles,instructions,uops_executed.core,uops_executed.stall_cycles,cache-references,cache-misses,cycle_activity.stalls_total,cycle_activity.stalls_mem_any,cycle_activity.stalls_l3_miss,cycle_activity.stalls_l2_miss,cycle_activity.stalls_l1d_miss" --pid $(pgrep valkey-server) -- sleep 60 - - Performance counter stats for process id '3038': - - 60046.411437 cpu-clock (msec) # 1.001 CPUs utilized - 168991975443 cpu-cycles # 2.814 GHz (36.40%) - 388248178431 instructions # 2.30 insn per cycle (45.50%) - 443134227322 uops_executed.core # 7379.862 M/sec (45.51%) - 30317116399 uops_executed.stall_cycles # 504.895 M/sec (45.51%) - 670821512 cache-references # 11.172 M/sec (45.52%) - 23727619 cache-misses # 3.537 % of all cache refs (45.43%) - 30278479141 cycle_activity.stalls_total # 504.251 M/sec (36.33%) - 19981138777 cycle_activity.stalls_mem_any # 332.762 M/sec (36.33%) - 725708324 cycle_activity.stalls_l3_miss # 12.086 M/sec (36.33%) - 8487905659 cycle_activity.stalls_l2_miss # 141.356 M/sec (36.32%) - 10011909368 cycle_activity.stalls_l1d_miss # 166.736 M/sec (36.31%) - - 60.002765665 seconds time elapsed - -It's important to know that there are two very different ways in which PMCs can -be used (counting and sampling), and we've focused solely on PMCs counting for -the sake of this analysis. Brendan Greg clearly explains it on the following -[link](https://www.brendangregg.com/blog/2017-05-04/the-pmcs-of-ec2.html). - diff --git a/topics/persistence.md b/topics/persistence.md deleted file mode 100644 index f8899fe4..00000000 --- a/topics/persistence.md +++ /dev/null @@ -1,338 +0,0 @@ ---- -title: Persistence -description: How Valkey writes data to disk ---- - -Persistence refers to the writing of data to durable storage, such as a solid-state disk (SSD). Valkey provides a range of persistence options. These include: - -* **RDB** (Valkey Database): RDB persistence performs point-in-time snapshots of your dataset at specified intervals. -* **AOF** (Append Only File): AOF persistence logs every write operation received by the server. These operations can then be replayed again at server startup, reconstructing the original dataset. Commands are logged using the same format as the Valkey protocol itself. -* **No persistence**: You can disable persistence completely. This is sometimes used when caching. -* **RDB + AOF**: You can also combine both AOF and RDB in the same instance. - -To learn more about how to evaluate your Valkey persistence strategy, read on. - -## RDB advantages - -* RDB is a very compact single-file point-in-time representation of your Valkey data. RDB files are perfect for backups. For instance you may want to archive your RDB files every hour for the latest 24 hours, and to save an RDB snapshot every day for 30 days. This allows you to easily restore different versions of the data set in case of disasters. -* RDB is very good for disaster recovery, being a single compact file that can be transferred to far data centers, or onto Amazon S3 (possibly encrypted). -* RDB maximizes Valkey performances since the only work the Valkey parent process needs to do in order to persist is forking a child that will do all the rest. The parent process will never perform disk I/O or alike. -* RDB allows faster restarts with big datasets compared to AOF. -* On replicas, RDB supports [partial resynchronizations after restarts and failovers](replication.md#partial-sync-after-restarts-and-failovers). - -## RDB disadvantages - -* RDB is NOT good if you need to minimize the chance of data loss in case Valkey stops working (for example after a power outage). You can configure different *save points* where an RDB is produced (for instance after at least five minutes and 100 writes against the data set, you can have multiple save points). However you'll usually create an RDB snapshot every five minutes or more, so in case of Valkey stopping working without a correct shutdown for any reason you should be prepared to lose the latest minutes of data. -* RDB needs to fork() often in order to persist on disk using a child process. fork() can be time consuming if the dataset is big, and may result in Valkey stopping serving clients for some milliseconds or even for one second if the dataset is very big and the CPU performance is not great. AOF also needs to fork() but less frequently and you can tune how often you want to rewrite your logs without any trade-off on durability. - -## AOF advantages - -* Using AOF Valkey is much more durable: you can have different fsync policies: no fsync at all, fsync every second, fsync at every query. With the default policy of fsync every second, write performance is still great. fsync is performed using a background thread and the main thread will try hard to perform writes when no fsync is in progress, so you can only lose one second worth of writes. -* The AOF log is an append-only log, so there are no seeks, nor corruption problems if there is a power outage. Even if the log ends with a half-written command for some reason (disk full or other reasons) the valkey-check-aof tool is able to fix it easily. -* Valkey is able to automatically rewrite the AOF in background when it gets too big. The rewrite is completely safe as while Valkey continues appending to the old file, a completely new one is produced with the minimal set of operations needed to create the current data set, and once this second file is ready Valkey switches the two and starts appending to the new one. -* AOF contains a log of all the operations one after the other in an easy to understand and parse format. You can even easily export an AOF file. For instance even if you've accidentally flushed everything using the `FLUSHALL` command, as long as no rewrite of the log was performed in the meantime, you can still save your data set just by stopping the server, removing the latest command, and restarting Valkey again. - -## AOF disadvantages - -* AOF files are usually bigger than the equivalent RDB files for the same dataset. -* AOF can be slower than RDB depending on the exact fsync policy. In general with fsync set to *every second* performance is still very high, and with fsync disabled it should be exactly as fast as RDB even under high load. Still RDB is able to provide more guarantees about the maximum latency even in the case of a huge write load. - - -Ok, so what should I use? ---- - -The general indication you should use both persistence methods is if -you want a degree of data safety comparable to what PostgreSQL can provide you. - -If you care a lot about your data, but still can live with a few minutes of -data loss in case of disasters, you can simply use RDB alone. - -There are many users using AOF alone, but we discourage it since to have an -RDB snapshot from time to time is a great idea for doing database backups, -for faster restarts, and in the event of bugs in the AOF engine. - -The following sections will illustrate a few more details about the two persistence models. - -## Snapshotting - -By default Valkey saves snapshots of the dataset on disk, in a binary -file called `dump.rdb`. You can configure Valkey to have it save the -dataset every N seconds if there are at least M changes in the dataset, -or you can manually call the `SAVE` or `BGSAVE` commands. - -For example, this configuration will make Valkey automatically dump the -dataset to disk every 60 seconds if at least 1000 keys changed: - - save 60 1000 - -This strategy is known as _snapshotting_. - -## No persistence - -If you prefer **not** to have persistence (for example when using a Valkey instance solely as a cache) that is also a possibility. - -RDB snapshotting is enabled by default. To disable it, set the `save` configuration parameter to the empty string `""` and remove any excess `save` lines that are present in the current configuration file. - - save "" - -Alternatively, you can also use the `--save ""` argument on the `valkey-server` binary. - -### How it works - -Whenever Valkey needs to dump the dataset to disk, this is what happens: - -* Valkey [forks](https://linux.die.net/man/2/fork). We now have a child -and a parent process. - -* The child starts to write the dataset to a temporary RDB file. - -* When the child is done writing the new RDB file, it replaces the old -one. - -This method allows Valkey to benefit from copy-on-write semantics. - -## Append-only file - -Snapshotting is not very durable. If your computer running Valkey stops, -your power line fails, or you accidentally `kill -9` your instance, the -latest data written to Valkey will be lost. While this may not be a big -deal for some applications, there are use cases for full durability, and -in these cases Valkey snapshotting alone is not a viable option. - -The _append-only file_ is an alternative, fully-durable strategy for -Valkey. - -You can turn on the AOF in your configuration file: - - appendonly yes - -From now on, every time Valkey receives a command that changes the -dataset (e.g. `SET`) it will append it to the AOF. When you restart -Valkey it will re-play the AOF to rebuild the state. - -Valkey uses a multi part AOF mechanism. -That is, the original single AOF file is split into base file (at most one) and incremental files (there may be more than one). -The base file represents an initial (RDB or AOF format) snapshot of the data present when the AOF is [rewritten](#log-rewriting). -The incremental files contains incremental changes since the last base AOF file was created. All these files are put in a separate directory and are tracked by a manifest file. - -### Log rewriting - -The AOF gets bigger and bigger as write operations are -performed. For example, if you are incrementing a counter 100 times, -you'll end up with a single key in your dataset containing the final -value, but 100 entries in your AOF. 99 of those entries are not needed -to rebuild the current state. - -The rewrite is completely safe. -While Valkey continues appending to the old file, -a completely new one is produced with the minimal set of operations needed to create the current data set, -and once this second file is ready Valkey switches the two and starts appending to the new one. - -Valkey supports an interesting feature: it is able to rebuild the AOF in the background without interrupting service to clients. -Whenever you issue a `BGREWRITEAOF`, Valkey will write the shortest sequence of commands needed to rebuild the current dataset in memory. -Valkey will automatically trigger log rewriting automatically (see the example configuration file for more information). - -When an AOF rewrite is scheduled, the Valkey parent process opens a new incremental AOF file to continue writing. -The child process executes the rewrite logic and generates a new base AOF. -Valkey will use a temporary manifest file to track the newly generated base file and incremental file. -When they are ready, Valkey will perform an atomic replacement operation to make this temporary manifest file take effect. -In order to avoid the problem of creating many incremental files in case of repeated failures and retries of an AOF rewrite, -Valkey introduces an AOF rewrite limiting mechanism to ensure that failed AOF rewrites are retried at a slower and slower rate. - -### How durable is the append only file? - -You can configure how many times Valkey will -[`fsync`](https://linux.die.net/man/2/fsync) data on disk. There are -three options: - -* `appendfsync always`: `fsync` every time new commands are appended to the AOF. Very very slow, very safe. Note that the commands are appended to the AOF after a batch of commands from multiple clients or a pipeline are executed, so it means a single write and a single fsync (before sending the replies). -* `appendfsync everysec`: `fsync` every second. Fast enough and you may lose 1 second of data if there is a disaster. -* `appendfsync no`: Never `fsync`, just put your data in the hands of the Operating System. The faster and less safe method. Normally Linux will flush data every 30 seconds with this configuration, but it's up to the kernel's exact tuning. - -The suggested (and default) policy is to `fsync` every second. It is -both fast and relatively safe. The `always` policy is very slow in -practice, but it supports group commit, so if there are multiple parallel -writes Valkey will try to perform a single `fsync` operation. - -### What should I do if my AOF gets truncated? - -It is possible the server crashed while writing the AOF file, or the -volume where the AOF file is stored was full at the time of writing. When this happens the -AOF still contains consistent data representing a given point-in-time version -of the dataset (that may be old up to one second with the default AOF fsync -policy), but the last command in the AOF could be truncated. -The latest major versions of Valkey will be able to load the AOF anyway, just -discarding the last non well formed command in the file. In this case the -server will emit a log like the following: - -``` -* Reading RDB preamble from AOF file... -* Reading the remaining AOF tail... -# !!! Warning: short read while loading the AOF file !!! -# !!! Truncating the AOF at offset 439 !!! -# AOF loaded anyway because aof-load-truncated is enabled -``` - -You can change the default configuration to force Valkey to stop in such -cases if you want, but the default configuration is to continue regardless of -the fact the last command in the file is not well-formed, in order to guarantee -availability after a restart. - -Older versions of Valkey may not recover, and may require the following steps: - -* Make a backup copy of your AOF file. -* Fix the original file using the `valkey-check-aof` tool that ships with Valkey: - - $ valkey-check-aof --fix - -* Optionally use `diff -u` to check what is the difference between two files. -* Restart the server with the fixed file. - -### What should I do if my AOF gets corrupted? - -If the AOF file is not just truncated, but corrupted with invalid byte -sequences in the middle, things are more complex. Valkey will complain -at startup and will abort: - -``` -* Reading the remaining AOF tail... -# Bad file format reading the append only file: make a backup of your AOF file, then use ./valkey-check-aof --fix -``` - -The best thing to do is to run the `valkey-check-aof` utility, initially without -the `--fix` option, then understand the problem, jump to the given -offset in the file, and see if it is possible to manually repair the file: -The AOF uses the same format of the Valkey protocol and is quite simple to fix -manually. Otherwise it is possible to let the utility fix the file for us, but -in that case all the AOF portion from the invalid part to the end of the -file may be discarded, leading to a massive amount of data loss if the -corruption happened to be in the initial part of the file. - -### How it works - -Log rewriting uses the same copy-on-write trick already in use for -snapshotting. This is how it works: - -**Valkey multi-part AOF** - -* Valkey [forks](https://linux.die.net/man/2/fork), so now we have a child -and a parent process. - -* The child starts writing the new base AOF in a temporary file. - -* The parent opens a new increments AOF file to continue writing updates. - If the rewriting fails, the old base and increment files (if there are any) plus this newly opened increment file represent the complete updated dataset, - so we are safe. - -* When the child is done rewriting the base file, the parent gets a signal, -and uses the newly opened increment file and child generated base file to build a temp manifest, -and persist it. - -* Profit! Now Valkey does an atomic exchange of the manifest files so that the result of this AOF rewrite takes effect. Valkey also cleans up the old base file and any unused increment files. - -### How I can switch to AOF, if I'm currently using dump.rdb snapshots? - -If you want to enable AOF in a server that is currently using RDB snapshots, you need to convert the data by enabling AOF via CONFIG command on the live server first. - -**IMPORTANT:** not following this procedure (e.g. just changing the config and restarting the server) can result in data loss! - -Preparations: - -* Make a backup of your latest dump.rdb file. -* Transfer this backup to a safe place. - -Switch to AOF on live database: - -* Enable AOF: `valkey-cli config set appendonly yes` -* Optionally disable RDB: `valkey-cli config set save ""` -* Make sure writes are appended to the append only file correctly. -* **IMPORTANT:** Update your `valkey.conf` (potentially through `CONFIG REWRITE`) and ensure that it matches the configuration above. - If you forget this step, when you restart the server, the configuration changes will be lost and the server will start again with the old configuration, resulting in a loss of your data. - -Next time you restart the server: - -* Before restarting the server, wait for AOF rewrite to finish persisting the data. - You can do that by watching `INFO persistence`, waiting for `aof_rewrite_in_progress` and `aof_rewrite_scheduled` to be `0`, and validating that `aof_last_bgrewrite_status` is `ok`. -* After restarting the server, check that your database contains the same number of keys it contained previously. - -## Interactions between AOF and RDB persistence - -Valkey makes sure to avoid triggering an AOF rewrite when an RDB -snapshotting operation is already in progress, or allowing a `BGSAVE` while the -AOF rewrite is in progress. This prevents two Valkey background processes -from doing heavy disk I/O at the same time. - -When snapshotting is in progress and the user explicitly requests a log -rewrite operation using `BGREWRITEAOF` the server will reply with an OK -status code telling the user the operation is scheduled, and the rewrite -will start once the snapshotting is completed. - -In the case both AOF and RDB persistence are enabled and Valkey restarts the -AOF file will be used to reconstruct the original dataset since it is -guaranteed to be the most complete. - -## Backing up Valkey data - -Before starting this section, make sure to read the following sentence: **Make Sure to Backup Your Database**. Disks break, instances in the cloud disappear, and so forth: no backups means huge risk of data disappearing into /dev/null. - -Valkey is very data backup friendly since you can copy RDB files while the -database is running: the RDB is never modified once produced, and while it -gets produced it uses a temporary name and is renamed into its final destination -atomically using rename(2) only when the new snapshot is complete. - -This means that copying the RDB file is completely safe while the server is -running. This is what we suggest: - -* Create a cron job in your server creating hourly snapshots of the RDB file in one directory, and daily snapshots in a different directory. -* Every time the cron script runs, make sure to call the `find` command to make sure too old snapshots are deleted: for instance you can take hourly snapshots for the latest 48 hours, and daily snapshots for one or two months. Make sure to name the snapshots with date and time information. -* At least one time every day make sure to transfer an RDB snapshot *outside your data center* or at least *outside the physical machine* running your Valkey instance. - -### Backing up AOF persistence - -If you run a Valkey instance with only AOF persistence enabled, you can still perform backups. -AOF files are split into multiple files which reside in a single directory determined by the `appenddirname` configuration. -During normal operation all you need to do is copy/tar the files in this directory to achieve a backup. However, if this is done during a [rewrite](#log-rewriting), you might end up with an invalid backup. -To work around this you must disable AOF rewrites during the backup: - -1. Turn off automatic rewrites with
- `CONFIG SET` `auto-aof-rewrite-percentage 0`
- Make sure you don't manually start a rewrite (using `BGREWRITEAOF`) during this time. -2. Check there's no current rewrite in progress using
- `INFO` `persistence`
- and verifying `aof_rewrite_in_progress` is 0. If it's 1, then you'll need to wait for the rewrite to complete. -3. Now you can safely copy the files in the `appenddirname` directory. -4. Re-enable rewrites when done:
- `CONFIG SET` `auto-aof-rewrite-percentage ` - -**Note:** If you want to minimize the time AOF rewrites are disabled you may create hard links to the files in `appenddirname` (in step 3 above) and then re-enable rewrites (step 4) after the hard links are created. -Now you can copy/tar the hardlinks and delete them when done. This works because Valkey guarantees that it -only appends to files in this directory, or completely replaces them if necessary, so the content should be -consistent at any given point in time. - - -**Note:** If you want to handle the case of the server being restarted during the backup and make sure no rewrite will automatically start after the restart you can change step 1 above to also persist the updated configuration via `CONFIG REWRITE`. -Just make sure to re-enable automatic rewrites when done (step 4) and persist it with another `CONFIG REWRITE`. - -## Disaster recovery - -Disaster recovery in the context of Valkey is basically the same story as -backups, plus the ability to transfer those backups in many different external -data centers. This way data is secured even in the case of some catastrophic -event affecting the main data center where Valkey is running and producing its -snapshots. - -We'll review the most interesting disaster recovery techniques -that don't have too high costs. - -* Amazon S3 and other similar services are a good way for implementing your disaster recovery system. Simply transfer your daily or hourly RDB snapshot to S3 in an encrypted form. You can encrypt your data using `gpg -c` (in symmetric encryption mode). Make sure to store your password in many different safe places (for instance give a copy to the most important people of your organization). It is recommended to use multiple storage services for improved data safety. -* Transfer your snapshots using SCP (part of SSH) to far servers. This is a fairly simple and safe route: get a small VPS in a place that is very far from you, install ssh there, and generate a ssh client key without passphrase, then add it in the `authorized_keys` file of your small VPS. You are ready to transfer backups in an automated fashion. Get at least two VPS in two different providers -for best results. - -It is important to understand that this system can easily fail if not -implemented in the right way. At least, make absolutely sure that after the -transfer is completed you are able to verify the file size (that should match -the one of the file you copied) and possibly the SHA1 digest, if you are using -a VPS. - -You also need some kind of independent alert system if the transfer of fresh -backups is not working for some reason. diff --git a/topics/pipeline_iops.png b/topics/pipeline_iops.png deleted file mode 100644 index 6ab11079..00000000 Binary files a/topics/pipeline_iops.png and /dev/null differ diff --git a/topics/pipelining.md b/topics/pipelining.md deleted file mode 100644 index 750bfdb5..00000000 --- a/topics/pipelining.md +++ /dev/null @@ -1,174 +0,0 @@ ---- -title: "Pipelining" -description: How to optimize round-trip times by batching Valkey commands ---- - -Valkey pipelining is a technique for improving performance by issuing multiple commands at once without waiting for the response to each individual command. Pipelining is supported by most Valkey clients. This document describes the problem that pipelining is designed to solve and how pipelining works in Valkey. - -## Request/Response protocols and round-trip time (RTT) - -Valkey is a TCP server using the client-server model and what is called a *Request/Response* protocol. - -This means that usually a request is accomplished with the following steps: - -* The client sends a query to the server, and reads from the socket, usually in a blocking way, for the server response. -* The server processes the command and sends the response back to the client. - -So for instance a four commands sequence is something like this: - - * *Client:* INCR X - * *Server:* 1 - * *Client:* INCR X - * *Server:* 2 - * *Client:* INCR X - * *Server:* 3 - * *Client:* INCR X - * *Server:* 4 - -Clients and Servers are connected via a network link. -Such a link can be very fast (a loopback interface) or very slow (a connection established over the Internet with many hops between the two hosts). -Whatever the network latency is, it takes time for the packets to travel from the client to the server, and back from the server to the client to carry the reply. - -This time is called RTT (Round Trip Time). -It's easy to see how this can affect performance when a client needs to perform many requests in a row (for instance adding many elements to the same list, or populating a database with many keys). -For instance if the RTT time is 250 milliseconds (in the case of a very slow link over the Internet), even if the server is able to process 100k requests per second, we'll be able to process at max four requests per second. - -If the interface used is a loopback interface, the RTT is much shorter, typically sub-millisecond, but even this will add up to a lot if you need to perform many writes in a row. - -Fortunately there is a way to improve this use case. - -## Valkey Pipelining - -A Request/Response server can be implemented so that it is able to process new requests even if the client hasn't already read the old responses. -This way it is possible to send *multiple commands* to the server without waiting for the replies at all, and finally read the replies in a single step. - -This is called pipelining, and is a technique widely in use for many decades. -For instance many POP3 protocol implementations already support this feature, dramatically speeding up the process of downloading new emails from the server. - -Valkey has supported pipelining since its early days, so whatever version you are running, you can use pipelining with Valkey. -This is an example using the raw netcat utility: - -```bash -$ (printf "PING\r\nPING\r\nPING\r\n"; sleep 1) | nc localhost 6379 -+PONG -+PONG -+PONG -``` - -This time we don't pay the cost of RTT for every call, but just once for the three commands. - -To be explicit, with pipelining the order of operations of our very first example will be the following: - - * *Client:* INCR X - * *Client:* INCR X - * *Client:* INCR X - * *Client:* INCR X - * *Server:* 1 - * *Server:* 2 - * *Server:* 3 - * *Server:* 4 - -> **IMPORTANT NOTE**: While the client sends commands using pipelining, the server will be forced to queue the replies, using memory. So if you need to send a lot of commands with pipelining, it is better to send them as batches each containing a reasonable number, for instance 10k commands, read the replies, and then send another 10k commands again, and so forth. The speed will be nearly the same, but the additional memory used will be at most the amount needed to queue the replies for these 10k commands. - -## It's not just a matter of RTT - -Pipelining is not just a way to reduce the latency cost associated with the -round trip time, it actually greatly improves the number of operations -you can perform per second in a given Valkey server. -This is because without using pipelining, serving each command is very cheap from -the point of view of accessing the data structures and producing the reply, -but it is very costly from the point of view of doing the socket I/O. This -involves calling the `read()` and `write()` syscall, that means going from user -land to kernel land. -The context switch is a huge speed penalty. - -When pipelining is used, many commands are usually read with a single `read()` -system call, and multiple replies are delivered with a single `write()` system -call. Consequently, the number of total queries performed per second -initially increases almost linearly with longer pipelines, and eventually -reaches 10 times the baseline obtained without pipelining, as shown in this figure. - -![Pipeline size and IOPs](pipeline_iops.png) - -## A real world code example - - -In the following benchmark we'll use a Ruby client, supporting pipelining, to test the speed improvement due to pipelining: - -```ruby -require 'rubygems' -require 'redis' - -def bench(descr) - start = Time.now - yield - puts "#{descr} #{Time.now - start} seconds" -end - -def without_pipelining - r = Redis.new - 10_000.times do - r.ping - end -end - -def with_pipelining - r = Redis.new - r.pipelined do - 10_000.times do - r.ping - end - end -end - -bench('without pipelining') do - without_pipelining -end -bench('with pipelining') do - with_pipelining -end -``` - -Running the above simple script yields the following figures on my MacOS system, running over the loopback interface, where pipelining will provide the smallest improvement as the RTT is already pretty low: - -``` -without pipelining 1.185238 seconds -with pipelining 0.250783 seconds -``` -As you can see, using pipelining, we improved the transfer by a factor of five. - -## Pipelining vs Scripting - -Using [Valkey scripting](../commands/eval.md), a number of use cases for pipelining can be addressed more efficiently using scripts that perform a lot of the work needed at the server side. -A big advantage of scripting is that it is able to both read and write data with minimal latency, making operations like *read, compute, write* very fast (pipelining can't help in this scenario since the client needs the reply of the read command before it can call the write command). - -Sometimes the application may also want to send `EVAL` or `EVALSHA` commands in a pipeline. -This is entirely possible and Valkey explicitly supports it with the [SCRIPT LOAD](../commands/script-load.md) command (it guarantees that `EVALSHA` can be called without the risk of failing). - -## Appendix: Why are busy loops slow even on the loopback interface? - -Even with all the background covered in this page, you may still wonder why -a Valkey benchmark like the following (in pseudo code), is slow even when -executed in the loopback interface, when the server and the client are running -in the same physical machine: - -```sh -FOR-ONE-SECOND: - Valkey.SET("foo","bar") -END -``` - -After all, if both the Valkey process and the benchmark are running in the same -box, isn't it just copying messages in memory from one place to another without -any actual latency or networking involved? - -The reason is that processes in a system are not always running, actually it is -the kernel scheduler that lets the process run. -So, for instance, when the benchmark is allowed to run, it reads the reply from the Valkey server (related to the last command executed), and writes a new command. -The command is now in the loopback interface buffer, but in order to be read by the server, the kernel should schedule the server process (currently blocked in a system call) -to run, and so forth. -So in practical terms the loopback interface still involves network-like latency, because of how the kernel scheduler works. - -Basically a busy loop benchmark is the silliest thing that can be done when -metering performances on a networked server. The wise thing is just avoiding -benchmarking in this way. diff --git a/topics/problems.md b/topics/problems.md deleted file mode 100644 index e1745121..00000000 --- a/topics/problems.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: "Troubleshooting Valkey" -description: Problems with Valkey? Start here. ---- - -This page tries to help you with what to do if you have issues with Valkey. Part of the Valkey project is helping people that are experiencing problems because we don't like to leave people alone with their issues. - -* If you have **latency problems** with Valkey, that in some way appears to be idle for some time, read our [Valkey latency troubleshooting guide](latency.md). -* Valkey stable releases are usually very reliable, however in the rare event you are **experiencing crashes** the developers can help a lot more if you provide debugging information. Please read our [Debugging Valkey guide](debugging.md). -* We have a long history of users experiencing crashes with Valkey that actually turned out to be servers with **broken RAM**. Please test your RAM using **valkey-server --test-memory** in case Valkey is not stable in your system. Valkey built-in memory test is fast and reasonably reliable, but if you can you should reboot your server and use [memtest86](https://memtest86.com). diff --git a/topics/programmability.md b/topics/programmability.md deleted file mode 100644 index be01db09..00000000 --- a/topics/programmability.md +++ /dev/null @@ -1,117 +0,0 @@ ---- -title: "Programmability" -description: > - Extending Valkey with Lua and Valkey Functions ---- - -Valkey provides a programming interface that lets you execute custom scripts on the server itself. -You can use [Functions](functions-intro.md) to create, manage and run scripts. -You can also use [Lua scripting with the EVAL command](eval-intro.md) to program the server. - -## Background - -Valkey is a _"domain-specific language for abstract data types"_. -The language that Valkey speaks consists of its [commands](../commands/). -Most the commands specialize at manipulating core [data types](data-types.md) in different ways. -In many cases, these commands provide all the functionality that a developer requires for managing application data in Valkey. - -The term **programmability** in Valkey means having the ability to execute arbitrary user-defined logic by the server. -We refer to such pieces of logic as **scripts**. -In our case, scripts enable processing the data where it lives, a.k.a _data locality_. -Furthermore, the responsible embedding of programmatic workflows in the Valkey server can help in reducing network traffic and improving overall performance. -Developers can use this capability for implementing robust, application-specific APIs. -Such APIs can encapsulate business logic and maintain a data model across multiple keys and different data structures. - -User scripts are executed in Valkey by an embedded, sandboxed scripting engine. -Presently, Valkey supports a single scripting engine, the [Lua 5.1](https://www.lua.org/) interpreter. - -Please refer to the [Valkey Lua API Reference](lua-api.md) page for complete documentation. - -## Running scripts - -Valkey provides two means for running scripts. - -Firstly, the `EVAL` command enables running server-side scripts. -Eval scripts provide a quick and straightforward way to have Valkey run your scripts ad-hoc. -However, using them means that the scripted logic is a part of your application (not an extension of the Valkey server). -Every applicative instance that runs a script must have the script's source code readily available for loading at any time. -That is because scripts are only cached by the server and are volatile. -As your application grows, this approach can become harder to develop and maintain. - -Secondly, added in v7.0, Valkey Functions are essentially scripts that are first-class database elements. -As such, functions decouple scripting from application logic and enable independent development, testing, and deployment of scripts. -To use functions, they need to be loaded first, and then they are available for use by all connected clients. -In this case, loading a function to the database becomes an administrative deployment task (such as loading a Valkey module, for example), which separates the script from the application. - -Please refer to the following pages for more information: - -* [Valkey Eval Scripts](eval-intro.md) -* [Valkey Functions](functions-intro.md) - -When running a script or a function, Valkey guarantees its atomic execution. -The script's execution blocks all server activities during its entire time, similarly to the semantics of [transactions](transactions.md). -These semantics mean that all of the script's effects either have yet to happen or had already happened. -The blocking semantics of an executed script apply to all connected clients at all times. - -Note that the potential downside of this blocking approach is that executing slow scripts is not a good idea. -It is not hard to create fast scripts because scripting's overhead is very low. -However, if you intend to use a slow script in your application, be aware that all other clients are blocked and can't execute any command while it is running. - -## Read-only scripts - -A read-only script is a script that only executes commands that don't modify any keys within Valkey. -Read-only scripts can be executed either by adding the `no-writes` [flag](lua-api.md#script_flags) to the script or by executing the script with one of the read-only script command variants: `EVAL_RO`, `EVALSHA_RO`, or `FCALL_RO`. -They have the following properties: - -* They can always be executed on replicas. -* They can always be killed by the `SCRIPT KILL` command. -* They never fail with OOM error when Valkey is over the memory limit. -* They are not blocked during write pauses, such as those that occur during coordinated failovers. -* They cannot execute any command that may modify the data set. -* Currently `PUBLISH`, `SPUBLISH` and `PFCOUNT` are also considered write commands in scripts, because they could attempt to propagate commands to replicas and AOF file. - -In addition to the benefits provided by all read-only scripts, the read-only script commands have the following advantages: - -* They can be used to configure an ACL user to only be able to execute read-only scripts. -* Many clients also better support routing the read-only script commands to replicas for applications that want to use replicas for read scaling. - -#### Read-only script history - -Read-only scripts and read-only script commands were introduced in Redis OSS 7.0 - -* Before Redis OSS 7.0.1 `PUBLISH`, `SPUBLISH` and `PFCOUNT` were not considered write commands in scripts -* Before Redis OSS 7.0.1 the `no-writes` [flag](lua-api.md#script_flags) did not imply `allow-oom` -* Before Redis OSS 7.0.1 the `no-writes` flag did not permit the script to run during write pauses. - - -The recommended approach is to use the standard scripting commands with the `no-writes` flag unless you need one of the previously mentioned features. - -## Sandboxed script context - -Valkey places the engine that executes user scripts inside a sandbox. -The sandbox attempts to prevent accidental misuse and reduce potential threats from the server's environment. - -Scripts should never try to access the Valkey server's underlying host systems, such as the file system, network, or attempt to perform any other system call other than those supported by the API. - -Scripts should operate solely on data stored in Valkey and data provided as arguments to their execution. - -## Maximum execution time - -Scripts are subject to a maximum execution time (set by default to five seconds). -This default timeout is enormous since a script usually runs in less than a millisecond. -The limit is in place to handle accidental infinite loops created during development. - -It is possible to modify the maximum time a script can be executed with millisecond precision, -either via `valkey.conf` or by using the `CONFIG SET` command. -The configuration parameter affecting max execution time is called `busy-reply-threshold`. - -When a script reaches the timeout threshold, it isn't terminated by Valkey automatically. -Doing so would violate the contract between Valkey and the scripting engine that ensures that scripts are atomic. -Interrupting the execution of a script has the potential of leaving the dataset with half-written changes. - -Therefore, when a script executes longer than the configured timeout, the following happens: - -* Valkey logs that a script is running for too long. -* It starts accepting commands again from other clients but will reply with a BUSY error to all the clients sending normal commands. A few commands allowed in this state are those that manage the connection, control the busy state, or modify client metadata, such as `SCRIPT KILL`, `FUNCTION KILL`, `SHUTDOWN NOSAVE`, `AUTH`, `HELLO`, `QUIT`, `RESET`, `SELECT`, and various `CLIENT` sub-commands. -* It is possible to terminate a script that only executes read-only commands using the `SCRIPT KILL` and `FUNCTION KILL` commands. These commands do not violate the scripting semantic as no data was written to the dataset by the script yet. -* If the script had already performed even a single write operation, the only command allowed is `SHUTDOWN NOSAVE` that stops the server without saving the current data set on disk (basically, the server is aborted). diff --git a/topics/protocol.md b/topics/protocol.md deleted file mode 100644 index c79eb6f6..00000000 --- a/topics/protocol.md +++ /dev/null @@ -1,709 +0,0 @@ ---- -title: "Serialization protocol specification" -description: Valkey's serialization protocol (RESP) is the wire protocol that clients implement ---- - -To communicate with the Valkey server, Valkey clients use a protocol called REdis Serialization Protocol (RESP). -The protocol was designed for Redis and is used by many other client-server software projects. - -This page is for client authors. -If you're looking for an existing client, see the [client libraries](../clients/). - -RESP is a compromise among the following considerations: - -* Simple to implement. -* Fast to parse. -* Human readable. - -RESP can serialize different data types including integers, strings, and arrays. -It also features an error-specific type. -A client sends a request to the Valkey server as an array of strings. -The array's contents are the command and its arguments that the server should execute. -The server's reply type is command-specific. - -RESP is binary-safe and uses prefixed length to transfer bulk data so it does not require processing bulk data transferred from one process to another. - -**Note:** -The protocol outlined here is used only for client-server communication. -[Valkey Cluster](cluster-spec.md) uses a different binary protocol for exchanging messages between nodes. - -## RESP versions - -The first version of the RESP protocol was experimental and was never widely used. - -The next version, RESP2, became the standard communication method for clients early on. - -[RESP3](https://github.com/redis/redis-specifications/blob/master/protocol/RESP3.md) is a superset of RESP2 that aims to make a client author's life a little easier. -Valkey supports RESP3's features (excluding streaming strings and streaming aggregates) alongside RESP2. -The `HELLO` command lets clients handshake and upgrade the connection's protocol version (see [Client handshake](#client-handshake)). - -Both RESP2 and RESP3 clients can invoke all core commands. Depending on what RESP version you are using, your commands may return different replies based on the different protocol versions used. - -Future versions of Valkey may change the default protocol version, but it is unlikely that RESP2 will become entirely deprecated. -It is possible, however, that new features in upcoming versions will require the use of RESP3. - -## Network layer -A client connects to a Valkey server by creating a TCP connection to its port (the default is 6379). - -While RESP is technically non-TCP specific, the protocol is used exclusively with TCP connections (or equivalent stream-oriented connections like Unix sockets) in the context of Valkey. - -## Request-Response model -The Valkey server accepts commands composed of different arguments. -Then, the server processes the command and sends the reply back to the client. - -This is the simplest model possible; however, there are some exceptions: - -* Valkey requests can be [pipelined](#multiple-commands-and-pipelining). - Pipelining enables clients to send multiple commands at once and wait for replies later. -* When a RESP2 connection subscribes to a [Pub/Sub](pubsub.md) channel, the protocol changes semantics and becomes a *push* protocol. - The client no longer requires sending commands because the server will automatically send new messages to the client (for the channels the client is subscribed to) as soon as they are received. -* The `MONITOR` command. - Invoking the `MONITOR` command switches the connection to an ad-hoc push mode. - The protocol of this mode is not specified but is obvious to parse. -* [Protected mode](security.md#protected-mode). - Connections opened from a non-loopback address to a Valkey while in protected mode are denied and terminated by the server. - Before terminating the connection, Valkey unconditionally sends a `-DENIED` reply, regardless of whether the client writes to the socket. -* The [RESP3 Push type](#pushes). - As the name suggests, a push type allows the server to send out-of-band data to the connection. - The server may push data at any time, and the data isn't necessarily related to specific commands executed by the client. -* When RESP3 is used, the commands `SUBSCRIBE`, `UNSUBSCRIBE` and their pattern and sharded variants, - return either an error reply *or one or more Push replies, without any regular in-band reply*. - This is considered a design mistake of these commands but the behaviour is kept for backward compatibility. - Clients need to compensate for this behaviour. - -Excluding these exceptions, the Valkey protocol is a simple request-response protocol. - -## RESP protocol description -RESP is essentially a serialization protocol that supports several data types. -In RESP, the first byte of data determines its type. - -Valkey generally uses RESP as a [request-response](#request-response-model) protocol in the following way: - -* Clients send commands to a Valkey server as an [array](#arrays) of [bulk strings](#bulk-strings). - The first (and sometimes also the second) bulk string in the array is the command's name. - Subsequent elements of the array are the arguments for the command. -* The server replies with a RESP type. - The reply's type is determined by the command's implementation and possibly by the client's protocol version. - -RESP is a binary protocol that uses control sequences encoded in standard ASCII. -The `A` character, for example, is encoded with the binary byte of value 65. -Similarly, the characters CR (`\r`), LF (`\n`) and SP (` `) have binary byte values of 13, 10 and 32, respectively. - -The `\r\n` (CRLF) is the protocol's _terminator_, which **always** separates its parts. - -The first byte in an RESP-serialized payload always identifies its type. -Subsequent bytes constitute the type's contents. - -We categorize every RESP data type as either _simple_, _bulk_ or _aggregate_. - -Simple types are similar to scalars in programming languages that represent plain literal values. Booleans and Integers are such examples. - -RESP strings are either _simple_ or _bulk_. -Simple strings never contain carriage return (`\r`) or line feed (`\n`) characters. -Bulk strings can contain any binary data and may also be referred to as _binary_ or _blob_. -Note that bulk strings may be further encoded and decoded, e.g. with a wide multi-byte encoding, by the client. - -Aggregates, such as Arrays and Maps, can have varying numbers of sub-elements and nesting levels. - -The following table summarizes the RESP data types that Valkey supports: - -| RESP data type | Minimal protocol version | Category | First byte | -| --- | --- | --- | --- | -| [Simple strings](#simple-strings) | RESP2 | Simple | `+` | -| [Simple Errors](#simple-errors) | RESP2 | Simple | `-` | -| [Integers](#integers) | RESP2 | Simple | `:` | -| [Bulk strings](#bulk-strings) | RESP2 | Aggregate | `$` | -| [Arrays](#arrays) | RESP2 | Aggregate | `*` | -| [Nulls](#nulls) | RESP3 | Simple | `_` | -| [Booleans](#booleans) | RESP3 | Simple | `#` | -| [Doubles](#doubles) | RESP3 | Simple | `,` | -| [Big numbers](#big-numbers) | RESP3 | Simple | `(` | -| [Bulk errors](#bulk-errors) | RESP3 | Aggregate | `!` | -| [Verbatim strings](#verbatim-strings) | RESP3 | Aggregate | `=` | -| [Maps](#maps) | RESP3 | Aggregate | `%` | -| [Sets](#sets) | RESP3 | Aggregate | `~` | -| [Pushes](#pushes) | RESP3 | Aggregate | `>` | -| [Attributes](#attributes) | RESP3 | Aggregate | `\|` | - -### Simple strings -Simple strings are encoded as a plus (`+`) character, followed by a string. -The string mustn't contain a CR (`\r`) or LF (`\n`) character and is terminated by CRLF (i.e., `\r\n`). - -Simple strings transmit short, non-binary strings with minimal overhead. -For example, many Valkey commands reply with just "OK" on success. -The encoding of this Simple String is the following 5 bytes: - - +OK\r\n - -When Valkey replies with a simple string, a client library should return to the caller a string value composed of the first character after the `+` up to the end of the string, excluding the final CRLF bytes. - -To send binary strings, use [bulk strings](#bulk-strings) instead. - -### Simple errors -RESP has specific data types for errors. -Simple errors, or simply just errors, are similar to [simple strings](#simple-strings), but their first character is the minus (`-`) character. -The difference between simple strings and errors in RESP is that clients should treat errors as exceptions, whereas the string encoded in the error type is the error message itself. - -The basic format is: - - -Error message\r\n - -Valkey replies with an error only when something goes wrong, for example, when you try to operate against the wrong data type, or when the command does not exist. -The client should raise an exception when it receives an Error reply. - -The following are examples of error replies: - - -ERR unknown command 'asdf' - -WRONGTYPE Operation against a key holding the wrong kind of value - -The first upper-case word after the `-`, up to the first space or newline, represents the kind of error returned. -This word is called an _error prefix_. -Note that the error prefix is a convention used by Valkey rather than part of the RESP error type. - -For example, in Valkey, `ERR` is a generic error, whereas `WRONGTYPE` is a more specific error that implies that the client attempted an operation against the wrong data type. -The error prefix allows the client to understand the type of error returned by the server without checking the exact error message. - -A client implementation can return different types of exceptions for various errors, or provide a generic way for trapping errors by directly providing the error name to the caller as a string. - -However, such a feature should not be considered vital as it is rarely useful. -Also, simpler client implementations can return a generic error value, such as `false`. - -### Integers -This type is a CRLF-terminated string that represents a signed, base-10, 64-bit integer. - -RESP encodes integers in the following way: - - :[<+|->]\r\n - -* The colon (`:`) as the first byte. -* An optional plus (`+`) or minus (`-`) as the sign. -* One or more decimal digits (`0`..`9`) as the integer's unsigned, base-10 value. -* The CRLF terminator. - -For example, `:0\r\n` and `:1000\r\n` are integer replies (of zero and one thousand, respectively). - -Many Valkey commands return RESP integers, including `INCR`, `LLEN`, and `LASTSAVE`. -An integer, by itself, has no special meaning other than in the context of the command that returned it. -For example, it is an incremental number for `INCR`, a UNIX timestamp for `LASTSAVE`, and so forth. -However, the returned integer is guaranteed to be in the range of a signed 64-bit integer. - -In some cases, integers can represent true and false Boolean values. -For instance, `SISMEMBER` returns 1 for true and 0 for false. - -Other commands, including `SADD`, `SREM`, and `SETNX`, return 1 when the data changes and 0 otherwise. - -### Bulk strings -A bulk string represents a single binary string. -The string can be of any size, but by default, Valkey limits it to 512 MB (see the `proto-max-bulk-len` configuration directive). - -RESP encodes bulk strings in the following way: - - $\r\n\r\n - -* The dollar sign (`$`) as the first byte. -* One or more decimal digits (`0`..`9`) as the string's length, in bytes, as an unsigned, base-10 value. -* The CRLF terminator. -* The data. -* A final CRLF. - -So the string "hello" is encoded as follows: - - $5\r\nhello\r\n - -The empty string's encoding is: - - $0\r\n\r\n - - - -### Arrays -Clients send commands to the Valkey server as RESP arrays. -Similarly, some Valkey commands that return collections of elements use arrays as their replies. -An example is the `LRANGE` command that returns elements of a list. - -RESP Arrays' encoding uses the following format: - - *\r\n... - -* An asterisk (`*`) as the first byte. -* One or more decimal digits (`0`..`9`) as the number of elements in the array as an unsigned, base-10 value. -* The CRLF terminator. -* An additional RESP type for every element of the array. - -So an empty Array is just the following: - - *0\r\n - -Whereas the encoding of an array consisting of the two bulk strings "hello" and "world" is: - - *2\r\n$5\r\nhello\r\n$5\r\nworld\r\n - -As you can see, after the `*CRLF` part prefixing the array, the other data types that compose the array are concatenated one after the other. -For example, an Array of three integers is encoded as follows: - - *3\r\n:1\r\n:2\r\n:3\r\n - -Arrays can contain mixed data types. -For instance, the following encoding is of a list of four integers and a bulk string: - - *5\r\n - :1\r\n - :2\r\n - :3\r\n - :4\r\n - $5\r\n - hello\r\n - -(The raw RESP encoding is split into multiple lines for readability). - -The first line the server sent is `*5\r\n`. -This numeric value tells the client that five reply types are about to follow it. -Then, every successive reply constitutes an element in the array. - -All of the aggregate RESP types support nesting. -For example, a nested array of two arrays is encoded as follows: - - *2\r\n - *3\r\n - :1\r\n - :2\r\n - :3\r\n - *2\r\n - +Hello\r\n - -World\r\n - -(The raw RESP encoding is split into multiple lines for readability). - -The above encodes a two-element array. -The first element is an array that, in turn, contains three integers (1, 2, 3). -The second element is another array containing a simple string and an error. - -**Note:** -In some places, the RESP Array type may be referred to as _multi bulk_. -The two are the same. - -### Nulls -The null data type represents non-existent values. - -In RESP3, null is encoded using the underscore (`_`) character, followed by the CRLF terminator (`\r\n`). -Here's null's raw RESP encoding: - - _\r\n - -RESP2 features two specially crafted values for representing null values, -known as "null bulk strings" and "null arrays". -This duality has always been a redundancy that added zero semantical value to the protocol itself. -The null type, introduced in RESP3, aims to fix this wrong. -Clients should handle all these representations of null in the same way. -For example, a Ruby library should return `nil` while a C library should return `NULL` (or set a special flag in the reply object). - -#### Null bulk strings -Whereas RESP3 has a dedicated data type for [null values](#nulls), RESP2 has no such type. -Instead, due to historical reasons, the representation of null values in RESP2 is via predetermined forms of the [bulk strings](#bulk-strings) and [arrays](#arrays) types. - -The null bulk string represents a non-existing value. -The `GET` command returns the Null Bulk String when the target key doesn't exist. - -It is encoded as a bulk string with the length of negative one (-1), like so: - - $-1\r\n - -A Valkey client should return a nil object when the server replies with a null bulk string rather than the empty string. - -#### Null arrays -Whereas RESP3 has a dedicated data type for [null values](#nulls), RESP2 has no such type. Instead, due to historical reasons, the representation of null values in RESP2 is via predetermined forms of the [Bulk Strings](#bulk-strings) and [arrays](#arrays) types. - -Null arrays exist as an alternative way of representing a null value. -For instance, when the `BLPOP` command times out, it returns a null array. - -The encoding of a null array is that of an array with the length of -1, i.e. - - *-1\r\n - -When Valkey replies with a null array, the client should return a null object rather than an empty array. - -#### Null elements in arrays -Single elements of an array may be [null](#nulls). -This is used in Valkey replies to signal that these elements are missing and not empty strings. This can happen, for example, with the `SORT` command when used with the `GET pattern` option -if the specified key is missing. - -Here's an example of an array reply containing a null element, represented as a RESP2 null bulk string: - - *3\r\n - $5\r\n - hello\r\n - $-1\r\n - $5\r\n - world\r\n - -Above, the second element is null. -The client library should return to its caller something like this: - - ["hello",nil,"world"] - -### Booleans -RESP booleans are encoded as follows: - - #\r\n - -* The octothorpe character (`#`) as the first byte. -* A `t` character for true values, or an `f` character for false ones. -* The CRLF terminator. - -### Doubles -The Double RESP type encodes a double-precision floating point value. -Doubles are encoded as follows: - - ,[<+|->][.][[sign]]\r\n - -* The comma character (`,`) as the first byte. -* An optional plus (`+`) or minus (`-`) as the sign. -* One or more decimal digits (`0`..`9`) as an unsigned, base-10 integral value. -* An optional dot (`.`), followed by one or more decimal digits (`0`..`9`) as an unsigned, base-10 fractional value. -* An optional capital or lowercase letter E (`E` or `e`), followed by an optional plus (`+`) or minus (`-`) as the exponent's sign, ending with one or more decimal digits (`0`..`9`) as an unsigned, base-10 exponent value. -* The CRLF terminator. - -Here's the encoding of the number 1.23: - - ,1.23\r\n - -Because the fractional part is optional, the integer value of ten (10) can, therefore, be RESP-encoded both as an integer as well as a double: - - :10\r\n - ,10\r\n - -In such cases, the Valkey client should return native integer and double values, respectively, providing that these types are supported by the language of its implementation. - -The positive infinity, negative infinity and NaN values are encoded as follows: - - ,inf\r\n - ,-inf\r\n - ,nan\r\n - - - -### Big numbers -This type can encode integer values outside the range of signed 64-bit integers. - -Big numbers use the following encoding: - - ([+|-]\r\n - -* The left parenthesis character (`(`) as the first byte. -* An optional plus (`+`) or minus (`-`) as the sign. -* One or more decimal digits (`0`..`9`) as an unsigned, base-10 value. -* The CRLF terminator. - -Example: - - (3492890328409238509324850943850943825024385\r\n - -Big numbers can be positive or negative but can't include fractionals. -Client libraries written in languages with a big number type should return a big number. -When big numbers aren't supported, the client should return a string and, when possible, signal to the caller that the reply is a big integer (depending on the API used by the client library). - -### Bulk errors -This type combines the purpose of [simple errors](#simple-errors) with the expressive power of [bulk strings](#bulk-strings). - -It is encoded as: - - !\r\n\r\n - -* An exclamation mark (`!`) as the first byte. -* One or more decimal digits (`0`..`9`) as the error's length, in bytes, as an unsigned, base-10 value. -* The CRLF terminator. -* The error itself. -* A final CRLF. - -As a convention, the error begins with an uppercase (space-delimited) word that conveys the error message. - -For instance, the error "SYNTAX invalid syntax" is represented by the following protocol encoding: - - !21\r\n - SYNTAX invalid syntax\r\n - -(The raw RESP encoding is split into multiple lines for readability). - -### Verbatim strings -This type is similar to the [bulk string](#bulk-strings), with the addition of providing a hint about the data's encoding. - -A verbatim string's RESP encoding is as follows: - - =\r\n:\r\n - -* An equal sign (`=`) as the first byte. -* One or more decimal digits (`0`..`9`) as the string's total length, in bytes, as an unsigned, base-10 value. -* The CRLF terminator. -* Exactly three (3) bytes represent the data's encoding. -* The colon (`:`) character separates the encoding and data. -* The data. -* A final CRLF. - -Example: - - =15\r\n - txt:Some string\r\n - -(The raw RESP encoding is split into multiple lines for readability). - -Some client libraries may ignore the difference between this type and the string type and return a native string in both cases. -However, interactive clients, such as command line interfaces (e.g., [`valkey-cli`](cli.md)), can use this type and know that their output should be presented to the human user as is and without quoting the string. - -For example, the Valkey command `INFO` outputs a report that includes newlines. -When using RESP3, `valkey-cli` displays it correctly because it is sent as a Verbatim String reply (with its three bytes being "txt"). -When using RESP2, however, the `valkey-cli` is hard-coded to look for the `INFO` command to ensure its correct display to the user. - -### Maps -The RESP map encodes a collection of key-value tuples, i.e., a dictionary or a hash. - -It is encoded as follows: - - %\r\n... - -* A percent character (`%`) as the first byte. -* One or more decimal digits (`0`..`9`) as the number of entries, or key-value tuples, in the map as an unsigned, base-10 value. -* The CRLF terminator. -* Two additional RESP types for every key and value in the map. - -For example, the following JSON object: - - { - "first": 1, - "second": 2 - } - -Can be encoded in RESP like so: - - %2\r\n - +first\r\n - :1\r\n - +second\r\n - :2\r\n - -(The raw RESP encoding is split into multiple lines for readability). - -Both map keys and values can be any of RESP's types. - -Valkey clients should return the idiomatic dictionary type that their language provides. -However, low-level programming languages (such as C, for example) will likely return an array along with type information that indicates to the caller that it is a dictionary. - -**Note:** -RESP2 doesn't have a map type. -A map in RESP2 is represented by a flat array containing the keys and the values. -The first element is a key, followed by the corresponding value, then the next key and so on, like this: -`key1, value1, key2, value2, ...`. - -### Sets -Sets are somewhat like [Arrays](#arrays) but are unordered and should only contain unique elements. - -RESP set's encoding is: - - ~\r\n... - -* A tilde (`~`) as the first byte. -* One or more decimal digits (`0`..`9`) as the number of elements in the set as an unsigned, base-10 value. -* The CRLF terminator. -* An additional RESP type for every element of the Set. - -Clients should return the native set type if it is available in their programming language. -Alternatively, in the absence of a native set type, an array coupled with type information can be used (in C, for example). - - - -### Pushes -RESP's pushes contain out-of-band data. -They are an exception to the protocol's request-response model and provide a generic _push mode_ for connections. - -Push events are encoded similarly to [arrays](#arrays), differing only in their first byte: - - >\r\n... - -* A greater-than sign (`>`) as the first byte. -* One or more decimal digits (`0`..`9`) as the number of elements in the message as an unsigned, base-10 value. -* The CRLF terminator. -* An additional RESP type for every element of the push event. - -Pushed data may precede or follow any of RESP's data types but never inside them. -That means a client won't find push data in the middle of a map reply, for example. -It also means that pushed data may appear before or after a command's reply, as well as by itself (without calling any command). - -Clients should react to pushes by invoking a callback that implements their handling of the pushed data. - - - -### Attributes -An attribute carries auxiliary data about the reply that follows it. -It isn't the reply itself. - -Attributes are encoded like [maps](#maps), differing only in their first byte: - - |\r\n... - -* A pipe character (`|`) as the first byte. -* One or more decimal digits (`0`..`9`) as the number of entries, or key-value tuples, in the attribute as an unsigned, base-10 value. -* The CRLF terminator. -* Two additional RESP types for every key and value in the attribute. - -The reply follows the attribute's last value and isn't counted in the number of entries. -For example, `DEBUG PROTOCOL attrib` replies to a RESP3 connection with an attribute of one entry, followed by a bulk string reply: - - |1\r\n - $14\r\n - key-popularity\r\n - *2\r\n - $7\r\n - key:123\r\n - :90\r\n - $39\r\n - Some real reply following the attribute\r\n - -(The raw RESP encoding is split into multiple lines for readability). - -An attribute can also precede an element of an aggregate, such as one of the replies in an `EXEC` reply, and isn't counted in the aggregate's number of elements. - -Clients should return the value that follows the attribute as usual, and either expose the attribute separately or discard it. - -Attributes are RESP3 only. -On a RESP2 connection, `DEBUG PROTOCOL attrib` replies with only the bulk string, and `ValkeyModule_ReplyWithAttribute` returns `VALKEYMODULE_ERR` instead of adding an attribute. - -## Client handshake -New RESP connections should begin the session by calling the `HELLO` command. -This practice accomplishes two things: - -1. It allows servers to be backward compatible with RESP2 versions. - This is needed in Valkey to make the transition to version 3 of the protocol gentler. -2. The `HELLO` command returns information about the server and the protocol that the client can use for different goals. - -The `HELLO` command has the following high-level syntax: - - HELLO [optional-arguments] - -The first argument of the command is the protocol version we want the connection to be set. -By default, the connection starts in RESP2 mode. -If we specify a connection version that is too big and unsupported by the server, it should reply with a `-NOPROTO` error. Example: - - Client: HELLO 4 - Server: -NOPROTO sorry, this protocol version is not supported. - -At that point, the client may retry with a lower protocol version. - -Similarly, the client can easily detect a server that is only able to speak RESP2: - - Client: HELLO 3 - Server: -ERR unknown command 'HELLO' - -The client can then proceed and use RESP2 to communicate with the server. - -Note that even if the protocol's version is supported, the `HELLO` command may return an error, perform no action and remain in RESP2 mode. -For example, when used with invalid authentication credentials in the command's optional `!AUTH` clause: - - Client: HELLO 3 AUTH default mypassword - Server: -ERR invalid password - (the connection remains in RESP2 mode) - -A successful reply to the `HELLO` command is a map reply. -The information in the reply is partly server-dependent, but certain fields are mandatory for all the RESP3 implementations: -* **server**: "redis" (or other software name). -* **version**: the server's version. -* **proto**: the highest supported version of the RESP protocol. - -In Valkey's RESP3 implementation, the following fields are also emitted: - -* **id**: the connection's identifier (ID). -* **mode**: "standalone", "sentinel" or "cluster". -* **role**: "master" or "replica". -* **modules**: list of loaded modules as an Array of Bulk Strings. - -## Sending commands to a Valkey server -Now that you are familiar with the RESP serialization format, you can use it to help write a Valkey client library. -We can further specify how the interaction between the client and the server works: - -* A client sends the Valkey server an [array](#arrays) consisting of only bulk strings. -* A Valkey server replies to clients, sending any valid RESP data type as a reply. - -So, for example, a typical interaction could be the following. - -The client sends the command `LLEN mylist` to get the length of the list stored at the key _mylist_. -Then the server replies with an [integer](#integers) reply as in the following example (`C:` is the client, `S:` the server). - - C: *2\r\n - C: $4\r\n - C: LLEN\r\n - C: $6\r\n - C: mylist\r\n - - S: :48293\r\n - -As usual, we separate different parts of the protocol with newlines for simplicity, but the actual interaction is the client sending `*2\r\n$4\r\nLLEN\r\n$6\r\nmylist\r\n` as a whole. - -## Multiple commands and pipelining -A client can use the same connection to issue multiple commands. -Pipelining is supported, so multiple commands can be sent with a single write operation by the client. -The client can skip reading replies and continue to send the commands one after the other. -All the replies can be read at the end. - -For more information, see [Pipelining](pipelining.md). - -## Inline commands -Sometimes you may need to send a command to the Valkey server but only have `telnet` available. -While the Valkey protocol is simple to implement, it is not ideal for interactive sessions, and `valkey-cli` may not always be available. -For this reason, Valkey also accepts commands in the _inline command_ format. - -The following example demonstrates a server/client exchange using an inline command (the server chat starts with `S:`, the client chat with `C:`): - - C: PING - S: +PONG - -Here's another example of an inline command where the server returns an integer: - - C: EXISTS somekey - S: :0 - -Basically, to issue an inline command, you write space-separated arguments in a telnet session. -Since no command starts with `*` (the identifying byte of RESP Arrays), Valkey detects this condition and parses your command inline. - -## High-performance parser for the Valkey protocol - -While the Valkey protocol is human-readable and easy to implement, its implementation can exhibit performance similar to that of a binary protocol. - -RESP uses prefixed lengths to transfer bulk data. -That makes scanning the payload for special characters unnecessary (unlike parsing JSON, for example). -For the same reason, quoting and escaping the payload isn't needed. - -Reading the length of aggregate types (for example, bulk strings or arrays) can be processed with code that performs a single operation per character while at the same time scanning for the CR character. - -Example (in C): - -```c -#include - -int main(void) { - unsigned char *p = "$123\r\n"; - int len = 0; - - p++; - while(*p != '\r') { - len = (len*10)+(*p - '0'); - p++; - } - - /* Now p points at '\r', and the len is in bulk_len. */ - printf("%d\n", len); - return 0; -} -``` - -After the first CR is identified, it can be skipped along with the following LF without further processing. -Then, the bulk data can be read with a single read operation that doesn't inspect the payload in any way. -Finally, the remaining CR and LF characters are discarded without additional processing. - -While comparable in performance to a binary protocol, the Valkey protocol is significantly more straightforward to implement in most high-level languages, reducing the number of bugs in client software. - -## Tips for Valkey client authors - -* For testing purposes, use [Lua's type conversions](lua-api.md#lua-to-resp3-type-conversion) to have Valkey reply with any RESP2/RESP3 needed. - As an example, a RESP3 double can be generated like so: - ``` - EVAL "return { double = tonumber(ARGV[1]) }" 0 1e0 - ``` - diff --git a/topics/pubsub.md b/topics/pubsub.md deleted file mode 100644 index aa69dcdc..00000000 --- a/topics/pubsub.md +++ /dev/null @@ -1,191 +0,0 @@ ---- -title: Pub/Sub -description: How to use pub/sub channels in Valkey ---- - -`SUBSCRIBE`, `UNSUBSCRIBE` and `PUBLISH` implement the [Publish/Subscribe messaging paradigm](https://en.wikipedia.org/wiki/Publish/subscribe) where publishers send their messages to channels, without knowledge of what receivers (subscribers) there may be. -Subscribers express interest in one or more channels and only receive messages that are of interest, without knowledge of what (if any) publishers there are. -This decoupling of publishers and subscribers allows for greater scalability and a more dynamic network topology. - -Pubsub channels are not persisted. If there are no subscribes to a channel when a message is published, the message is lost. -If you're looking for persisted messages queues, you may want to look into [Streams](streams-intro.md) instead. - -To subscribe to channels "channel11" and "ch:00" the client issues a `SUBSCRIBE` providing the names of the channels: - -```bash -SUBSCRIBE channel11 ch:00 -``` - -Messages sent by other clients to these channels will be pushed by Valkey to all the subscribed clients. -Subscribers receive the messages in the order that the messages are published. - -A client subscribed to one or more channels shouldn't issue commands, although it can `SUBSCRIBE` and `UNSUBSCRIBE` to and from other channels. -The replies to subscription and unsubscribing operations are sent in the form of messages so that the client can just read a coherent stream of messages where the first element indicates the type of message. -The commands that are allowed in the context of a subscribed RESP2 client are: - -* `PING` -* `PSUBSCRIBE` -* `PUNSUBSCRIBE` -* `QUIT` -* `RESET` -* `SSUBSCRIBE` -* `SUBSCRIBE` -* `SUNSUBSCRIBE` -* `UNSUBSCRIBE` - -However, if RESP3 is used (see `HELLO`), a client can issue any commands while in the subscribed state. - -Please note that when using `valkey-cli`, in subscribed mode commands such as `UNSUBSCRIBE` and `PUNSUBSCRIBE` cannot be used because `valkey-cli` will not accept any commands and can only quit the mode with `Ctrl-C`. - -## Delivery semantics - -Valkey' Pub/Sub exhibits _at-most-once_ message delivery semantics. -As the name suggests, it means that a message will be delivered once if at all. -Once the message is sent by the Valkey server, there's no chance of it being sent again. -If the subscriber is unable to handle the message (for example, due to an error or a network disconnect) the message is forever lost. - -If your application requires stronger delivery guarantees, you may want to learn about [Streams](streams-intro.md). -Messages in streams are persisted, and support both _at-most-once_ as well as _at-least-once_ delivery semantics. - -## Format of pushed messages - -A message is an [array-reply](protocol.md#arrays) with three elements. - -The first element is the kind of message: - -* `subscribe`: means that we successfully subscribed to the channel given as the second element in the reply. - The third argument represents the number of channels we are currently subscribed to. - -* `unsubscribe`: means that we successfully unsubscribed from the channel given as second element in the reply. - The third argument represents the number of channels we are currently subscribed to. - When the last argument is zero, we are no longer subscribed to any channel, and the client can issue any kind of Valkey command as we are outside the Pub/Sub state. - -* `message`: it is a message received as a result of a `PUBLISH` command issued by another client. - The second element is the name of the originating channel, and the third argument is the actual message payload. - -## Database & Scoping - -Pub/Sub has no relation to the key space. -It was made to not interfere with it on any level, including database numbers. - -Publishing on db 10, will be heard by a subscriber on db 1. - -If you need scoping of some kind, prefix the channels with the name of the environment (test, staging, production...). - -## Wire protocol example - -``` -SUBSCRIBE first second -*3 -$9 -subscribe -$5 -first -:1 -*3 -$9 -subscribe -$6 -second -:2 -``` - -At this point, from another client we issue a `PUBLISH` operation against the channel named `second`: - -``` -> PUBLISH second Hello -``` - -This is what the first client receives: - -``` -*3 -$7 -message -$6 -second -$5 -Hello -``` - -Now the client unsubscribes itself from all the channels using the `UNSUBSCRIBE` command without additional arguments: - -``` -UNSUBSCRIBE -*3 -$11 -unsubscribe -$6 -second -:1 -*3 -$11 -unsubscribe -$5 -first -:0 -``` - -## Pattern-matching subscriptions - -The Valkey Pub/Sub implementation supports pattern matching. -Clients may subscribe to glob-style patterns to receive all the messages sent to channel names matching a given pattern. - -For instance: - -``` -PSUBSCRIBE news.* -``` - -Will receive all the messages sent to the channel `news.art.figurative`, `news.music.jazz`, etc. -All the glob-style patterns are valid, so multiple wildcards are supported. - -``` -PUNSUBSCRIBE news.* -``` - -Will then unsubscribe the client from that pattern. -No other subscriptions will be affected by this call. - -Messages received as a result of pattern matching are sent in a different format: - -* The type of the message is `pmessage`: it is a message received as a result from a `PUBLISH` command issued by another client, matching a pattern-matching subscription. - The second element is the original pattern matched, the third element is the name of the originating channel, and the last element is the actual message payload. - -Similarly to `SUBSCRIBE` and `UNSUBSCRIBE`, `PSUBSCRIBE` and `PUNSUBSCRIBE` commands are acknowledged by the system sending a message of type `psubscribe` and `punsubscribe` using the same format as the `subscribe` and `unsubscribe` message format. - -## Messages matching both a pattern and a channel subscription - -A client may receive a single message multiple times if it's subscribed to multiple patterns matching a published message, or if it is subscribed to both patterns and channels matching the message. -This is shown by the following example: - -``` -SUBSCRIBE foo -PSUBSCRIBE f* -``` - -In the above example, if a message is sent to channel `foo`, the client will receive two messages: one of type `message` and one of type `pmessage`. - -## The meaning of the subscription count with pattern matching - -In `subscribe`, `unsubscribe`, `psubscribe` and `punsubscribe` message types, the last argument is the count of subscriptions still active. -This number is the total number of channels and patterns the client is still subscribed to. -So the client will exit the Pub/Sub state only when this count drops to zero as a result of unsubscribing from all the channels and patterns. - -## Sharded Pub/Sub - -From Redis OSS 7.0, sharded Pub/Sub is introduced in which shard channels are assigned to slots by the same algorithm used to assign keys to slots. -A shard message must be sent to a node that owns the slot the shard channel is hashed to. -The cluster makes sure the published shard messages are forwarded to all nodes in the shard, so clients can subscribe to a shard channel by connecting to either the primary responsible for the slot, or to any of its replicas. -`SSUBSCRIBE`, `SUNSUBSCRIBE` and `SPUBLISH` are used to implement sharded Pub/Sub. - -Sharded Pub/Sub helps to scale the usage of Pub/Sub in cluster mode. -It restricts the propagation of messages to be within the shard of a cluster. -Hence, the amount of data passing through the cluster bus is limited in comparison to global Pub/Sub where each message propagates to each node in the cluster. -This allows users to horizontally scale the Pub/Sub usage by adding more shards. - -## Client library implementation hints - -Because all the messages received contain the original subscription causing the message delivery (the channel in the case of message type, and the original pattern in the case of pmessage type) client libraries may bind the original subscription to callbacks (that can be anonymous functions, blocks, function pointers), using a hash table. - -When a message is received an O(1) lookup can be done to deliver the message to the registered callback. diff --git a/topics/quickstart.md b/topics/quickstart.md deleted file mode 100644 index 1cc25385..00000000 --- a/topics/quickstart.md +++ /dev/null @@ -1,118 +0,0 @@ ---- -title: "Quick start guide" -description: Understand how to use basic Valkey data types ---- - -## Getting Started with Valkey - -### What is Valkey? - -Valkey is a fully open-source, in-memory data store backed by the Linux Foundation, offering microsecond-latency operations on rich data structures. See the [Introduction](introduction.md) for more. - -### Installation and Setup - -Getting Valkey up and running is straightforward. See the [Installation Guide](installation.md) for detailed instructions. - -If you just want to try Valkey quickly, head over to [Try-Valkey](https://valkey.io/try-valkey/) — an interactive playground where you can run any Valkey command right in your browser. - -### Data Operations - -Once connected with Valkey, you can interact by issuing commands to store and retrieve data. Valkey behaves like a **remote dictionary** – you can think of it as a giant hash map on a server. Each piece of data is stored under a unique **key**, and you use commands to read or modify values associated with those keys. - -Let’s walk through some fundamental operations with two of the most commonly used data types in Valkey, **strings** and **hashes**, using [`valkey-cli`](cli.md), the Valkey command line interface. - -* **Strings:** The simplest data type in Valkey is a string (binary-safe sequence of bytes). You can store text or binary data under a key. For example, to store a string value and then retrieve it: - -``` -127.0.0.1:6379> SET user:1000 "Alice" -OK -127.0.0.1:6379> GET user:1000 -"Alice" -``` - -Here we use the `SET` command to save the value `"Alice"` under the key `user:1000`, and `GET` to fetch it back. Valkey keys are often namespaced with prefixes (like `user:`) to group related items. You can store any data serialized as a string – numbers, JSON, binary blobs, etc. (Up to 512 MB per value, though very large values are not recommended for performance). - -* **Hashes:** Hashes allow you to store multiple fields and values under one key, similar to a JSON object or dictionary. This is useful for representing objects without using separate keys for each field. For example: - -``` -127.0.0.1:6379> HSET user:1000 name "Alice" email "alice@example.com" age "30" -(integer) 3 -127.0.0.1:6379> HGET user:1000 name -"Alice" -127.0.0.1:6379> HGETALL user:1000 -1) "name" -2) "Alice" -3) "email" -4) "alice@example.com" -5) "age" -6) "30" -``` - -We add three fields to the hash stored at `user:1000`. `HGET` retrieves a single field, and `HGETALL` returns all fields and values. Hashes are memory-efficient for storing structured data. - -* **Other Data Types:** Valkey supports many other native data structures. For example, **lists** (ordered collections of elements) support queue/stack operations, **sets** store unique items (useful for tags or unique lists), **sorted sets** maintain ordered rankings, and more. Each data type comes with specialized commands (e.g. `LPUSH`/`LRANGE` for lists, `SADD`/`SMEMBERS` for sets). You can find a full overview in the [Valkey data types documentation](data-types.md) and the command reference. - -### Example Use Case: Caching with Valkey - -One of the most popular ways to use Valkey is as a caching layer in front of a traditional database or expensive API. By caching results in Valkey, applications can serve repeated requests much faster and reduce load on back-end systems. - -**Scenario:** Imagine a web application that needs to fetch user profile data from a database. Without caching, each page load would query the database, making the app slow under load. With Valkey, you can cache the user data after the first retrieval: - -1. **Check cache first:** On a user profile request, the application first checks Valkey (using a key like `user:42:profile`) to see if the data is already cached. -2. **Fallback to DB if miss:** If the key is **not** found in Valkey (a cache miss), the application queries the database for the data. -3. **Store in cache:** The result from the database is then stored in Valkey for next time, with an expiration time (TTL). -4. **Subsequent hits:** Future requests find the data in Valkey (cache hit) and can skip the database query, returning data to the user much faster. - -In Valkey, setting a key with an expiration can be done in one command. For example, to cache a rendered page for 5 minutes (300 seconds): - -``` -127.0.0.1:6379> SET page:homepage "...rendered content..." EX 300 -OK -``` - - -The `EX 300` option tells Valkey to automatically expire (remove) the key after 300 seconds. Until it expires, any request for `page:homepage` will be served the cached content from memory. You can adjust TTLs based on how fresh the data needs to be. Expiring keys ensures the cache doesn’t serve stale data indefinitely. - -Valkey can **cache nearly anything** – from database query results and API responses to session tokens, rendered HTML, or even generated reports. Database caching is a classic use case, but it's only the beginning. E-commerce platforms use Valkey to serve personalized recommendations instantly. Gaming companies rely on it for real-time leaderboards and matchmaking. Fintech systems trust Valkey to cache fraud detection signals and scoring results under heavy load. In AI and ML pipelines, Valkey accelerates inference by caching model outputs, storing precomputed embeddings, and managing access tokens across distributed systems. With sub-millisecond latency and the capacity to process hundreds of thousands of operations per second, Valkey is built to keep up — no matter how demanding the workload. - -### Best Practices and Troubleshooting - -**Best Practices:** - -* **Use descriptive key names:** Organize keys with namespaces using colon notation (e.g. `user:42:settings`). This makes it easier to manage related keys and avoid collisions. -* **Choose the right data type:** Store data in its natural form. For example, use a hash to keep an object’s fields together under one key instead of multiple separate keys, or use a list for an ordered collection of items. Leverage Valkey’s rich data structures to minimize client-side processing. -* **Set expirations for volatile data:** If using Valkey as a cache, always set a TTL on keys that represent transient data (sessions, cache entries, etc.) to prevent them from living forever. This helps automatically prune old data and keeps memory usage in check. -* **Mind memory limits:** By default, Valkey will keep growing in memory until it reaches the host’s limits. For production, configure a `maxmemory` limit and an eviction policy (like *Least Recently Used* eviction) if using it as a cache. This ensures Valkey evicts least-used entries when full, rather than failing once memory is exhausted. -* **Enable persistence if needed:** If you want Valkey to permanently store data (not just cache), enable persistence options. Valkey supports creating point-in-time snapshots (RDB files) or append-only file logging (AOF) similar to Redis. This safeguards data in case of a restart or failure. - -**Troubleshooting Common Issues:** - -* **Cannot connect to Valkey:** If the CLI or client can’t connect (e.g. *Connection refused* or *Unable to connect* errors), first ensure the Valkey server process is running. If it’s running on a different host or container, make sure you specify the correct `-h` and `-p` in `valkey-cli`, and that the port **6379** is open through any firewalls. You can always test connectivity with `valkey-cli ping` (expect a **PONG**). -* **Keys not found (or data missing):** If you expected data to be in Valkey but `GET` returns nothing, consider that the key might have expired or been evicted if you set a max memory policy. Use the `TTL ` command to check time-to-live, and ensure your application logic correctly stores the data. Also, confirm that you’re connecting to the same Valkey instance (and database number, if applicable) where the data was written. -* **Performance issues:** If you encounter high latency, monitor Valkey’s built-in metrics. You can use the `INFO` command to get stats on memory, CPU, and command usage. For deeper analysis of latency spikes, Valkey provides a latency monitoring feature and a benchmarking tool (`valkey-benchmark`). Common causes of slowdowns include very large payloads or expensive commands blocking the server. If needed, consider distributing load via clustering or splitting data across multiple instances. -* **Valkey server crashes or is unstable:** Though rare, if Valkey crashes, check the server logs for errors. Ensure your system’s memory is healthy (faulty RAM can cause issues in in-memory databases). Run `valkey-server --test-memory` to perform a memory test of your system. - -For further diagnostics, see the [official troubleshooting guide](problems.md). We want to ensure that Valkey runs smoothly in your environment. - -### Next Steps - -Now that you have Valkey running and understand the basics, you can explore more advanced topics and use cases: - -* **Try Valkey**: Use [Try Valkey](https://valkey.io/try-valkey/) allows you to try Valkey, the high-performance in-memory data store, directly from your browser — no installation needed -* **Core Data Types**: Valkey offers powerful [data types](data-types.md) beyond simple strings. Understanding these types is key to designing efficient applications: - * [Strings](strings.md): The simplest type, used for caching, counters, and more. - * [Lists](lists.md): Ordered sequences ideal for queues and logs. - * [Sets](sets.md): Unordered collections of unique elements, great for tags or membership checks. - * [Hashes](hashes.md): Field-value pairs, often used for storing objects or records. - * [Sorted Sets](sorted-sets.md): Unique elements with scores, useful for leaderboards or time-series data. -* **Explore Valkey Modules:** Valkey supports pluggable modules that extend its core functionality with custom commands and data types. Take a look at few of our official modules to get started. - * **[Valkey Json](valkey-json.md)** - * **[Valkey Bloom](bloomfilters.md)** - * **[Valkey LDAP](ldap.md)** - * **[Valkey Search](search.md)** - * **[Valkey Large Object](large-object.md)** (version 0.x) -* **Publish/Subscribe Messaging:** Dive into Valkey’s Pub/Sub feature to build real-time apps (such as chat systems o live notifications). See the [**Pub/Sub** section](pubsub.md) of the docs for patterns and best practices (Valkey’s Pub/Sub supports pattern subscriptions and sharded channels for scalability). -* **Clustering and High Availability:** When you need to scale out or ensure uptime, Valkey Cluster mode allows sharding data across multiple nodes with automatic failover. Check out the **[Valkey Cluster tutorial](cluster-tutorial.md)** for a step-by-step guide to setting up a cluster and using replication. -* **Further Documentation:** Explore the **[Valkey Documentation by Topic](index.md)** for in-depth guides on persistence, security, Lua scripting, modules, and more. Key references include the [Commands Reference](../commands/) for details on every command, and the [FAQ](faq.md) for answers to common questions. - -Happy caching with Valkey! With its speed and flexibility, you now have a powerful tool to build fast, scalable applications. **Next steps** above will guide you as you deepen your Valkey knowledge and tackle more complex scenarios. Good luck on your Valkey journey! diff --git a/topics/releases.md b/topics/releases.md deleted file mode 100644 index ba5587aa..00000000 --- a/topics/releases.md +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: "Releases and versioning schema" -description: How new versions of Valkey are released and supported ---- - -Valkey is usually among the most critical pieces of a software stack. -For this reason, Valkey's release cycle prioritizes highly stable releases at the cost of slower release cycles. - -All Valkey releases are published in the [Valkey GitHub repository](https://github.com/valkey-io/valkey/releases). - -## Versioning - -Valkey stable releases will generally follow `major.minor.patch` [semantic versioning schema](https://semver.org/). -We follow semantic versioning to provide explicit guarantees regarding backward compatibility. - -When discussing compatibility, we refer to the following API contracts: - -1. Valkey commands including their inputs, outputs, and defined behavior -2. The functions and APIs that can be executed from a Lua script -3. The RDB version -4. The protocol used to establish and replicate data from primaries to replicas -5. The protocol between nodes within a Valkey cluster -6. The Valkey Module API interface -7. The AOF on disk format - -### Patch versions - -*Patch* versions are released with backwards compatible bug fixes and should not introduce new features. - -Upgrading from a previous patch version should be safe and seamless. -It should be safe to run a primary-replica pair or a Valkey cluster with servers running on different patch versions. - -*Patch* versions may also introduce small improvements such as performance or memory optimizations that are easy to verify as safe. - -### Minor versions - -*Minor* versions are released with new functionality that is added in a backward compatible manner. -Examples of new functionality include new commands, info fields, or configuration parameters. - -Upgrading from a previous minor version should be safe, and will not introduce incompatibilities between servers in the cluster when default server configurations are used. - -**NOTE:** Minor releases may include new commands and data types that can introduce incompatibility between servers in the cluster, but users need to opt-in to these features to cause this type of incompatibility. -For this reason, it is not recommended to run a Valkey cluster with servers running on different minor versions. -Users should avoid new features until all servers in the cluster have been upgraded. - -Commands may also be marked as **deprecated** in minor versions. -Deprecated commands are not removed, instead a replacement command or an alternative to using the command will be defined in the same minor version. - -### Major versions - -*Major* versions are released with significant functionality that may break backwards compatibility or alter key performance characteristics. -Examples of significant functionality includes altering the behavior of an existing command, removing previously deprecated commands, changing the default value of configs, and significant refactoring for performance improvements. - -Upgrading from a previous major version is intended to be safe, but should be approached with caution. -You should carefully read the release notes before performing a major version upgrade. -Although Major versions can introduce breaking changes, data replicated from primaries to replicas will always be sent in a backward compatible format. -You should always upgrade replicas before upgrading primaries in order to ensure data consistency. - -The Valkey community strives to make as few backwards breaking changes as possible. -When breaking changes are required, we will also strive to provide a way to mitigate the impact without incurring downtime to your application. - -## Release schedule - -The Valkey community typically releases a stable major version once each year. -Stable minor versions are introduced as needed between major releases, -with at least one minor version published annually. - -### Release candidate - -New minor and major versions of Valkey begin by branching off the `unstable` branch as an initial release candidate branch with a name that takes the form of *`major.minor`*, example `7.2`. -The first release candidate, or rc1, is released once it can be used for development purposes and for testing the new version. -Release candidate versions will start with a patch version of "0" and will take the form *`major.minor.patch-rcN`*, example `7.2.0-rc1` followed by `7.2.0-rc2`. -At this stage, most of the new features and changes in the new version are ready for review, and the version is released for the purpose of collecting public feedback. -Subsequent release candidates are released every couple of weeks, primarily for fixing bugs and refining features based off of user input. - -### Stable release - -Once development has ended and the feedback for release candidate slows down, it is ready for the final release. -At this point, the release is marked as stable and is released with "0" as its patch-level version. - -Patches are released as needed to fix high-urgency issues, or once a stable version accumulates enough fixes to justify it. - -## Support - -The latest stable release is always fully supported and maintained. - -The Valkey community will provide maintenance support, providing patch releases for bug fixes and all security fixes, for 3 years from when a minor version was first released. - -The Valkey community will also provide extended security support for the latest minor version of each major version for 5 years from when a version was first released. -The minor version to be used for this extended security support will be decided once the next major version has been launched. -The Valkey community will only patch security issues we believe to be possible to exploit, which will be up to the discretion of the TSC. - -For contacting the TSC on sensitive matters and security issues, please see [SECURITY.md](https://github.com/valkey-io/valkey/blob/unstable/SECURITY.md). - -### List of supported versions - -| Version | Initial release | Maintenance support end | Security support end | -| -- | -- | -- | -- | -| 9.2 | 2026-11-19 | 2029-11-19 | 2031-11-19 | -| 9.1 | 2026-05-19 | 2029-05-19 | 2031-05-19 | -| 9.0 | 2025-10-21 | 2028-10-21 | 2028-10-21 | -| 8.1 | 2025-03-31 | 2028-03-31 | 2030-03-31 | -| 8.0 | 2024-09-15 | 2027-09-15 | 2027-09-15 | -| 7.2 | 2024-04-16 | 2027-04-16 | 2029-04-16 | - -## Unstable tree - -The development tree of Valkey is located in the `unstable` branch in the [Valkey GitHub repository](https://github.com/valkey-io/valkey). - -This branch is the source tree where most of the new features are under development. -`unstable` is not considered production-ready: it may contain critical bugs, incomplete features, and is potentially unstable. - -However, we try hard to make sure that even the unstable branch is usable most of the time in a development environment without significant issues. diff --git a/topics/replication.md b/topics/replication.md deleted file mode 100644 index acc34fb7..00000000 --- a/topics/replication.md +++ /dev/null @@ -1,504 +0,0 @@ ---- -title: Replication -description: How Valkey supports high availability and failover with replication ---- - -At the base of Valkey replication (excluding the high availability features provided as an additional layer by [Valkey Cluster](cluster-tutorial.md) or [Valkey Sentinel](sentinel.md)) there is a *leader follower* (primary-replica) replication that is simple to use and configure. It allows replica Valkey instances to be exact copies of primary instances. The replica will automatically reconnect to the primary every time the link breaks, and will attempt to be an exact copy of it *regardless* of what happens to the primary. - -This system works using three main mechanisms: - -1. When a primary and a replica instances are well-connected, the primary keeps the replica updated by sending a stream of commands to the replica to replicate the effects on the dataset happening in the primary side due to: client writes, keys expired or evicted, any other action changing the primary dataset. -2. When the link between the primary and the replica breaks, for network issues or because a timeout is sensed in the primary or the replica, the replica reconnects and attempts to proceed with a partial resynchronization: it means that it will try to just obtain the part of the stream of commands it missed during the disconnection. -3. When a partial resynchronization is not possible, the replica will ask for a full resynchronization. This will involve a more complex process in which the primary needs to create a snapshot of all its data, send it to the replica, and then continue sending the stream of commands as the dataset changes. - -Valkey uses asynchronous replication, which being low latency and -high performance, is the natural replication mode for the vast majority of Valkey -use cases. However, Valkey replicas asynchronously acknowledge the amount of data -they received periodically with the primary. So the primary does not wait every time -for a command to be processed by the replicas, however it knows, if needed, what -replica already processed what command. - -Synchronous replication of certain data can be requested by the clients using -the [`WAIT`](../commands/wait.md) and [`WAITAOF`](../commands/waitaof.md) commands. -However, these commands are only able to ensure there are the -specified number of acknowledged copies in the other Valkey instances, it does not -turn a set of Valkey instances into a CP system with strong consistency: acknowledged -writes can still be lost during a failover, depending on the exact configuration -of the Valkey persistence. However, with `WAIT`/`WAITAOF`, the probability of losing a write -after a failure event is greatly reduced to certain hard to trigger failure -modes. - -You can check the [Valkey Sentinel](sentinel.md) or [Valkey Cluster](cluster-tutorial.md) documentation for more information -about high availability and failover. The rest of this document describes the basic characteristics of Valkey replication, starting with a few general facts: - -* Valkey uses asynchronous replication, with asynchronous replica-to-primary acknowledges of the amount of data processed. -* A primary can have multiple replicas. -* Replicas are able to accept connections from other replicas. Aside from connecting a number of replicas to the same primary, replicas can also be connected to other replicas in a cascading-like structure. All the sub-replicas will receive exactly the same replication stream from the primary. This is not available in cluster mode, where a replica always replicates a primary directly. -* Valkey replication is non-blocking on the primary side. This means that the primary will continue to handle queries when one or more replicas perform the initial synchronization or a partial resynchronization. -* Replication is also largely non-blocking on the replica side. While the replica is performing the initial synchronization, it can handle queries using the old version of the dataset, assuming you configured Valkey to do so in valkey.conf. Otherwise, you can configure Valkey replicas to return an error to clients if the replication stream is down. However, after the initial sync, the old dataset must be deleted and the new one must be loaded. The replica will block incoming connections during this brief window (that can be as long as many seconds for very large datasets). You can configure Valkey so that the deletion of the old data set happens in a different thread, however loading the new initial dataset will still happen in the main thread and block the replica. -* Replication can be used both for scalability, to have multiple replicas for read-only queries (for example, slow O(N) operations can be offloaded to replicas), or simply for improving data safety and high availability. -* You can use replication to avoid the cost of having the primary writing the full dataset to disk: a typical technique involves configuring your primary's `valkey.conf` to avoid persisting to disk at all, then connect a replica configured to save from time to time, or with AOF enabled. However, this setup must be handled with care, since a restarting primary will start with an empty dataset: if the replica tries to sync with it, the replica will be emptied as well. - -## Safety of replication when primary has persistence turned off - -Running a primary without persistence is possible, but it takes some care. The -danger is a primary that crashes and comes back as the *same* instance with an empty -dataset: its replicas will faithfully replicate that empty dataset and discard their -own copies of the data. The following failure mode wipes the data from the primary -and all of its replicas: - -1. We have a setup with node A acting as primary, with persistence turned down, and nodes B and C replicating from node A. -2. Node A crashes, however it has some auto-restart system, that restarts the process. However since persistence is turned off, the node restarts with an empty data set. -3. Nodes B and C will replicate from node A, which is empty, so they'll effectively destroy their copy of the data. - -Any one of the following is enough to prevent this: - -* **Turn persistence on**, on the primary and on the replicas. This is the simplest - choice and the one to prefer when there's no reason not to. It isn't always - possible, for example because of latency concerns due to very slow disks. -* **Don't restart a crashed instance automatically.** If the instance stays down, a - replica that still holds the data can be promoted in its place. -* **Replace a failed node instead of restarting it**, so that what comes back is a - new instance rather than the old one with an empty dataset. This relies on the - replacement not being mistaken for the node it replaced, which Valkey Cluster - guarantees using node IDs, but Valkey Sentinel does not. - -The last option is what containerized deployments typically do: when Valkey runs as -an ephemeral pod in Kubernetes, a crashed node is replaced by a new pod instead of -being restarted in place. Whether that is enough depends on how nodes are identified. -Valkey Cluster identifies them by node ID, and a replacement starts without any -cluster configuration, so it generates a fresh ID and joins as a new, empty node even -if it reuses the IP address of the node it replaced. It is never mistaken for the old -primary, and the surviving replicas keep their data and can be promoted instead. -Running without persistence is a perfectly reasonable choice in such a setup. - -Valkey Sentinel identifies instances by address, so a replacement reusing the address -of the old primary is taken for that primary having rebooted, and the replicas -replicate its empty dataset. This is also why an automatically restarting primary is -especially dangerous under Sentinel: it can come back before Sentinel detects any -failure. Sentinel does report the new process as a `+reboot` event, but by default -draws no conclusion from it, and `primary-reboot-down-after-period` only forces a -failover for as long as the primary stays unresponsive. - -## How Valkey replication works - -Every Valkey primary has a replication ID: it is a large pseudo random string -that marks a given story of the dataset. Each primary also takes an offset that -increments for every byte of replication stream that it is produced to be -sent to replicas, to update the state of the replicas with the new changes -modifying the dataset. The replication offset is incremented even if no replica -is actually connected, so basically every given pair of: - - Replication ID, offset - -Identifies an exact version of the dataset of a primary. - -When replicas connect to primaries, they use the [`PSYNC`](../commands/psync.md) command to send -their old primary replication ID and the offsets they processed so far. This way -the primary can send just the incremental part needed. However if there is not -enough *backlog* in the primary buffers, or if the replica is referring to a -history (replication ID) which is no longer known, then a full resynchronization -happens: in this case the replica will get a full copy of the dataset, from scratch. - -This is how a full synchronization works in more details: - -The primary starts a background process that produces a snapshot of the dataset in the RDB format. At the same time it starts to buffer all new write commands received from the clients. The snapshot is transferred to the replica, which loads it, and the primary then sends all the buffered commands to the replica. From there on it keeps sending the stream of new commands. This is done as a stream of commands and is in the same format of the Valkey protocol itself. - -How the snapshot is transferred and loaded — in particular whether it passes through a file on disk on the primary side, on the replica side, or neither — is covered in [Full synchronization](#full-synchronization). - -## Replication ID explained - -In the previous section we said that if two instances have the same replication -ID and replication offset, they have exactly the same data. However it is useful -to understand what exactly is the replication ID, and why instances have actually -two replication IDs: the main ID and the secondary ID. - -A replication ID basically marks a given *history* of the data set. Every time -an instance restarts from scratch as a primary, or a replica is promoted to primary, -a new replication ID is generated for this instance. The replicas connected to -a primary will inherit its replication ID after the handshake. So two instances -with the same ID are related by the fact that they hold the same data, but -potentially at a different time. It is the offset that works as a logical time -to understand, for a given history (replication ID), who holds the most updated -data set. - -For instance, if two instances A and B have the same replication ID, but one -with offset 1000 and one with offset 1023, it means that the first lacks certain -commands applied to the data set. It also means that A, by applying just a few -commands, may reach exactly the same state of B. - -The reason why Valkey instances have two replication IDs is because of replicas -that are promoted to primaries. After a failover, the promoted replica requires -to still remember what was its past replication ID, because such replication ID -was the one of the former primary. In this way, when other replicas will sync -with the new primary, they will try to perform a partial resynchronization using the -old primary replication ID. This will work as expected, because when the replica -is promoted to primary, it sets its secondary ID to its main ID, remembering what -was the offset when this ID switch happened. Later it will select a new random -replication ID, because a new history begins. When handling the new replicas -connecting, the primary will match their IDs and offsets both with the current -ID and the secondary ID (up to a given offset, for safety). In short this means -that after a failover, replicas connecting to the newly promoted primary don't have -to perform a full sync. - -In case you wonder why a replica promoted to primary needs to change its -replication ID after a failover: it is possible that the old primary is still -working as a primary because of some network partition: retaining the same -replication ID would violate the fact that the same ID and same offset of any -two random instances mean they have the same data set. - -## Full synchronization - -A full synchronization transfers a complete snapshot of the dataset from the -primary to the replica. The snapshot is always in the RDB format, but it does not -have to be written to a file: the primary can stream it directly over the -replication link, and the replica can load it directly from the socket. The two -sides are configured independently of each other. - -### On the primary: diskless or disk-based - -**Diskless** full sync is the default, controlled by `repl-diskless-sync` (enabled -by default). The background process streams the snapshot straight to the replica's -socket, so the primary never writes it to disk. This avoids the disk I/O and the -disk space an RDB file would need, which matters most when the disk is slow or the -dataset is large. - -Since the size of the payload is not known when the transfer begins, a streamed -snapshot is delimited by a randomly generated end-of-file marker instead of being -prefixed by its length. Replicas state during the handshake whether they -understand this format; one that doesn't is served with a disk-based transfer -instead. - -Before starting a transfer, the primary waits `repl-diskless-sync-delay` seconds -(5 by default) so that replicas arriving in the meantime can be served by the same -snapshot. Set it to 0 to start immediately. `repl-diskless-sync-max-replicas` -limits how many replicas a single transfer may serve; 0, the default, means no -limit. - -**Disk-based** full sync, selected with `repl-diskless-sync no`, makes the primary -save the snapshot to its RDB file and then send that file, prefixed by its length. -The file can be shared: replicas that ask for a full sync while the save is in -progress can attach to it and receive the same file when it completes. - -Even with `repl-diskless-sync no`, a replica that needs something the RDB file -cannot give it is still served by a diskless transfer, so that the file on disk -stays valid and reusable for the other replicas. This happens when the replica -asks for a filtered dataset, needs an older RDB version, or needs a different -compression codec than the one the file is written in. - -Whether the transfer is diskless or disk-based, replicas waiting for a full sync -at the same time are grouped: one background save serves all those that can share -the same snapshot, and any replica needing a different one — a different RDB -version, a different compression codec, or a filtered dataset — is served by a -separate save. - -### On the replica: loading from a file or from the socket - -By default the replica stores the incoming snapshot in a temporary file and loads -it once the transfer is complete. Note that this is independent of the primary's -setting: a snapshot streamed by a diskless primary is still written to disk by the -replica unless the replica is configured otherwise. - -Loading straight from the socket avoids that write and read, but it needs care, -because the replica cannot safely discard its current dataset before the new one -has arrived. The `repl-diskless-load` option chooses the strategy: - -* `disabled` (default) — don't load from the socket. Store the snapshot to a - temporary file first, then load it. -* `on-empty-db` — load from the socket, but only when the replica's dataset is - empty, so there is nothing that could be lost. Otherwise fall back to storing - the snapshot to a file first. -* `swapdb` — load from the socket while keeping the current dataset in memory, so - it can be restored if the transfer fails. The replica can keep serving the old - data while the transfer is in progress, but it needs enough memory to hold both - datasets; if it doesn't, it risks being killed by the OOM killer. -* `flush-before-load` — **dangerous**: delete the current dataset before loading - the new one. If anything goes wrong before the transfer completes, the replica - is left with no data. - -## Dual-channel replication - -*Available since Valkey 8.0.* - -During a full synchronization, the primary normally buffers the write commands -that arrive while the snapshot is being transferred, and it needs memory for such -a buffer per synchronizing replica. With dual-channel replication the replica -opens a second connection instead: the snapshot is transferred on one channel -while the replica itself accumulates the concurrent command stream on the other. -This takes the buffering off the primary, which is usually the busier of the two, -in exchange for the replica needing memory for the accumulated stream. - -To use it, set `dual-channel-replication-enabled yes` on both the primary and the -replica. The primary must also have `repl-diskless-sync` enabled, since the -snapshot is streamed over the connection. Changing the setting does not affect a -synchronization that is already running; it applies to subsequent ones. - -## Compressing the replication stream - -*Available since Valkey 9.2.* - -The data sent over the replication link can be compressed, trading CPU time for -network bandwidth. This is useful when replicating over a constrained or metered -network, such as between availability zones. Compression is controlled by -`repl-compression`: - -* `no` (default) — send the stream uncompressed. -* `yes` — compress with the current default algorithm, currently LZ4. -* `lz4` — LZ4: fast, with moderate compression. -* `zstd` — Zstandard: compresses better, at a higher CPU cost. Requires a build - with Zstandard support. - -Set `repl-compression` on both the primary and the replica. On each side the value -is the strongest algorithm that side will use, and weaker ones are accepted as -well. The link then uses the strongest algorithm the two have in common, or no -compression if they have none: a `zstd` primary and an `lz4` replica settle on -`lz4`, while a replica left at `no` receives an uncompressed stream no matter what -its primary is set to. Changing `repl-compression` renegotiates established links. - -This setting covers the diskless full sync payload and the continuous command -stream. A disk-based full sync is only possible when the negotiated algorithm -matches the format the RDB file is stored in, since that file is sent as it is, and -falls back to diskless otherwise. Using the same value for `repl-compression` and -`rdbcompression` therefore keeps disk-based full sync available. - -## Configuration - -To configure basic Valkey replication is trivial: just add the following line to the replica configuration file: - - replicaof 192.168.1.1 6379 - -Of course you need to replace 192.168.1.1 6379 with your primary IP address (or -hostname) and port. Alternatively, you can call the [`REPLICAOF`](../commands/replicaof.md) command and the -primary host will start a sync with the replica. - -In cluster mode, the replication topology is part of the cluster configuration, so -neither the `replicaof` directive nor the [`REPLICAOF`](../commands/replicaof.md) -command can be used. Use [`CLUSTER REPLICATE`](../commands/cluster-replicate.md) -instead, giving it the node ID of the primary to replicate. - -There are also a few parameters for tuning the replication backlog taken -in memory by the primary to perform the partial resynchronization. See the example -`valkey.conf` shipped with the Valkey distribution for more information. - -Full synchronization has its own parameters: `repl-diskless-sync`, -`repl-diskless-sync-delay` and `repl-diskless-sync-max-replicas` on the primary -and `repl-diskless-load` on the replica, all described in -[Full synchronization](#full-synchronization). See also -[Dual-channel replication](#dual-channel-replication) and -[Compressing the replication stream](#compressing-the-replication-stream). - -## Read-only replica - -Replicas are read-only by default. -This behavior is controlled by the `replica-read-only` option in the valkey.conf file, and can be enabled and disabled at runtime using [`CONFIG SET`](../commands/config-set.md). - -Read-only replicas will reject all write commands, so that it is not possible to write to a replica because of a mistake. This does not mean that the feature is intended to expose a replica instance to the internet or more generally to a network where untrusted clients exist, because administrative commands like [`DEBUG`](../commands/debug.md) or [`CONFIG`](../commands/config.md) are still enabled. The [Security](security.md) page describes how to secure a Valkey instance. - -You may wonder why it is possible to revert the read-only setting -and have replica instances that can be targeted by write operations. -The answer is that writable replicas exist only for historical reasons. -Using writable replicas can result in inconsistency between the primary and the replica, so it is not recommended to use writable replicas. -To understand in which situations this can be a problem, we need to understand how replication works. -Changes on the primary is replicated by propagating regular Valkey commands to the replica. -When a key expires on the primary, this is propagated as a [`DEL`](../commands/del.md) command. -If a key which exists on the primary but is deleted, expired or has a different type on the replica compared to the primary will react differently to commands like `DEL`, [`INCR`](../commands/incr.md) or [`RPOP`](../commands/rpop.md) propagated from the primary than intended. -The propagated command may fail on the replica or result in a different outcome. -To minimize the risks (if you insist on using writable replicas) we suggest you follow these recommendations: - -* Don't write to keys in a writable replica that are also used on the primary. - (This can be hard to guarantee if you don't have control over all the clients that write to the primary.) - -* Don't configure an instance as a writable replica as an intermediary step when upgrading a set of instances in a running system. - In general, don't configure an instance as a writable replica if it can ever be promoted to a primary if you want to guarantee data consistency. - -Historically, there were some use cases that were considered legitimate for writable replicas. -As of version 7.0, these use cases are now all obsolete and the same can be achieved by other means. -For example: - -* Computing slow Set or Sorted set operations and storing the result in temporary local keys using commands like [`SUNIONSTORE`](../commands/sunionstore.md) and [`ZINTERSTORE`](../commands/zinterstore.md). - Instead, use commands that return the result without storing it, such as [`SUNION`](../commands/sunion.md) and [`ZINTER`](../commands/zinter.md). - -* Using the [`SORT`](../commands/sort.md) command (which is not considered a read-only command because of the optional STORE option and therefore cannot be used on a read-only replica). - Instead, use [`SORT_RO`](../commands/sort_ro.md), which is a read-only command. - -* Using [`EVAL`](../commands/eval.md) and [`EVALSHA`](../commands/evalsha.md) are also not considered read-only commands, because the Lua script may call write commands. - Instead, use [`EVAL_RO`](../commands/eval_ro.md) and [`EVALSHA_RO`](../commands/evalsha_ro.md) where the Lua script can only call read-only commands. - -While writes to a replica will be discarded if the replica and the primary resync or if the replica is restarted, there is no guarantee that they will sync automatically. - -Before version 4.0, writable replicas were incapable of expiring keys with a time to live set. -This means that if you use [`EXPIRE`](../commands/expire.md) or other commands that set a maximum TTL for a key, the key will leak, and while you may no longer see it while accessing it with read commands, you will see it in the count of keys and it will still use memory. -Valkey is able to evict keys with TTL as primaries do, with the exceptions of keys written in DB numbers greater than 63 (but by default Valkey instances only have 16 databases). -Note though that even in versions greater than 4.0, using `EXPIRE` on a key that could ever exists on the primary can cause inconsistency between the replica and the primary. - -Also note that replica writes are only local, and are not propagated to sub-replicas attached to the instance. Sub-replicas instead will always receive the replication stream identical to the one sent by the top-level primary to the intermediate replicas. So for example in the following setup: - - A ---> B ---> C - -Even if `B` is writable, C will not see `B` writes and will instead have identical dataset as the primary instance `A`. - -## Setting a replica to authenticate to a primary - -If your primary has a password via `requirepass`, it's trivial to configure the -replica to use that password in all sync operations. - -To do it on a running instance, use `valkey-cli` and type: - - config set primaryauth - -To set it permanently, add this to your config file: - - primaryauth - -## Allow writes only with N attached replicas - -You can configure a Valkey primary to -accept write queries only if at least N replicas are currently connected to the -primary. - -However, because Valkey uses asynchronous replication it is not possible to ensure -the replica actually received a given write, so there is always a window for data -loss. - -This is how the feature works: - -* Valkey replicas ping the primary every second, acknowledging the amount of replication stream processed. -* Valkey primaries will remember the last time it received a ping from every replica. -* The user can configure a minimum number of replicas that have a lag not greater than a maximum number of seconds. - -If there are at least N replicas, with a lag less than M seconds, then the write will be accepted. - -You may think of it as a best effort data safety mechanism, where consistency is not ensured for a given write, but at least the time window for data loss is restricted to a given number of seconds. In general bound data loss is better than unbound one. - -If the conditions are not met, the primary will instead reply with an error and the write will not be accepted. - -There are two configuration parameters for this feature: - -* min-replicas-to-write `` -* min-replicas-max-lag `` - -For more information, please check the example `valkey.conf` file shipped with the -Valkey source distribution. - -## How Valkey replication deals with expires on keys - -Valkey expires allow keys to have a limited time to live (TTL). Such a feature depends -on the ability of an instance to count the time, however Valkey replicas correctly -replicate keys with expires, even when such keys are altered using Lua -scripts. - -To implement such a feature Valkey cannot rely on the ability of the primary and -replica to have synced clocks, since this is a problem that cannot be solved -and would result in race conditions and diverging data sets, so Valkey -uses three main techniques to make the replication of expired keys -able to work: - -1. Replicas don't expire keys, instead they wait for primaries to expire the keys. When a primary expires a key (or evicts it because of LRU), it synthesizes a `DEL` command which is transmitted to all the replicas. -2. However because of primary-driven expire, sometimes replicas may still have in memory keys that are already logically expired, since the primary was not able to provide the `DEL` command in time. To deal with that the replica uses its logical clock to report that a key does not exist **only for read operations** that don't violate the consistency of the data set (as new commands from the primary will arrive). In this way replicas avoid reporting logically expired keys that are still existing. In practical terms, an HTML fragments cache that uses replicas to scale will avoid returning items that are already older than the desired time to live. -3. No keys expire while a script is running. Conceptually, time is frozen for the duration of the script, so a given key either exists or doesn't for as long as the script runs, and a key that is logically expired when the script starts expires the first time it is accessed rather than somewhere in the middle. This keeps the effects the script propagates to the replicas and to the AOF consistent with what the script itself observed. The same applies to a transaction: time is frozen for the whole [`MULTI`](../commands/multi.md)/[`EXEC`](../commands/exec.md) block. - -Once a replica is promoted to a primary it will start to expire keys independently, and will not require any help from its old primary. - -## Replication throttling - -*Available since Valkey 9.2.* - -When the primary produces write commands faster than a replica can consume them, -the replica's client output buffer (COB) grows. If the COB exceeds the configured -`client-output-buffer-limit` for replicas, the replica is disconnected and must -perform a full resynchronization, which is costly for both primary and replica. - -When enabled, the primary monitors every replica's client output buffer and, when -it is projected to exceed a safe threshold, slows incoming write commands to let -the replica catch up. The throttle rate adjusts gradually until the buffer -stabilizes or the replica is fully caught up, at which point throttling is -removed. - -Throttled clients are queued: their read handler is removed so no new commands are -buffered, and they are released at the configured rate by a timer event. The -command is not rejected; from the client's perspective, the response simply takes -longer. Throttled clients can be identified by the `h` flag in -[`CLIENT LIST`](../commands/client-list.md) output. - -To enable replication throttling, set `repl-throttling-enabled yes`. The default -is `no`. This option can be changed at runtime with -[`CONFIG SET`](../commands/config-set.md). Disabling it while throttling is active -immediately releases all queued clients and tears down the throttler. - -## Configuring replication with containers and NAT - -When containers using port forwarding, or Network Address Translation, are used, Valkey replication needs some extra care, especially when using Valkey Sentinel or other systems where the primary [`INFO`](../commands/info.md) or [`ROLE`](../commands/role.md) commands output is scanned to discover replicas' addresses. - -The problem is that the `ROLE` command, and the replication section of -the `INFO` output, when issued into a primary instance, will show replicas -as having the IP address they use to connect to the primary, which, in -environments using NAT may be different compared to the logical address of the -replica instance (the one that clients should use to connect to replicas). - -Similarly the replicas will be listed with the listening port configured -into `valkey.conf`, that may be different from the forwarded port in case -the port is remapped. - -To fix both issues, it is possible to force -a replica to announce an arbitrary pair of IP and port to the primary. -The two configurations directives to use are: - - replica-announce-ip 5.5.5.5 - replica-announce-port 1234 - -There is no need to set both of them if only the IP address or only the port needs -to be overridden. - -In cluster mode, clients and other nodes learn the addresses of the nodes from the -cluster topology rather than from `INFO` and `ROLE`, so the equivalent options are -the `cluster-announce-*` family, described in the -[Valkey Cluster tutorial](cluster-tutorial.md). - -## The INFO and ROLE command - -There are two Valkey commands that provide a lot of information on the current -replication parameters of primary and replica instances. One is `INFO`. If the -command is called with the `replication` argument as `INFO replication` only -information relevant to the replication are displayed. Another more -computer-friendly command is `ROLE`, that provides the replication status of -primaries and replicas together with their replication offsets, list of connected -replicas and so forth. - -## Partial sync after restarts and failovers - -When an instance is promoted to primary after a failover, -it will still be able to perform a partial resynchronization with the replicas -of the old primary. To do so, the replica remembers the old replication ID and -offset of its former primary, so can provide part of the backlog to the connecting -replicas even if they ask for the old replication ID. - -However the new replication ID of the promoted replica will be different, since it -constitutes a different history of the data set. For example, the primary can -return available and can continue accepting writes for some time, so using the -same replication ID in the promoted replica would violate the rule that a -replication ID and offset pair identifies only a single data set. - -Moreover, replicas - when powered off gently and restarted - are able to store -in the `RDB` file the information needed to resync with their -primary. This is useful in case of upgrades. When this is needed, it is better to -use the [`SHUTDOWN`](../commands/shutdown.md) command in order to perform a `save & quit` operation on the -replica. - -It is not possible to partially sync a replica that restarted via the -AOF file. However the instance may be turned to RDB persistence before shutting -down it, than can be restarted, and finally AOF can be enabled again. - -## `Maxmemory` on replicas - -By default, a replica will ignore `maxmemory` (unless it is promoted to a primary after a failover or manually). -It means that the eviction of keys will be handled by the primary, sending the DEL commands to the replica as keys evict in the primary side. - -This behavior ensures that primaries and replicas stay consistent, which is usually what you want. -However, if your replica is writable, or you want the replica to have a different memory setting, and you are sure all the writes performed to the replica are idempotent, then you may change this default (but be sure to understand what you are doing). - -Note that since the replica by default does not evict, it may end up using more memory than what is set via `maxmemory` (since there are certain buffers that may be larger on the replica, or data structures may sometimes take more memory and so forth). -Make sure you monitor your replicas, and make sure they have enough memory to never hit a real out-of-memory condition before the primary hits the configured `maxmemory` setting. - -To change this behavior, you can allow a replica to not ignore the `maxmemory`. The configuration directives to use is: - - replica-ignore-maxmemory no diff --git a/topics/search-configurables.md b/topics/search-configurables.md deleted file mode 100644 index d46b3191..00000000 --- a/topics/search-configurables.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: "Valkey Search - Configuration" -description: Valkey Search Module Configurable Settings ---- - -# Configurables - -The search module uses the Valkey configuration mechanism. Each configuration below can be set as a module load argument or with the `CONFIG SET` command, except `search.use-coordinator`, which can be set only as a module load argument. - -The module also has developer-only configurations, intended for testing and diagnosing the module. They are not listed on this page. Enabling developer-only configurations is not a supported operating mode. They can be changed with `CONFIG SET` or as module load arguments only while `search.debug-mode` is `yes` (default `no`); values set in the Valkey configuration file are accepted regardless of `search.debug-mode`. - -| Name | Type | Default Value | Description | -| :-------------------------------------------- | :-----: | :-----------: | :-------------------------------------------------------------------------------------------------------------------------------- | -| search.async-fanout-threshold | Number | 30 | Minimum number of fanout targets for which remote requests are issued asynchronously. Range: 1 to 10000. | -| search.backfill-batch-size | Number | 10240 | Controls the batch size for backfilling indexes. Range: 1 to 2147483647. | -| search.cluster-map-expiration-ms | Number | 250 | Controls how long (in milliseconds) the coordinator caches the cluster topology map before refreshing it from the Valkey cluster. Range: 0 to 3600000. | -| search.coordinator-query-timeout-secs | Number | 25 | Controls the gRPC deadline timeout (in seconds) for distributed coordinator query operations. It is independent of the query timeout: with the default `search.default-timeout-ms` of 50000, a remote shard still running after this deadline is treated as a failed shard (see `search.enable-partial-results`). Range: 1 to 3600. | -| search.cursor-max-count | Number | 100000 | Maximum `COUNT` accepted by `WITHCURSOR` and `FT.CURSOR READ`. Range: 1 to `INT64_MAX`. | -| search.cursor-max-idle-ms | Number | `INT64_MAX` | Maximum `MAXIDLE` (milliseconds) accepted by `WITHCURSOR` | -| search.debug-mode | Boolean | no | Enables developer-only configurations and lifts the upper bound of `search.emulate-release`. Not listed by `CONFIG GET search.*`; read it by its full name. | -| search.default-scorer | Enum | BM25STD | Scorer used when a query omits `SCORER`. See [Search - Scoring](search-scoring.md). Values: `BM25STD`. | -| search.default-timeout-ms | Number | 50000 | Controls the default timeout in milliseconds for FT.SEARCH, FT.AGGREGATE and FT.HYBRID. Range: 1 to 60000. | -| search.drain-mutation-queue-on-save | Boolean | no | Drain the mutation queue before RDB save | -| search.emulate-release | Version | 1.0.0 | Release whose behavior is emulated for gated compatibility fixes (see [COMPATIBILITY.md](https://github.com/valkey-io/valkey-search/blob/main/COMPATIBILITY.md#compatibility-defects)). The default is `.0.0` of the running module, so fixes gated at 1.3.0 are off by default. Range: 1.0.0 to the running module version; the upper bound is lifted while `search.debug-mode` is `yes`. | -| search.enable-consistent-results | Boolean | no | Default option for delivering consistent results when timeout occurs (uses CONSISTENT if not explicitly provided) | -| search.enable-partial-results | Boolean | yes | Default option for delivering partial results when timeout occurs (uses SOMESHARDS if not explicitly provided) | -| search.fuzzy-max-distance | Number | 3 | Controls the maximum allowed edit distance for fuzzy search queries. Range: 1 to 50. | -| search.high-priority-weight | Number | 100 | Weight for high priority tasks in thread pools; low priority = 100 - this value. Range: 0 to 100. | -| search.hnsw-block-size | Number | 10240 | HNSW resize configuration parameter for vector index block allocation. Range: 0 to 4294967295. | -| search.info-developer-visible | Boolean | no | Show developer metrics in `INFO`. See [INFO SEARCH metrics](search-observables.md). | -| search.local-fanout-queue-wait-threshold | Number | 50 | Queue wait threshold in milliseconds for preferring local node in fanout operations. Range: 0 to 10000. | -| search.log-level | Enum | notice | Controls module log level verbosity. Values: `warning`, `notice`, `verbose`, `debug`. | -| search.max-attributes | Number | 1000 | Controls the max number of attributes per index. Range: 1 to 10000. | -| search.max-group-key-expansion | Number | 65536 | Maximum number of groups one record can expand into in an FT.AGGREGATE GROUPBY over multi-value fields; exceeding it fails the query. Range: 1 to 4294967295. | -| search.max-indexes | Number | 1000 | Controls the maximum number of search indexes that can be created in the system. Range: 1 to 10000000. | -| search.max-mutation-queue-size-on-restore | Number | 10000 | Limits the mutation queue size during RDB restore to prevent memory spikes. Range: 1 to 1000000. | -| search.max-nonvector-search-results-fetched | Number | 100000 | Maximum number of matches retained per shard by a non-vector query. See [Vector Range Match](search-query.md#vector-range-match) for `VECTOR_RANGE` behavior. Range: 0 to 4294967295. | -| search.max-numeric-field-length | Number | 128 | Controls the max length of a numeric field. Range: 1 to 256. | -| search.max-prefixes | Number | 8 | Controls the max number of prefixes per index. Range: 1 to 16. | -| search.max-query-queue-depth | Number | 100000 | When the reader thread pool queue reaches this depth, FT.SEARCH, FT.AGGREGATE and FT.HYBRID are rejected with `Search query queue depth exceeded` before fan-out. Checked on each node that receives the query. 0 means unlimited. Range: 0 to 2147483647. | -| search.max-search-result-fields-count | Number | 500 | Controls the max number of fields in the content of the search response. Range: 1 to 1000. | -| search.max-search-result-record-size | Number | 5242880 | Controls the max content size for a record in the search response. Range: 100 to 10485760. | -| search.max-tag-field-length | Number | 256 | Controls the max length of a tag field. Range: 1 to 10000. | -| search.max-term-expansions | Number | 200 | Maximum number of words to search in text operations (prefix, suffix, fuzzy) to limit memory usage. Range: 1 to 100000. | -| search.max-timeout-ms | Number | 60000 | Controls the maximum allowed TIMEOUT value, in milliseconds, for FT.SEARCH, FT.AGGREGATE and FT.HYBRID. Range: 1 to 60000. | -| search.max-vector-attributes | Number | 1000 | Deprecated alias of `search.max-attributes`; used instead of it only when explicitly set. Range: 1 to 10000. | -| search.max-vector-dimensions | Number | 32768 | Controls the max dimensions for vector indices. Range: 1 to 64000. | -| search.max-vector-ef-construction | Number | 1000000 | Controls the max EF construction parameter for HNSW algorithm. Range: 1 to 1000000. | -| search.max-vector-ef-runtime | Number | 1000000 | Maximum `EF_RUNTIME` accepted for HNSW fields and query overrides. Range: 1 to 1000000. | -| search.max-vector-knn | Number | 10000 | Controls the max KNN parameter for vector search. Range: 1 to 100000. | -| search.max-vector-m | Number | 2000000 | Controls the max M parameter for HNSW algorithm. Range: 2 to 2000000. | -| search.max-worker-suspension-secs | Number | 60 | Max time in seconds that worker thread pool is suspended after fork started. Range: 0 to 3600. | -| search.proximity-inorder-compat-mode | Boolean | no | Controls proximity iterator's inorder/overlap violation check logic (compatibility mode) | -| search.query-string-bytes | Number | 10240 | Controls the length of the query string for FT.SEARCH command. Range: 1 to 4294967295. | -| search.query-string-depth | Number | 1000 | Controls the depth of the query string parsing from the FT.SEARCH cmd. Range: 1 to 4294967295. | -| search.query-string-terms-count | Number | 1000 | Controls the size of the query string parsing from the FT.SEARCH cmd (number of nodes in predicate tree). Range: 1 to 10000. | -| search.reader-threads | Number | Physical CPU cores | Controls the reader thread pool size; dynamically resizes pool on modification. Range: 1 to 1024. | -| search.search-result-background-cleanup | Boolean | | Enable search result cleanup on background thread | -| search.search-result-buffer-multiplier | Number (decimal) | 1.5 | Multiplier for search result buffer size allocation. Range: 1.0 to 1000.0. | -| search.skip-corrupted-internal-update-entries | Boolean | no | Skip corrupted AOF entries during internal updates | -| search.skip-rdb-load | Boolean | no | Skip loading vector index data from RDB file | -| search.tag-min-prefix-length | Number | 2 | Minimum number of characters required before trailing `*` in TAG wildcard queries (length excludes `*`). Range: 0 to 4294967295. | -| search.thread-pool-wait-time-samples | Number | 100 | Sample queue size for thread pool wait time tracking. Range: 10 to 10000. | -| search.use-coordinator | Boolean | no | Controls whether this instance uses the coordinator. Can be set only as a module load argument; it is not visible to `CONFIG GET` or `CONFIG SET`. | -| search.utility-threads | Number | 1 | Controls the utility thread pool size; dynamically resizes pool on modification. Range: 1 to 1024. | -| search.vector-chunk-huge-pages | Boolean | yes | Allocate vector index memory in 2 MB transparent huge pages (needs Valkey 9.2+ and THP not disabled); applies to new allocations | -| search.vector-unshare-batch-size | Number | 10240 | Number of vector records unshared per server cron tick. Range: 1 to 4294967295. | -| search.writer-threads | Number | Physical CPU cores | Controls the writer thread pool size; dynamically resizes pool on modification. Range: 1 to 1024. | - -`search.vector-chunk-huge-pages` takes effect when the server provides the external memory APIs (Valkey 9.2+) and transparent huge pages are not disabled for the process or host. Vector memory is then allocated and counted in 2 MB units, so a small index reports a few MB more `used_memory`. A 2 MB chunk is released only when all the vectors in it are deleted, so after most keys of a FLAT index are deleted, `used_memory` stays near its peak until new vectors reuse the space. diff --git a/topics/search-data-formats.md b/topics/search-data-formats.md deleted file mode 100644 index b2444c0d..00000000 --- a/topics/search-data-formats.md +++ /dev/null @@ -1,447 +0,0 @@ ---- -title: "Valkey Search - Data Formats" -description: Valkey Search Module Formats for Input Field Data ---- - -This document describes the data formats accepted by the search module for each field type during ingestion (when keys are created or modified) and how those values are processed before being stored in the index. - -# Tag Fields - -For both HASH and JSON index types, the incoming data for a tag field is a single UTF-8 string. A tag field can contain one or more tag values within a single string. - -With `search.emulate-release` below 1.3.0 (the default), a TAG value with malformed UTF-8 is indexed as raw bytes. With 1.3.0 or later it is rejected as invalid data (see [Invalid Values](#invalid-values)). See [COMPATIBILITY.md](https://github.com/valkey-io/valkey-search/blob/main/COMPATIBILITY.md) (`tag_rejects_non_utf8`). - -## Tag Ingestion - -On ingestion, the input string is split using the declared `SEPARATOR` character into individual tags. The default separator is `,` (comma). A different separator can be specified when the field is declared with [`FT.CREATE`](../commands/ft.create.md): - -``` -FT.CREATE idx SCHEMA color TAG SEPARATOR "|" -``` - -The separator must be a single byte (one ASCII character). A multi-byte character is rejected. - -After splitting, each tag is processed as follows: - -1. Leading and trailing ASCII whitespace is stripped from each tag. -2. Empty tags (those that are empty or whitespace only after trimming) are silently discarded. -3. Duplicate tags within a single field value are deduplicated. - -If the field value produces no valid tags after processing, the key is untracked for that field and, if the field was not already indexed for that key, counted in `hash_indexing_failures`. - -### Case Sensitivity - -By default, tag matching is case-insensitive. The `CASESENSITIVE` option on `FT.CREATE` changes this behavior: - -``` -FT.CREATE idx SCHEMA color TAG CASESENSITIVE -``` - -When `CASESENSITIVE` is not set, tags like `"Blue"` and `"blue"` are treated as equivalent during search. When `CASESENSITIVE` is set, they are treated as distinct values. - -### Ingestion Separator vs. Query Separator - -The separator specified in `FT.CREATE` applies only during data ingestion. In query expressions (`FT.SEARCH`), the separator between tags is always `|` (pipe), regardless of the ingestion separator. See the [query documentation](search-query.md#tag-match) for details. - -## Examples of Tag Values - -Given `FT.CREATE idx SCHEMA color TAG` (default separator `,`): - -``` -HSET doc:1 color "blue" --> tags: {"blue"} -HSET doc:2 color "blue,red" --> tags: {"blue", "red"} -HSET doc:3 color " blue , red " --> tags: {"blue", "red"} -HSET doc:4 color "blue,,red" --> tags: {"blue", "red"} -HSET doc:5 color "hello world, green is nice" --> tags: {"hello world", "green is nice"} -HSET doc:6 color " " --> no tags (key is untracked) -``` - -Note that spaces within a tag are preserved. In the example above, `"hello world"` is a single tag containing a space. - -Given `FT.CREATE idx SCHEMA skills TAG SEPARATOR "|"`: - -``` -HSET doc:1 skills "python|java|go" --> tags: {"python", "java", "go"} -HSET doc:2 skills "python | java" --> tags: {"python", "java"} -``` - -# Numeric Fields - -A numeric field contains a single number. On ingestion, the field value is parsed as a 64-bit IEEE 754 double-precision floating-point number. - -## Accepted Formats - -The following formats are accepted on ingestion: - -- **Integers**: `"42"`, `"-100"`, `"0"` -- **Floating-point**: `"3.14"`, `"-0.5"`, `"2.0"` -- **Scientific notation**: `"1e2"`, `"3.14e-5"` -- **Positive infinity**: `"inf"`, `"Inf"`, `"+inf"` -- **Negative infinity**: `"-inf"`, `"-Inf"` - -The following are rejected: - -- **NaN**: `"nan"`, `"NaN"`, `"NAN"` -- explicitly rejected on ingestion. -- **Non-numeric strings**: `"hello"`, `""`. - -A rejected value is invalid data; see [Invalid Values](#invalid-values). - -## Precision and Range - -All numeric values are stored internally as 64-bit double-precision floating-point numbers: - -- **Range**: approximately +/-1.7976931348623157 x 10^308 -- **Integer precision**: integers up to 2^53 (9,007,199,254,740,992) are represented exactly; larger integers may lose precision. -- **Decimal precision**: approximately 15-17 significant decimal digits. - -## Examples of Numeric Values - -``` -HSET product:1 price "999.99" --> stored as 999.99 -HSET product:2 price "42" --> stored as 42.0 -HSET product:3 price "-100" --> stored as -100.0 -HSET product:4 price "1e2" --> stored as 100.0 -HSET product:5 price "inf" --> stored as +infinity -HSET product:6 price "nan" --> rejected (invalid data) -HSET product:7 price "hello" --> rejected (invalid data) -``` - -See the [query documentation](search-query.md#numeric-range-match) for details on querying numeric ranges. - -# Vector Fields - -A vector field contains a fixed-length array of floating-point numbers. The data format differs between HASH and JSON index types. - -## Supported Data Types - -Three element types are supported. All are little-endian and all work with every -distance metric; they differ only in how many bytes each element occupies and how -much precision it retains. - -| `TYPE` | Bytes per element | sign / exponent / mantissa bits | Largest finite magnitude | Approx. decimal digits | -| --- | --- | --- | --- | --- | -| `FLOAT32` | 4 | 1 / 8 / 23 | ~3.4e38 | ~7 | -| `FLOAT16` | 2 | 1 / 5 / 10 | 65504 | ~3 | -| `BFLOAT16` | 2 | 1 / 8 / 7 | ~3.4e38 | ~2 | - -`FLOAT16` and `BFLOAT16` both halve the memory a vector occupies compared with -`FLOAT32`. They differ in how they spend their 16 bits. `FLOAT16` keeps more -mantissa, so it is more precise, but its exponent range is much smaller: values -above 65504 in magnitude overflow to infinity. `BFLOAT16` is simply the top 16 -bits of a `FLOAT32`, so it keeps the full `FLOAT32` exponent range and trades -away precision instead. - -As a rule of thumb, embeddings that are normalized or otherwise bounded suit -`FLOAT16`, while data with a wide dynamic range suits `BFLOAT16`. - -Choosing a 2-byte type is lossy: each element is rounded to the target type when -it is ingested, and the rounded value is what the index stores and compares. Recall -may therefore differ slightly from the same data indexed as `FLOAT32`. - -The data type is specified as a required parameter in the [`FT.CREATE`](../commands/ft.create.md) command, and is reported back by [`FT.INFO`](../commands/ft.info.md) as the attribute's `data_type`: - -``` -FT.CREATE idx SCHEMA embedding VECTOR HNSW 6 TYPE FLOAT16 DIM 3 DISTANCE_METRIC L2 -``` - -### Version requirement - -An index schema that declares `FLOAT16` or `BFLOAT16` records a minimum module -version of 1.3.0. A module older than that refuses to load such an index rather -than misreading its 2-byte elements as `FLOAT32`. This matters when downgrading, -and in mixed-version clusters: keep to `FLOAT32` if an index has to be readable -by modules earlier than 1.3.0. Indexes that use only `FLOAT32` are unaffected. - -### BFLOAT16 hardware requirement - -`BFLOAT16` indexes require a CPU that provides a SIMD BF16 conversion path: -Haswell or newer on x86-64, or NEON-BF16/SVE-BF16 on ARM. On a CPU without one, -creating a `BFLOAT16` index -- or loading one from an RDB -- fails with an error -rather than producing incorrect distances. `FLOAT32` and `FLOAT16` indexes have -no such requirement. - -## HASH Vector Format - -For HASH-type indexes, vectors are stored as raw binary blobs. Each element is -written in little-endian byte order using the index's declared `TYPE`, so the -total blob size must be exactly `DIM * `: `DIM * 4` for -`FLOAT32`, `DIM * 2` for `FLOAT16` and `BFLOAT16`. - -The same 3-dimensional vector `[0.0, 0.0, 1.0]` in each type: - -``` -FLOAT32 (12 bytes) \x00\x00\x00\x00 \x00\x00\x00\x00 \x00\x00\x80\x3f -FLOAT16 (6 bytes) \x00\x00 \x00\x00 \x00\x3c -BFLOAT16 (6 bytes) \x00\x00 \x00\x00 \x80\x3f -``` - -Note that the `BFLOAT16` encoding of 1.0 is the high half of the `FLOAT32` -encoding (`\x80\x3f`), which is what makes the conversion a truncation of the -top two bytes rather than a change of layout. - -In Python, a HASH vector can be created with: - -```python -import numpy as np - -# FLOAT32 -vector = np.array([0.0, 0.0, 1.0], dtype=np.float32).tobytes() - -# FLOAT16 -vector = np.array([0.0, 0.0, 1.0], dtype=np.float16).tobytes() - -client.hset("doc:1", mapping={"embedding": vector}) -``` - -Or equivalently with `struct`, whose format characters are `f` for `FLOAT32` and -`e` for `FLOAT16`: - -```python -import struct -vector = struct.pack("<3f", 0.0, 0.0, 1.0) # '<' = little-endian, 'f' = FLOAT32 -vector = struct.pack("<3e", 0.0, 0.0, 1.0) # 'e' = FLOAT16 -``` - -Neither `numpy` nor `struct` has a native `BFLOAT16` type. Encode it by rounding -each `FLOAT32` to nearest-even and keeping the top two bytes: - -```python -import struct - -def to_bfloat16(values): - packed = struct.pack(f"<{len(values)}f", *values) - out = bytearray() - for i in range(len(values)): - u = int.from_bytes(packed[i * 4:i * 4 + 4], "little") - u = (u + 0x7FFF + ((u >> 16) & 1)) & 0xFFFFFFFF # round to nearest, ties to even - out += u.to_bytes(4, "little")[2:4] # keep the high half - return bytes(out) - -client.hset("doc:1", mapping={"embedding": to_bfloat16([0.0, 0.0, 1.0])}) -``` - -The `ml_dtypes` package provides a `bfloat16` dtype usable with `numpy` if you -would rather not hand-roll the conversion. - -If the blob size does not match the size implied by `DIM` and `TYPE`, the vector -is rejected as invalid data (see [Invalid Values](#invalid-values)). A `FLOAT32`-encoded blob -supplied to a `FLOAT16` index is the common way to hit this: it is twice the -expected length. - -## JSON Vector Format - -For JSON type indexes, a vector may be written either as a **native JSON array** -of numbers or as a **JSON string** containing a bracketed, comma-separated list. -Both forms are supported and equivalent -- they index identically and return -identical distances: - -``` -JSON.SET doc:1 $ '{"embedding": [1.0, 0.0, 0.0]}' # native array -JSON.SET doc:2 $ '{"embedding": "[1.0, 0.0, 0.0]"}' # quoted string -``` - -Prefer the native array. It is ordinary JSON, so other readers of the document -see a real array rather than an opaque string, and it needs no client-side -formatting. The quoted string is the older form, still supported for documents -already written that way. - -Either form is converted element by element to the index's declared `TYPE`. For -a `FLOAT16` or `BFLOAT16` index the values are therefore rounded to 2-byte -precision on ingest, exactly as a binary blob would be. - -In Python, with the native array form: - -```python -client.json().set("doc:1", "$", {"embedding": [1.0, 0.0, 0.0]}) -``` - -Or with the string form: - -```python -vector = [1.0, 0.0, 0.0] -client.json().set("doc:2", "$", - {"embedding": "[" + ",".join(str(v) for v in vector) + "]"}) -``` - -A value containing a non-numeric element, or whose element count does not match -`DIM`, is not indexed for that field: the key is left out of vector search -results, exactly as an incorrectly sized binary blob would be. - -## Query Vectors - -Regardless of whether the index is on HASH or JSON keys, query vectors provided -via `PARAMS` to `FT.SEARCH` must always use the binary blob format (the same -format as HASH vectors), encoded with the index's declared `TYPE`. - -A query blob whose length does not match `DIM * ` is -rejected. Querying a 3-dimensional `FLOAT16` index with a `FLOAT32`-encoded blob, -for instance, returns: - -``` -Error parsing vector similarity parameters: query vector blob size (12) does not -match index's expected size (6). -``` - -## Examples of Vector Field Values - -A 3-dimensional vector with HASH storage: - -``` -FT.CREATE idx ON HASH SCHEMA vec VECTOR FLAT 6 TYPE FLOAT32 DIM 3 DISTANCE_METRIC L2 - -HSET doc:1 vec "\x00\x00\x80?\x00\x00\x00\x00\x00\x00\x00\x00" -``` - -A 3-dimensional vector with JSON storage: - -``` -FT.CREATE idx ON JSON SCHEMA $.vec AS vec VECTOR FLAT 6 TYPE FLOAT32 DIM 3 DISTANCE_METRIC L2 - -JSON.SET doc:1 $ '{"vec": [1.0, 0.0, 0.0]}' -``` - -The same document using the string form, which is equivalent: - -``` -JSON.SET doc:1 $ '{"vec": "[1.0, 0.0, 0.0]"}' -``` - -The same vector in a `FLOAT16` index, where each element is 2 bytes rather than 4: - -``` -FT.CREATE idx ON HASH SCHEMA vec VECTOR FLAT 6 TYPE FLOAT16 DIM 3 DISTANCE_METRIC L2 - -HSET doc:1 vec "\x00\x3c\x00\x00\x00\x00" -``` - -# Invalid Values - -A value that is rejected as invalid data (a malformed `NUMERIC` value, a wrong-size -`VECTOR`, or, with 1.3.0 behavior, a non-UTF-8 `TAG` value) is counted in -`hash_indexing_failures` when the field was not already indexed for that key; a -rejected update to an already-indexed field is not counted. With `search.emulate-release` below 1.3.0 (the default), -only that field is treated as missing; the key is still indexed for its other -fields. With 1.3.0 or later, the whole key is removed from the index, matching -RediSearch. See [COMPATIBILITY.md](https://github.com/valkey-io/valkey-search/blob/main/COMPATIBILITY.md) (`invalid_data_drops_key`). - -# Text Fields - -A text field contains a string of words. On ingestion, the raw string passes through a multi-stage processing pipeline to produce a sequence of searchable tokens. - -## Text Ingestion - -The pipeline consists of four stages applied in order: - -1. **Lexical Analysis** -- split text into words -2. **Case Folding** -- convert to lowercase -3. **Stop Word Removal** -- filter out common words -4. **Stemming** -- reduce words to root forms - -### Lexical Analysis - -The input string is split into words based on punctuation characters and whitespace. A "word" is any contiguous sequence of characters that is not punctuation and not whitespace. - -**Whitespace characters** always break words. This includes spaces, tabs, newlines, carriage returns, and control characters. For every language except English, Unicode whitespace such as the no-break space (U+00A0) and the ideographic space (U+3000) also breaks words; English keeps ASCII-only whitespace. - -**Punctuation characters** are configurable. The default set depends on `LANGUAGE`. For English it is: - -``` -,.<>{}[]"':;!@#$%^&*()-+=~/\|? -``` - -Other languages add their own punctuation to this set, for example `« » – —` for French and `، ؛ ؟` for Arabic. - -A custom punctuation set can be specified at index creation time: - -``` -FT.CREATE idx PUNCTUATION ",.!?" SCHEMA content TEXT -``` - -The punctuation set is matched per character (Unicode code point), so it can include multi-byte characters such as `—`. Characters not in the set, such as CJK characters or emoji, become part of the surrounding word. For languages other than English, a character that normalizes to punctuation in the set is also a word boundary, for example the fullwidth comma `,` (U+FF0C) for Arabic, whose normalization maps it to `,`. - -**Escape sequences**: A backslash (`\`) before a punctuation character causes that character to be treated as part of the word rather than as a word boundary. The same rules apply to documents and to queries. With the default punctuation, which includes `\`: - -| Input | Tokens | -| :-------------- | :----------------------------------------------------------------- | -| `hello\,world` | `hello,world` (escaped punctuation is kept) | -| `hello\\world` | `hello\world` (an escaped backslash is kept) | -| `hello\world` | `hello`, `world` (before other characters, `\` is a word boundary) | -| `hello\` | `hello` in a document; an error in a query | - -If `\` is removed from a custom punctuation set, a backslash before a non-punctuation character is dropped and the word continues. - -The input must be valid UTF-8. A text field containing invalid UTF-8 is not indexed and is counted in `hash_indexing_failures`. - -### Case Folding - -After tokenization, each word is converted to lowercase. For ASCII text, this uses standard ASCII lowercasing. For text containing non-ASCII characters, Unicode case folding (via ICU) is applied. - -### Stop Word Removal - -Stop words are common words that are excluded from the index. The default stop word list for English is: - -> a, an, and, are, as, at, be, but, by, for, if, in, into, is, it, no, not, of, on, or, such, that, the, their, then, there, these, they, this, to, was, will, with - -Stop words can be customized at index creation time: - -``` -FT.CREATE idx STOPWORDS 2 the a SCHEMA content TEXT -FT.CREATE idx NOSTOPWORDS SCHEMA content TEXT -``` - -`NOSTOPWORDS` or `STOPWORDS 0` disables stop word removal entirely. - -Removed stop words do not occupy a position in the token sequence. For example, `"the quick brown fox"` (where "the" is a stop word) produces positions: quick=0, brown=1, fox=2. This is relevant for phrase matching and proximity queries. - -### Stemming - -Stemming reduces words to their root form so that morphological variants match each other. For example, "running", "runs", and "run" all have the same stem: "run". The stemming algorithm is language-specific and uses the Snowball stemmer for the index's `LANGUAGE`. - -Stemming is controlled by these options: - -- `LANGUAGE ` (schema-level): Specifies the language, which selects the stemmer, the default stop words, and the default punctuation. Supported: `ENGLISH` (default), `ARABIC`, `DUTCH`, `FRENCH`, `GERMAN`, `INDONESIAN`, `ITALIAN`, `PORTUGUESE`, `RUSSIAN`, `SPANISH`, `SWEDISH`, `TURKISH`. -- `NOSTEM` (per-field): Disables stemming for a specific text field. Given before `SCHEMA`, it disables stemming for every text field of the index. -- `MINSTEMSIZE ` (schema-level): Words shorter than this length are not stemmed. The default is 4. - -When stemming is enabled, the original word (not the stemmed form) is stored in the index. The stem mapping is recorded separately so that a search on a term expands to match all terms that share the same stem, as well as the stem itself. - -## Text Ingestion Examples - -### Lexical Processing Examples - -Given the default punctuation set: - -| Input | Tokens | -| :---------------- | :---------------------------- | -| `"hello world"` | `hello`, `world` | -| `"hello, world!"` | `hello`, `world` | -| `"it's a test"` | `it`, `s`, `a`, `test` | -| `"hello-world"` | `hello`, `world` | -| `"price: $100"` | `price`, `100` | -| `"hello\,world"` | `hello,world` (escaped comma) | - -### Stop Word Removal Example - -Given the default stop word list and input `"the quick brown fox is not fast"`: - -| Stage | Result | -| :---------------------- | :-------------------------------------------------- | -| After tokenization | `the`, `quick`, `brown`, `fox`, `is`, `not`, `fast` | -| After case folding | `the`, `quick`, `brown`, `fox`, `is`, `not`, `fast` | -| After stop word removal | `quick`, `brown`, `fox`, `fast` | - -The stop words `the`, `is`, and `not` are removed. The remaining words have positions 0 through 3. - -### Stemming Example - -Given English stemming with the default `MINSTEMSIZE` of 4 and input `"The Running Searches cat"`: - -| Stage | Result | -| :---------------------- | :--------------------------------------------------- | -| After tokenization | `The`, `Running`, `Searches`, `cat` | -| After case folding | `the`, `running`, `searches`, `cat` | -| After stop word removal | `running`, `searches`, `cat` | -| Indexed tokens | `running` (position 0), `searches` (position 1), `cat` (position 2) | -| Stem mappings | `run` -> {`running`}, `search` -> {`searches`} | - -The word `the` is removed as a stop word. The word `cat` (3 characters) is below the minimum stem size and is not stemmed. A search for `run` or `runs` will match `running` through the stem mapping. \ No newline at end of file diff --git a/topics/search-expressions.md b/topics/search-expressions.md deleted file mode 100644 index 2525b1f5..00000000 --- a/topics/search-expressions.md +++ /dev/null @@ -1,196 +0,0 @@ ---- -title: "Valkey Search - Aggregation Expressions" -description: Valkey Search Module Aggregation Expression Language ---- - -The `FILTER`, `APPLY`, `SORTBY` and `GROUPBY` stages of `FT.AGGREGATE` use expressions to compute values. The processing stages of `FT.HYBRID` and the `FILTER` option of `FT.CREATE` use the same language. - -Where this page describes behavior that depends on `search.emulate-release`, the setting applies only to `FT.AGGREGATE`. `FT.HYBRID` and `FT.CREATE ... FILTER` always use the 1.3.0 behavior. - -The expression engine operates on input values, generating output values. Values in the expression language are dynamically typed and can be either Nil (missing/invalid), Numeric (64-bit floating point) or String (a sequence of bytes). A value can also be an array, such as the output of the `TOLIST` and `RANDOM_SAMPLE` reducers or a multi-value JSON field. - -The syntax of expressions generally follows the "C" language syntax and operator precedence rules with some specialized syntax for accessing fields of records and parameters from the `FT.AGGREGATE` command. - -``` - ::= - - ::= - | "||" - - ::= - | "&&" - - ::= - | - - ::= "<" | "<=" | "==" | "!=" | ">" | ">=" - - ::= - | - - ::= "+" | "-" - -::= - | - - ::= "*" | "/" - - ::= - | "^" - - ::= - | - | - | - | - | "!" - | "(" ")" - - ::= "@" - - ::= "$" - - ::= "(" ")" - - ::= - | - | "," - -``` - -This grammar applies with `search.emulate-release` 1.3.0 or later. Below 1.3.0 (the default for `FT.AGGREGATE`), `^` has the same precedence as `*` and `/` and is left-associative, and `&&` has the same precedence as `||`, so `@a || @b && @c` is `(@a || @b) && @c`. See [COMPATIBILITY.md](https://github.com/valkey-io/valkey-search/blob/main/COMPATIBILITY.md). - -# Primary Values - -Numeric constants are the usual syntax of decimal integer and floating point expression formats, plus _inf_, _+inf_ and _-inf_. - -String constants are enclosed with single (`'`) or double quotes(`"`). A backslash (`\`) followed by a quote can be used to insert a quote character. - -A parameter-ref selects a string value provided by the `PARAMS` clause of the executing `FT.AGGREGATE` command. With `search.emulate-release` 1.3.0 or later, a parameter whose text is a number is a numeric value. - -A field-ref is used to access values from the record currently being processed. If the field doesn't exist then the reference returns a Nil value. With `search.emulate-release` 1.3.0 or later, a reference to a field the key does not have is _missing_: an operator or function (other than `exists`, `concat` and `&&`) given a missing value returns missing, and an `APPLY` whose expression is missing drops the record. `concat` given a missing value returns Nil instead, so an `APPLY` that uses it keeps the record. - -# Operators - -## Arithmetic Operators - -The following numeric operators are available. String values are converted to numeric, but become a Nil if the conversion fails. An empty string converts to 0 with `search.emulate-release` below 1.3.0, and does not convert with 1.3.0 or later. If either input to a numeric operator is Nil, then the output is Nil. Division by zero gives `nan` below 1.3.0; with 1.3.0 or later it gives `inf`, `-inf`, or `nan` for `0/0`. - -| Syntax | Operation | -| :----: | :------------- | -| + | Addition | -| - | Subtraction | -| \* | Multiplication | -| / | Division | -| ^ | Exponentiation | - -## Relational Operators - -The following relational operators are available. Relational operators perform conversions according to the following prioritized rules: - -1. If both inputs are Nil, they are considered equal. -2. If one of the inputs is Nil then the comparison is unordered. -3. If both inputs are numbers, then a numeric comparison is performed. -4. If both inputs are strings, then a string comparison is performed. -5. If either input is a number and the other input can be converted to a number, then a numeric comparison is performed. -6. The two inputs are compared as strings. - -With `search.emulate-release` 1.3.0 or later, the kind of comparison is instead chosen from the operand types when the expression is compiled: numeric if either operand is numeric (such as a numeric constant, a `NUMERIC` field or a numeric function), else string if either operand is a string. In a numeric comparison a string that does not convert to a number is an error for `<`, `<=`, `>` and `>=`, while `==` is false and `!=` is true. In `FT.AGGREGATE` and `FT.HYBRID` the error fails the command; in `FT.CREATE ... FILTER` the key is not indexed. So `@f < 5` compares numbers, while `@f < '5'` compares strings when `@f` is a `TAG` field. - -| Syntax | Operation | -| :----: | :----------------------- | -| < | Less than | -| <= | Less than or equal to | -| == | Equal to | -| != | Not equal to | -| > | Greater than | -| >= | Greater than or equal to | - -## Logical Operators - -The logical operators `&&`, `||` and `!` generate 0 for false and 1 for true. A value is false when it is 0, Nil, an empty array or an empty string (with `search.emulate-release` below 1.2.1, any string), and true otherwise. With `search.emulate-release` 1.3.0 or later, `&&` and `||` evaluate their right operand only when the left one does not decide the result. - -# Functions - -## Numeric Processing Functions - -Supported numeric functions are listed. Numeric functions always convert their inputs to a number. A Nil input gives Nil. An input that does not convert gives Nil with `search.emulate-release` below 1.2.1, and `nan` with 1.2.1 or later. - -| Syntax | Operation | -| :---------------: | :------------------------------------------- | -| log(expression) | ln(expression) | -| abs(expression) | \| expression \| | -| ceil(expression) | Round to smallest not less than expression | -| floor(expression) | Round to largest not greater than expression | -| log2(expression) | log2(expression) | -| exp(expression) | exp(expression) | -| sqrt(expression) | sqrt(expression) | - -## String Processing Functions - -String processing functions. With `search.emulate-release` below 1.3.0, inputs are converted to strings (or, for the `offset` and `length` of `substr`, to numbers) as appropriate, except that with 1.2.1 or later `lower` and `upper` of a value that is not a string give Nil. With 1.3.0 or later a number is never converted, except by `concat`, which converts numbers to strings (`concat(12, 'x')` gives `12x`): `lower` and `upper` of a number give Nil, and a number given to `strlen`, `startswith`, `contains` or as `s` of `substr`, or a string given as `offset` or `length` of `substr`, is an error that fails the command. - -| Syntax | Operation | -| :-----------------------: | ---------------------------------------------------------------------------------------------------------------------- | -| upper(s) | Convert to upper case (ASCII Only) | -| lower(s) | Convert to lower case (ASCII Only) | -| startswith(s1, s2) | 1 if s2 matches the start of s1 otherwise 0 | -| contains(s1, s2) | The number of occurrences of s2 in s1 | -| strlen(s) | Number of bytes in the string | -| substr(s, offset, length) | `length` bytes of s starting at `offset`. A negative offset counts from the end of s. A negative length ends that many bytes before the end of s | -| concat(s1, s2, ...) | Concatenate up to 50 string expressions into a single string | - -## Timestamp Processing Functions - -Time functions extract various time fields from a numeric UTC Unix timestamp using the `gmtime` C library function, or round the timestamp down. With `search.emulate-release` 1.2.1 or later, a timestamp before 1970 gives Nil in every function below except `timefmt`; below 1.2.1 the value is computed from the negative timestamp. - -Supported time functions include: - -| Syntax | Operation | -| :-------------------------: | :----------------------------------------------- | -| dayofweek(timestamp) | Extract day of week from timestamp. Range: 0-6 | -| dayofmonth(timestamp) | Extract day of month from timestamp. Range: 1-31 | -| dayofyear(timestamp) | Extract day of year from timestamp. Range: 0-365 | -| monthofyear(timestamp) | Extract month of year from timestamp. Range: 0-11 | -| year(timestamp) | Extract year from timestamp. | -| minute(timestamp) | Timestamp rounded down to the start of its minute | -| hour(timestamp) | Timestamp rounded down to the start of its hour | -| day(timestamp) | Timestamp rounded down to the start of its day | -| month(timestamp) | Timestamp rounded down to the start of its month (below 1.2.1, the start of the day before) | -| timefmt(timestamp [, fmt]) | Convert timestamp to string using strftime. `fmt` defaults to `%FT%TZ`. | -| parsetime(time_string [, fmt]) | Parse time string into timestamp using strptime. `fmt` defaults to `%FT%TZ`. | - -With `search.emulate-release` 1.2.1 or later, `timefmt` with an empty format and `parsetime` of a string that does not match the format give Nil. Below 1.2.1, `timefmt` gives an empty string and `parsetime` does not detect the mismatch. `parsetime` parses only as much of the string as the format matches and ignores any text after it. - -## Exists Function - -The exists function returns 0 if the input argument is Nil else 1. This can be used to test if a field is present in the current record. - -| Syntax | Operation | -| :-----------: | :----------------------------- | -| exists(value) | 0 if the value is Nil, else 1. | - -## Conditional Function - -`case` returns `if_true` when the condition is true, and `if_false` otherwise. -Only the returned expression is evaluated, so the other one may refer to a -field that the record does not have. - -| Syntax | Operation | -| :--------------------------------: | :-------------------------------------------------------- | -| case(condition, if_true, if_false) | `if_true` when `condition` is true, otherwise `if_false`. | - -The condition is false when it is 0, Nil, an empty array or an empty string -(with `search.emulate-release` below 1.2.1, any string), and true otherwise. -When it refers to a missing field or fails with an error: - -- In `FT.AGGREGATE` with `search.emulate-release` below `1.3.0` (the default), - a missing field is Nil, so the condition is false. -- Otherwise, the missing field or the error becomes the result of `case`, and - neither expression is evaluated. - -For example, the following gives records without `foo` the value `no foo`: - -``` -case(exists(@foo), @foo, "no foo") -``` diff --git a/topics/search-monitoring.md b/topics/search-monitoring.md deleted file mode 100644 index 610182d7..00000000 --- a/topics/search-monitoring.md +++ /dev/null @@ -1,165 +0,0 @@ ---- -title: "Valkey Search - Metrics and configurations" -description: Valkey Search Module INFO SEARCH ---- - -## Metrics - INFO SEARCH - -### search_index_stats - -| Metric Name | Unit | Description | -| :--- | :---: | :--- | -| search_number_of_attributes | Count | Total attributes across all search indexes | -| search_number_of_indexes | Count | Total number of search indexes | -| search_total_active_write_threads | Count | Active writer threads (0 if suspended) | -| search_total_indexed_documents | Count | Total documents indexed across all indexes | - -### search_indexing - -| Metric Name | Unit | Description | -| :--- | :---: | :--- | -| search_background_indexing_status | String | Background indexing status: IN_PROGRESS or NO_ACTIVITY | - -### search_memory - -| Metric Name | Unit | Description | -| :--- | :---: | :--- | -| search_index_reclaimable_memory | Bytes | Memory reclaimable after vector deletions | -| search_used_memory_bytes | Bytes | Total memory used by the module | -| search_used_memory_human | String | Total memory used by the module (human readable) | - -### search_query - -| Metric Name | Unit | Description | -| :--- | :---: | :--- | -| search_failure_requests_count | Count | Total failed query requests | -| search_hybrid_requests_count | Count | Hybrid queries (vector and non-vector) | -| search_inline_filtering_requests_count | Count | Queries using inline filtering | -| search_nonvector_requests_count | Count | Exclusively non-vector search queries | -| search_prefiltering_requests_count | Count | Queries using pre-filtering | -| search_result_record_dropped_count | Count | Records dropped when search results exceed limits | -| search_successful_requests_count | Count | Total successful query requests | -| search_vector_requests_count | Count | Query requests that include a vector component | - -### search_rdb - -| Metric Name | Unit | Description | -| :--- | :---: | :--- | -| search_rdb_load_failure_cnt | Count | Failed RDB load operations | -| search_rdb_load_success_cnt | Count | Successful RDB load operations | -| search_rdb_save_failure_cnt | Count | Failed RDB save operations | -| search_rdb_save_success_cnt | Count | Successful RDB save operations | - -### search_string_interning - -| Metric Name | Unit | Description | -| :--- | :---: | :--- | -| search_string_interning_store_size | Count | Unique strings in the interning store | - -### search_thread-pool - -| Metric Name | Unit | Description | -| :--- | :---: | :--- | -| search_query_queue_size | Count | Current reader thread pool queue size | -| search_reader_resumed_cnt | Count | Times the reader thread pool was resumed | -| search_used_read_cpu | Decimal fractions | Average CPU used by reader threads (-1 if unavailable) | -| search_used_write_cpu | Decimal fractions | Average CPU used by writer threads (-1 if unavailable) | -| search_worker_pool_suspend_cnt | Count | Times the worker thread pool was suspended | -| search_writer_queue_size | Count | Current writer thread pool queue size | -| search_writer_resumed_cnt | Count | Times the writer thread pool was resumed | -| search_writer_suspension_expired_cnt | Count | Times writer suspension expired due to timeout | - -### search_vector_externing - -| Metric Name | Unit | Description | -| :--- | :---: | :--- | -| search_vector_externing_deferred_entry_cnt | Count | Deferred entries in vector externalization | -| search_vector_externing_entry_count | Count | Total entries in the vector externalizer | -| search_vector_externing_generated_value_cnt | Count | Generated values during vector externalization | -| search_vector_externing_hash_extern_errors | Count | Errors during hash externalization | -| search_vector_externing_lru_promote_cnt | Count | LRU promotions in vector externalization | -| search_vector_externing_num_lru_entries | Count | Entries in the vector externalizer LRU cache | - -### search_latency - -| Metric Name | Unit | Description | -| :--- | :---: | :--- | -| search_flat_vector_index_search_latency_usec | Microseconds | Latency distribution for flat vector index searches | -| search_hnsw_vector_index_search_latency_usec | Microseconds | Latency distribution for HNSW vector index searches | - -### search_coordinator - -These metrics are only available when cluster mode is enabled. - -| Metric Name | Unit | Description | -| :--- | :---: | :--- | -| search_coordinator_bytes_in | Bytes | Total incoming gRPC response bytes from remote nodes | -| search_coordinator_bytes_out | Bytes | Total outgoing gRPC request bytes to remote nodes | -| search_coordinator_client_get_global_metadata_failure_count | Count | Failed client requests to get global metadata | -| search_coordinator_client_get_global_metadata_failure_latency_usec | Microseconds | Latency for failed client metadata requests | -| search_coordinator_client_get_global_metadata_success_count | Count | Successful client requests to get global metadata | -| search_coordinator_client_get_global_metadata_success_latency_usec | Microseconds | Latency for successful client metadata requests | -| search_coordinator_client_search_index_partition_failure_count | Count | Failed client searches on index partitions | -| search_coordinator_client_search_index_partition_failure_latency_usec | Microseconds | Latency for failed partition searches | -| search_coordinator_client_search_index_partition_success_count | Count | Successful client searches on index partitions | -| search_coordinator_client_search_index_partition_success_latency_usec | Microseconds | Latency for successful partition searches | -| search_coordinator_server_get_global_metadata_failure_count | Count | Failed server requests to get global metadata | -| search_coordinator_server_get_global_metadata_success_count | Count | Successful server requests to get global metadata | -| search_coordinator_server_get_global_metadata_failure_latency_usec | Microseconds | Latency for failed server metadata requests | -| search_coordinator_server_get_global_metadata_success_latency_usec | Microseconds | Latency for successful server metadata requests | -| search_coordinator_server_listening_port | Port | Port the coordinator server is listening on | -| search_coordinator_server_search_index_partition_failure_count | Count | Failed server searches on index partitions | -| search_coordinator_server_search_index_partition_failure_latency_usec | Microseconds | Latency for failed server partition searches | -| search_coordinator_server_search_index_partition_success_count | Count | Successful server searches on index partitions | -| search_coordinator_server_search_index_partition_success_latency_usec | Microseconds | Latency for successful server partition searches | -| search_coordinator_threads_cpu_time_sec | Seconds | Cumulative CPU time consumed by coordinator (gRPC) threads | - -## Configurations - -The search module uses the Valkey configuration mechanism. Thus each of the named configuration below can be set on the `MODULE LODEX` command OR via the `CONFIG SET` command. - -| Name | Type | Default Value | Description | -| :--- | :---: | :---: | :--- | -| search.query-string-bytes | Number | 10240 | Maximum allowable length of the query string for FT.SEARCH or FT.AGGREGATE commands | -| search.hnsw-block-size | Number | 10240 | Number of vectors of space to add to HNSW index size when additional space required. | -| search.reader-threads | Number | Physical core count | Reader thread pool size; dynamically resizes pool on modification | -| search.writer-threads | Number | Physical core count | Writer thread pool size; dynamically resizes pool on modification | -| search.utility-threads | Number | 1 | Utility thread pool size; dynamically resizes pool on modification | -| search.max-worker-suspension-secs | Number | 60 | Controls how long the worker thread pool quiescing around a fork. Values > 0 are resumption timeouts if a fork runs too long. Values <=0 mean no quiescing. | -| search.skip-rdb-load | Boolean | false | When enabled, loads index schemas from the RDB but ignores all stored index content. This initializes empty, functional indexes that are then repopulated from the underlying data source. Use this to ensure a clean index state or to recover from corrupted index. | -| search.skip-corrupted-internal-update-entries | Boolean | false | Skip corrupted AOF entries during internal updates. May be useful for recovering from a corrupted AOF file. | -| search.log-level | Enum | from core | Controls module log level verbosity: "debug", "verbose", "notice" or "warning". Default value is to fetch the log level from the core at startup. | -| search.enable-partial-results | Boolean | true | Default option for delivering partial results when errors such as timeout occur. This applies a default behavior on commands which can be explicitly overridden by FT.INFO/FT.SEARCH commands using the SOMESHARDS (for partial results) option and the ALLSHARDS (for complete results) option. | -| search.enable-consistent-results | Boolean | false | Default option for delivering consistent results when errors such as timeout occur. This applies a default behavior on commands which can be explicitly overridden by FT.INFO/FT.SEARCH commands using the CONSISTENT/INCONSISTENT option.| -| search.search-result-background-cleanup | Boolean | false | Enable search result cleanup on background thread | -| search.high-priority-weight | Number | 100 | Fairness for high priority tasks in thread pools [0..100]. | -| search.local-fanout-queue-wait-threshold | Number | 50 | When this value is less than the average read queue wait time (in milliSeconds) the local node is preferred in a fanout operation. | -| search.thread-pool-wait-time-samples | Number | 100 | Sample queue size for thread pool wait time tracking | -| search.tag-min-prefix-length | Number | 2 | Minimum number of characters required before trailing `*` in TAG wildcard queries (length excludes `*`) | -| search.max-term-expansions | Number | 200 | Maximum number of words to search in text operations (prefix, suffix, fuzzy) to limit memory usage | -| search.search-result-buffer-multiplier | String | 1.5 | Multiplier for search result buffer size to handle rapid data changes. This ensures results are not dropped when concurrent mutations render in-flight data invalid before the response is sent. | -| search.drain-mutation-queue-on-save | Boolean | false | Drain the mutation queue before RDB save. | -| search.query-string-depth | Number | 1000 | Controls the depth of the query string parsing from the FT.SEARCH cmd | -| search.query-string-terms-count | Number | 1000 | Controls the size of the query string parsing from the FT.SEARCH cmd (number of nodes in predicate tree) | -| search.fuzzy-max-distance | Number | 3 | Controls the maximum allowed edit distance for fuzzy search queries | -| search.max-vector-knn | Number | 10000 | Controls the max KNN parameter for vector search | -| search.proximity-inorder-compat-mode | Boolean | false | Enables / disables the overlap violation check logic in Proximity searches when INORDER is enabled. Use this to allow overlapping intersection blocks within the query string. | -| search.max-prefixes | Number | 8 | Controls the max number of prefixes per index | -| search.max-tag-field-length | Number | 256 | Controls the max length of a tag field | -| search.max-numeric-field-length | Number | 128 | Controls the max length of a numeric field | -| search.max-vector-attributes | Number | 1000 | Controls the max number of attributes per index | -| search.max-vector-dimensions | Number | 32768 | Controls the max dimensions for vector indices | -| search.max-vector-m | Number | 2000000 | Controls the max M parameter for HNSW algorithm | -| search.max-vector-ef-construction | Number | 1000000 | Controls the max EF construction parameter for HNSW algorithm | -| search.max-vector-ef-runtime | Number | 1000000 | Controls the max EF runtime parameter for HNSW algorithm | -| search.default-timeout-ms | Number | 50000 | Controls the default timeout in milliseconds for FT.SEARCH | -| search.max-search-result-record-size | Number | 5242880 | Controls the max content size for a record in the search response | -| search.max-search-result-fields-count | Number | 500 | Controls the max number of fields in the content of the search response | -| search.backfill-batch-size | Number | 10240 | Controls the batch size for backfilling indexes | -| search.coordinator-query-timeout-secs | Number | 120 | Controls the gRPC deadline timeout (in seconds) for distributed coordinator query operations. | -| search.max-indexes | Number | 1000 | Controls the maximum number of search indexes that can be created in the system | -| search.async-fanout-threshold | Number | 30 | Controls the threshold for async fanout operations (minimum number of targets to use async) | -| search.max-nonvector-search-results-fetched | Number | 100000 | Controls the maximum number of results to fetch in background threads before content fetching on non-vector (numeric/tag/text) query paths | -| search.max-attributes | Number | 1000 | Controls the max number of attributes per index | -| search.cluster-map-expiration-ms | Number | 250 | Controls how long (in milliseconds) the coordinator caches the cluster topology map before refreshing it from the Valkey cluster. | -| search.max-mutation-queue-size-on-restore | Number | 10000 | Controls the maximum mutation queue size during RDB load. If the queue exceeds this threshold, the restore process yields to the main thread, allowing the queue to be processed before continuing ingestion. This prevents excessive memory overhead. | diff --git a/topics/search-observables.md b/topics/search-observables.md deleted file mode 100644 index 3f3df330..00000000 --- a/topics/search-observables.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -title: "Valkey Search - INFO SEARCH Metrics" -description: Valkey Search Module INFO SEARCH Metrics ---- - -# INFO SEARCH metrics - -Only Application metrics are listed here. These are kept compatible across releases. Developer metrics are hidden unless -`search.info-developer-visible` is set to `yes`, and may change or be removed in any release without notice. - -Some metrics are reported only when they apply. The `coordinator_*` metrics appear only when the module is loaded with -`--use-coordinator`. Metrics ending in `_latency_usec` additionally appear only after at least one sample has been recorded. - -Valkey prefixes each field with `search_` and each section with `search_` in `INFO` output, so `compatibility_usage` appears as -`search_compatibility_usage` in section `search_compatibility`. - -| Metric Name | Section | Unit | Description | -| :--------------------------------------------------------------- | :----------------: | :----------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `compatibility_usage` | `compatibility` | String | Comma-separated `label=count` list of legacy behaviors used because `search.emulate-release` is below the release that fixed them (see below) | -| `coordinator_bytes_in` | `coordinator` | Bytes | Total size (in bytes) of incoming gRPC response messages received by the coordinator client from remote nodes | -| `coordinator_bytes_out` | `coordinator` | Bytes | Total size (in bytes) of outgoing gRPC request messages sent by the coordinator client to remote nodes | -| `coordinator_client_get_global_metadata_failure_count` | `coordinator` | Count | Count of failed client requests to get global metadata | -| `coordinator_client_get_global_metadata_failure_latency_usec` | `coordinator` | Microseconds | Latency distribution (in microseconds) for failed client metadata requests | -| `coordinator_client_get_global_metadata_success_count` | `coordinator` | Count | Count of successful client requests to get global metadata | -| `coordinator_client_get_global_metadata_success_latency_usec` | `coordinator` | Microseconds | Latency distribution (in microseconds) for successful client metadata requests | -| `coordinator_client_search_index_partition_failure_count` | `coordinator` | Count | Count of failed client searches on index partitions | -| `coordinator_client_search_index_partition_failure_latency_usec` | `coordinator` | Microseconds | Latency distribution (in microseconds) for failed partition searches | -| `coordinator_client_search_index_partition_success_count` | `coordinator` | Count | Count of successful client searches on index partitions | -| `coordinator_client_search_index_partition_success_latency_usec` | `coordinator` | Microseconds | Latency distribution (in microseconds) for successful partition searches | -| `coordinator_server_get_global_metadata_failure_count` | `coordinator` | Count | Count of failed server requests to get global metadata | -| `coordinator_server_get_global_metadata_failure_latency_usec` | `coordinator` | Microseconds | Latency distribution (in microseconds) for failed server metadata requests | -| `coordinator_server_get_global_metadata_success_count` | `coordinator` | Count | Count of successful server requests to get global metadata | -| `coordinator_server_get_global_metadata_success_latency_usec` | `coordinator` | Microseconds | Latency distribution (in microseconds) for successful server metadata requests | -| `coordinator_server_listening_port` | `coordinator` | Port | The port number the coordinator server is listening on | -| `coordinator_server_search_index_partition_cpu_time_usec` | `coordinator` | Microseconds | Cumulative CPU time (in microseconds) spent handling remote query operations on this node | -| `coordinator_server_search_index_partition_failure_count` | `coordinator` | Count | Count of failed server searches on index partitions | -| `coordinator_server_search_index_partition_failure_latency_usec` | `coordinator` | Microseconds | Latency distribution (in microseconds) for failed server partition searches | -| `coordinator_server_search_index_partition_success_count` | `coordinator` | Count | Count of successful server searches on index partitions | -| `coordinator_server_search_index_partition_success_latency_usec` | `coordinator` | Microseconds | Latency distribution (in microseconds) for successful server partition searches | -| `coordinator_threads_cpu_time_sec` | `coordinator` | Seconds | Cumulative CPU time consumed by coordinator (gRPC) threads | -| `hnsw_add_exceptions_count` | `hnswlib` | Count | Count of exceptions during HNSW vector additions | -| `hnsw_create_exceptions_count` | `hnswlib` | Count | Count of exceptions during HNSW vector creation | -| `hnsw_modify_exceptions_count` | `hnswlib` | Count | Count of exceptions during HNSW vector modifications | -| `hnsw_remove_exceptions_count` | `hnswlib` | Count | Count of exceptions during HNSW vector removals | -| `hnsw_search_exceptions_count` | `hnswlib` | Count | Count of exceptions during HNSW vector searches | -| `number_of_attributes` | `index_stats` | Count | Total count of all attributes across all search indexes | -| `number_of_indexes` | `index_stats` | Count | Total number of search indexes | -| `num_cursors` | `cursors` | Count | Number of open cursors created by `WITHCURSOR` | -| `total_active_write_threads` | `index_stats` | Count | Number of active writer threads (0 if suspended, otherwise the writer thread pool size) | -| `total_indexed_documents` | `index_stats` | Count | Total number of indexed documents across all search indexes | -| `background_indexing_status` | `indexing` | String | Background indexing status: IN_PROGRESS or NO_ACTIVITY | -| `flat_vector_index_search_latency_usec` | `latency` | Microseconds | Latency distribution (in microseconds) for flat vector index searches | -| `hnsw_vector_index_search_latency_usec` | `latency` | Microseconds | Latency distribution (in microseconds) for HNSW vector index searches | -| `index_reclaimable_memory` | `memory` | Bytes | Track memory that can be reclaimed after vector deletions | -| `used_memory_bytes` | `memory` | Bytes | Total memory used by the module (in bytes) | -| `used_memory_human` | `memory` | String | Total memory used by the module (in human readable format) | -| `successful_requests_count` | `query` | Count | Total count of successful query requests | -| `failure_requests_count` | `query` | Count | Total count of failed query requests | -| `hybrid_requests_count` | `query` | Count | Count of KNN queries that also have a non-vector filter, for example `@color:{red}=>[KNN 10 @vec $v]`, including an `FT.HYBRID` `VSIM` arm with `FILTER`. It does not count `FT.HYBRID` commands as such | -| `nonvector_requests_count` | `query` | Count | Number of requests that are exclusively non-vector search queries, including vector range (`VECTOR_RANGE`) queries and the `SEARCH` arm of `FT.HYBRID` | -| `vector_requests_count` | `query` | Count | Number of KNN queries without a filter, for example `*=>[KNN 10 @vec $v]`. An `FT.HYBRID` `VSIM` arm without `FILTER` is not counted | -| `inline_filtering_requests_count` | `query` | Count | Count of queries using inline filtering | -| `prefiltering_requests_count` | `query` | Count | Count of queries using pre-filtering | -| `result_record_dropped_count` | `query` | Count | Tracks records dropped when FT.SEARCH results exceed configured limits | -| `vector_range_results_fetched_limited_count` | `query` | Count | Count of `VECTOR_RANGE` queries whose results were truncated on this shard. See [Result limit](search-query.md#result-limit). | -| `rdb_load_failure_cnt` | `rdb` | Count | Number of failed RDB load operations | -| `rdb_load_success_cnt` | `rdb` | Count | Number of successful RDB load operations | -| `rdb_save_failure_cnt` | `rdb` | Count | Number of failed RDB save operations | -| `rdb_save_success_cnt` | `rdb` | Count | Number of successful RDB save operations | -| `string_interning_store_size` | `string_interning` | Count | Number of unique strings in the interning store | -| `query_queue_size` | `thread-pool` | Count | Current size of the reader thread pool queue | -| `reader_resumed_cnt` | `thread-pool` | Count | Number of times the reader worker thread pool was resumed | -| `used_read_cpu` | `thread-pool` | Percent | Average CPU percentage used by reader threads (returns -1 if unavailable) | -| `used_write_cpu` | `thread-pool` | Percent | Average CPU percentage used by writer threads (returns -1 if unavailable) | -| `worker_pool_suspend_cnt` | `thread-pool` | Count | Number of times the worker thread pool was suspended | -| `writer_queue_size` | `thread-pool` | Count | Current size of the writer thread pool queue | -| `writer_resumed_cnt` | `thread-pool` | Count | Number of times the writer worker thread pool was resumed | -| `writer_suspension_expired_cnt` | `thread-pool` | Count | Number of times writer suspension expired due to timeout | -| `vector_registry_dedup_cnt` | `vector_registry` | Count | Count of vector updates that reused an already registered copy of an identical vector | -| `vector_registry_entry_cnt` | `vector_registry` | Count | Number of vectors currently tracked by the vector registry | -| `vector_registry_pending_unshare_cnt` | `vector_registry` | Count | Number of vectors queued to stop being shared with the engine, after their index was dropped | -| `vector_registry_shared_externally_cnt` | `vector_registry` | Count | Count of vectors successfully shared with the engine's hash field, so only one copy is kept in memory | -| `vector_registry_shared_externally_errors` | `vector_registry` | Count | Count of failed attempts to share a vector with the engine's hash field | -| `vector_registry_sharing_active` | `vector_registry` | Boolean | 1 if vector memory sharing with the engine is enabled, otherwise 0 | - -## Compatibility counters - -The `compatibility_usage` metric is a comma-separated list of `label=count` pairs. Each count is how often a legacy, incompatible -behavior was used because `search.emulate-release` is set below the release that fixed it. See -[Compatibility Defects](https://github.com/valkey-io/valkey-search/blob/main/COMPATIBILITY.md#compatibility-defects) for the full list of labels and what each one changes. The metric -is always reported; a label appears in the list only after its legacy behavior is first used, and an absent label has a count of 0. diff --git a/topics/search-query.md b/topics/search-query.md deleted file mode 100644 index 6da25257..00000000 --- a/topics/search-query.md +++ /dev/null @@ -1,503 +0,0 @@ ---- -title: "Valkey Search - Queries" -description: Valkey Search Module Query Language Syntax, Semantics and Examples ---- - -The query of the `FT.SEARCH` and `FT.AGGREGATE` commands identifies a subset of the keys in the index to be processed by those commands. -The syntax and semantics of the query string is identical for both commands. - -A query has three different formats: pure-vector, hybrid-vector and non-vector. -A non-vector query can also select keys by vector distance, with the [vector range matcher](#vector-range-match). - -# Pure Vector Queries - -A pure-vector query performs a K Nearest Neighbors (KNN) query of a single vector field within the index. - -``` -*=>[ KNN @ $ [EF_RUNTIME ] [AS ] ] -``` - -# Hybrid Vector Queries - -A hybrid query adds a filter expression to indicate which keys within the index are candidates for results. - -``` -=>[ KNN @ $ [EF_RUNTIME ] [HYBRID_POLICY ] [AS ] ] -``` - -# Non-vector Query - -A non-vector query consists solely of a filter: - -``` - -``` - -Where: - -- `` (optional): Filter expression, see below -- `K` (required): The number of nearest neighbor vectors to return. -- `field` (required): The name of a vector field within the specified index. -- `parameter` (required): A `PARAM` name whose corresponding value provides the query vector for the KNN algorithm. - Note that this parameter must be encoded in little-endian byte order using the element type declared by the index (`TYPE FLOAT32`, `FLOAT16` or `BFLOAT16`); see [Supported Data Types](search-data-formats.md#supported-data-types). Its length must therefore be `DIM * 4` bytes for `FLOAT32` and `DIM * 2` bytes for the 16-bit types. -- `EF_RUNTIME ` (optional): Overrides the default value of `EF_RUNTIME` specified when the index was created. `EF_RUNTIME` is valid with the automatic policy and `HYBRID_POLICY BATCHES`. It is rejected with `HYBRID_POLICY ADHOC_BF`, which performs an exact search over the filtered candidates and does not use the HNSW runtime candidate limit. -- `HYBRID_POLICY ` (optional; requires a filter expression or `INKEYS`): Overrides the automatic choice between the two filtered-vector execution paths: - - `ADHOC_BF` evaluates the filter first, then computes exact distances for the matching vectors. - - `BATCHES` searches the vector index first and applies the filter while traversing vector candidates. An explicit `BATCHES` also takes precedence when `INKEYS` is supplied; the named keys remain part of the inline candidate filter. With the automatic policy, `INKEYS` uses filter-first execution. - - When omitted, Valkey Search chooses the path using its existing planner heuristic. -- `AS ` (optional): Overrides the default naming of the output distance field. The name may be `$`, in which case the value of that `PARAMS` entry is used; `K`, `EF_RUNTIME` and `HYBRID_POLICY` can also be given as `$`. By default this field is named `___score`, where `` is the field named in `@` (the attribute's `AS` alias from `FT.CREATE`, if it has one). For example, `@vec` produces `__vec_score`. - -For example, this query forces exact filter-first execution for documents tagged `electronics`: - -``` -FT.SEARCH products "@category:{electronics}=>[KNN 10 @embedding $query_vector HYBRID_POLICY ADHOC_BF]" PARAMS 2 query_vector "" DIALECT 2 -``` - -`HYBRID_POLICY` is accepted only inside the KNN brackets. Query-attribute syntax after the KNN brackets is not supported; for example, the following form returns an error: - -``` -@category:{electronics}=>[KNN 10 @embedding $query_vector]=>{$HYBRID_POLICY: ADHOC_BF} -``` - -`BATCH_SIZE` is not currently supported. - -## Filter Expression - -A filter identifies a set of keys. Filters can be constructed using individual query operator as well as by combining operators with `AND`, `OR`, `NEGATE` operators. - -It is not the case that the of filtering terminology implies an O(N) scan of keys in an index. Valkey search intelligently combines the usage of secondary indexes and simple filtering to efficiently locate the keys that a filter identifies. Determining the computational complexity of a particular filter is difficult, but generally no worse than O(log N) and sometimes as fast as O(1). - -The BNF for a filter is: - -``` - ::= - - ::= - | "|" - ::= - | " " - ::= - | "-" - ::= - | - | - | - | - | - | "(" ")" - | "@" ":(" ")" - | "=>{$weight:" "}" - -``` - -### Tag Match - -The tag match operator is specified with one or more match strings separated by the `|` character. -Tag match supports both exact match and prefix match. -If a match string end with an `*` then prefix matching is performed, otherwise exact matching is performed. -Case insensitive matching can be configured when the field was declared. - -``` -@:{} -or -@:{ | } -or -@:{ | | ...} -``` - -For example, the following query will return documents with blue OR black OR green color. - -``` -@color:{blue | black | green} -``` - -As another example, the following query will return documents containing "hello world" or "hello universe" - -``` -@color:{hello world | hello universe} -``` - -This example will match black or any word that starts with fred: - -``` -@color:{black | fred*} -``` - -For more examples see [Tag Fields](#example-tag-queries). - -### Numeric Range Match - -Numeric range matcher selects keys based on the value of a numeric field being between a given start and end value. -Both inclusive and exclusive range queries are supported. For simple relational comparisons, \+inf, \-inf can be used -with a range query. - -The syntax for a range search operator is: - -``` -@:[ [(] [(] ] -``` - -where is either a decimal integer, floating-point number or ±inf - -Bounds without a leading open paren are inclusive, whereas bounds with the leading open parenthesis are exclusive. - -Use the following table as a guide for mapping mathematical expressions to filtering queries: - -| Desired comparison | Numeric matcher | -| :----------------: | :----------------- | -| min ≤ field ≤ max | @field:[min max] | -| min < field ≤ max | @field:[(min max] | -| min ≤ field < max | @field:[min (max] | -| min < field < max | @field:[(min (max] | -| field ≥ min | @field:[min +inf] | -| field > min | @field:[(min +inf] | -| field ≤ max | @field:[-inf max] | -| field < max | @field:[-inf (max] | -| field = val | @field:[val val] | - -Examples of numeric matchers - -``` -@price:[10 100] 10 ≤ field ≤ 100 -@price:[(10 100.5] 10 < field ≤ 100.5 -@price:[-inf (1e2] price < 100 -``` - -### Vector Range Match - -A `VECTOR_RANGE` matcher selects keys whose vector is within a specified radius of a query vector. It can be combined with other matchers using AND, OR, and negation. - -#### Syntax - -``` -@:[VECTOR_RANGE $ [EF_RUNTIME ] [AS ]] -@:[VECTOR_RANGE $]=>{$YIELD_DISTANCE_AS: } -@:[VECTOR_RANGE $]=>{$EPSILON: } -@:[VECTOR_RANGE $]=>{$YIELD_DISTANCE_AS: ; $EPSILON: } -``` - -- `field-name` (required): A `VECTOR` field of the index. -- `radius` (required): A non-negative floating-point number, or `$` to read the radius from `PARAMS`. A key matches when its distance is less than or equal to the radius. -- `parameter` (required): The name of a `PARAMS` entry containing the query vector, encoded as for a KNN query. -- `EF_RUNTIME ` (optional): Overrides the HNSW field's `EF_RUNTIME` for this query. `` is a literal or `$` to read the value from `PARAMS`. It must be an integer from 1 through `search.max-vector-ef-runtime`. It is ignored for `FLAT` fields. -- `AS ` or `$YIELD_DISTANCE_AS: ` (optional): Makes the distance available as ``. When `RETURN` is used, it must list `` to return the distance. `SORTBY` and `FT.AGGREGATE` stages can also use the name. `FT.SEARCH` rejects a name that is already an index attribute; `FT.AGGREGATE` accepts it and resolves `@` to the distance. -- `$EPSILON: ` (optional): Controls how far an HNSW search explores beyond the radius. Use a value greater than 0. It is rejected for `FLAT` fields. - -The keyword and attribute names are case-insensitive. - -Restrictions: - -- A query can contain at most one `VECTOR_RANGE` matcher. -- `VECTOR_RANGE` cannot be used in the filter of a KNN query. -- Query attributes must directly follow the closing `]`. For example, `(@v:[VECTOR_RANGE 0.2 $vec])=>{$YIELD_DISTANCE_AS: dist}` is invalid. -- Query attribute values cannot be read from `PARAMS`. -- `$weight` is not a supported `VECTOR_RANGE` attribute. - -#### Distances and ordering - -The radius uses the distance metric configured for the field: - -- `L2`: Squared Euclidean distance. To match keys within Euclidean distance `d`, use radius `d²`. For example, use `0.25` for distance `0.5`. -- `IP`: `1 - dot(X,Y)`. The distance can be negative for unnormalized vectors. A radius of 0 matches vectors whose dot product with the query vector is at least 1. -- `COSINE`: Floating-point rounding can make the distance between identical vectors slightly greater than 0. Use a small positive radius when searching for identical vectors. - -`VECTOR_RANGE` results are not sorted by distance. To return the closest keys first, yield the distance and use `SORTBY ASC`. `WITHSCORES` returns the relevance score from other matchers, or 0 when there are none. - -The `VECTOR_RANGE` matcher does not match a key when its computed distance is NaN or positive infinity, even when the radius is `inf`. An `IP` distance of negative infinity matches every valid radius. - -#### Result limit - -`search.max-nonvector-search-results-fetched`, which defaults to 100000, limits how many matching keys each shard retains. If more keys match, the shard drops the additional matches without returning an error. The reported total includes only retained keys, and the retained keys are not guaranteed to be the nearest matches. - -In a cluster, each shard applies the limit independently, so a query can retain up to `number of shards × limit` keys before command-level pagination. `SORTBY`, `LIMIT`, aggregation stages, reducers, and cursors operate on the retained keys and cannot recover dropped matches. - -With `INKEYS`, each shard evaluates only the listed keys before applying the result limit. - -A limit of 0 returns no keys. The `search_vector_range_results_fetched_limited_count` INFO counter increments once on each shard that confirms at least one matching key was dropped. A query with exactly the configured number of matches does not increment it. - -#### HNSW search - -`FLAT` evaluates vector distances exactly. `HNSW` uses the graph and can miss keys that are within the radius. - -A larger `EF_RUNTIME` can improve HNSW recall by examining more graph candidates, at the cost of more distance calculations. If the query does not provide `EF_RUNTIME`, the field's configured value is used. - -HNSW also explores vectors within `radius × (1 + epsilon)` so it can reach matching vectors through nearby graph nodes outside the radius. Only vectors within the original radius are returned. The default epsilon is `0.01`; a larger value can improve recall but performs more work. With `INKEYS`, the listed keys are checked directly, so `EF_RUNTIME` and `$EPSILON` do not affect execution. - -#### Compound queries - -The result limit is applied to unique keys after the complete AND, OR, and negation expression is evaluated. - -A key can match through another branch of an OR expression while remaining outside the vector radius. The key stays in the result, but it has no yielded VECTOR_RANGE distance. When sorting by the distance, keys without one appear after keys with a distance for both `ASC` and `DESC`. - -For examples, see [Example Vector Range Queries](#example-vector-range-queries). - -## Text Search Operators - -Unlike the other search operators. The text search operators do not require that a field be specified. If a field is not specified for a text search operator, then all text fields within the index are searched. Regardless, if multiple text search operators are combined in an expression, then only keys which have all of the text search operators will satisfy the query. - -With `search.emulate-release` 1.3.0 or later, a query that is not valid UTF-8 fails with `Invalid UTF-8 in query expression`. See [COMPATIBILITY.md](https://github.com/valkey-io/valkey-search/blob/main/COMPATIBILITY.md). - -### Field-scoped Groups - -A field followed by a parenthesized expression applies the field to every text term inside the parentheses. - -``` -@title:(hello | world) same as @title:hello | @title:world -@title:(red shoes) same as @title:red @title:shoes -``` - -Only text terms (term, prefix, suffix, fuzzy and exact phrase) may appear inside the parentheses. A field modifier inside the group, such as `@title:(red | @body:shoes)`, is a syntax error, and empty parentheses are rejected. - -### Term Search - -The term search operator matches a single word. If the word is a stop word, the term search operator is removed from the query expression. -Term searches are subject to stemming unless the `VERBATIM` option is specified. - -Examples include: - -``` -hello matches the word hello in any text field -@t:hello matches the word hello but only in the t field (t must be a text field) -``` - -### Prefix Matching - -A term with a trailing `*` matches any word that starts with that term. - -``` -hello* matches words that start with hello such as hello, hello1, hello_world but not ohello -@t:hello* matches words that start with hello in the t field (t must be a text field) -``` - -### Suffix Matching - -A term with a leading `*` matches any word that ends with that term. - -Note that suffix searching will only locate words in fields that have `WITHSUFFIXTRIE` specified, i.e., fields declared with `NOSUFFIXTRIE` will not be searched. -Without a field specifier, a suffix term searches every text field that has `WITHSUFFIXTRIE`; if no text field has it, an error is issued. -If a field specifier is added to a suffix term search and that particular field was declared with `NOSUFFIXTRIE` then an error will be issued. - -``` -*hello matches words that end with hello such as hello, ohello but not hello1 -@t:*hello matches words that end with hello in the t field (t must be a text field with WITHSUFFIXTRIE) -``` - -### Exact Phrase Search - -The exact phrase search operator matches an exact sequence of words in a text field. The words to be matched are enclosed in double quotes. Each word in a phrase is matched exactly; prefix, suffix and fuzzy operators are not supported inside a phrase. The words are not subject to stop word removal nor stemming, otherwise this is equivalent to having the same words in a query with `SLOP 0` and `INORDER` options being specified. - -Note: with `search.emulate-release` 1.3.0 or later, single quotes also delimit a phrase, for example `'hello world'`; with the default setting (1.0.0), single quotes are treated as punctuation. - -``` -"hello world" matches the exact phrase "hello world" in any text field -@t:"hello world" matches the exact phrase "hello world" in the t field (t must be a text field) -``` - -### Fuzzy Search - -The fuzzy search operator matches words within a fixed damerau-levenshtein distance. See [damerau-levenshtein edit distance](https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance) for more information. Fuzzy matching is specified by enclosing the base word in percent symbols `%` one for each allowable edit distance. The maximum allowed edit distance is control by the configuration setting `search.fuzzy-max-distance`. - -``` -%hello% matches words that are one edit away from hello such as hello, hello1 -%%hello%% matches words that are two edits away from hello such as hello, hello1, ohello, hllo -@t:%hello% matches words that are one edit away from hello but only in the t field -%%hello% Error: leading and trailing count % count are different -``` - -## Query Weights - -A `=>{$weight: }` attribute after a term, a matcher or a parenthesized group multiplies the relevance score of that clause. The weight must be a non-negative, finite number, and `$weight` is the only supported attribute. See [Query Weights](search-scoring.md#query-weights). - -``` -jacket=>{$weight: 2.0} -jacket (@color:{red})=>{$weight: 2.0} -``` - -## Logical Operators - -### Logical Negation - -Any query can be negated by prepending the `-` character before each query. Negative queries return all keys that don't match the query. This also includes keys that don't have the field. - -For example, the negative query `-@genre:{comedy}` will return all books that are not comedy AND all books that don't have a genre field. - -The following query will return all books with "comedy" genre that are not published between 2015 and 2024, or that have no year field: - -``` -@genre:{comedy} -@year:[2015 2024] -``` - -### Logical `OR` - -To set a logical OR, use the `|` character between the predicates. - -Example: - -``` -query1 | query2 | query3 -``` - -### Logical `AND` - -To specify the `AND` operation use a space between the predicates. If the `INORDER` and `SLOP` options are not provided then the `AND` operation is done at the key level. This means that any key which satisfies each of the predicates will match. - -If either of the `INORDER` or `SLOP` options are provided, then the `AND` operation is extended beyond simple key matching to also include positional matching of the text searching operators. Positional matching requires that each predicate not only match the same key but that the text searching operators (term, prefix, suffix, exact phrase and fuzzy) must also match words that satisfy the requirements of `INORDER` and `SLOP` in the same field of the same key. - -For example: - -``` -query1 query2 query3 -``` - -### Proximity `AND` - -When two or more predicates of an AND operation contain text matchers, it becomes possible to also perform positional matching. Positional matching extends key-based matching to additionally require that matching words meet specified distance and ordering constraints. Positional matching is only applied within a single Text field. There is no positional relationship between terms in different Text fields. - -Position matching is enabled when either the `SLOP` or `INORDER` clauses are used on the command and applies to all multi-predicate AND operations within the current command. - -# Examples - -## Example Tag Queries - -For these examples, the following index declaration and data set will be used. - -``` -valkey-cli FT.CREATE index SCHEMA color TAG -valkey-cli HSET key1 color blue -valkey-cli HSET key2 color black -valkey-cli HSET key3 color green -valkey-cli HSET key4 color beige -valkey-cli HSET key5 color "beige,green" -valkey-cli HSET key6 color "hello world, green is my heart" -``` - -### Simple Tag Query - -``` -valkey-cli FT.SEARCH index @color:{blue} RETURN 1 color -1) (integer) 1 -2) "key1" -3) 1) "color" - 2) "blue" -``` - -### Multiple Tag Query - -``` -valkey-cli FT.SEARCH index "@color:{blue | black}" RETURN 1 color -1) (integer) 2 -2) "key2" -3) 1) "color" - 2) "black" -4) "key1" -5) 1) "color" - 2) "blue" -``` - -### Prefix Tag Query - -``` -valkey-cli FT.SEARCH index @color:{b\*} RETURN 1 color -1) (integer) 4 -2) "key2" -3) 1) "color" - 2) "black" -4) "key1" -5) 1) "color" - 2) "blue" -6) "key4" -7) 1) "color" - 2) "beige" -8) "key5" -9) 1) "color" - 2) "beige,green" -``` - -### Complex Tag Query - -``` -valkey-cli FT.SEARCH index @color:{b*|green} RETURN 1 color -1) (integer) 2 -2) "key3" -3) 1) "color" - 2) "green" -4) "key5" -5) 1) "color" - 2) "beige,green" -``` - -## Example Logical Operators - -Logical operators can be combined to form complex filter expressions. - -The following query will return all books with "comedy" or "horror" genre (AND) published between 2015 and 2024: - -``` - -@genre:{comedy|horror} @year:[2015 2024] - -``` - -The following query will return all books with "comedy" or "horror" genre (OR) published between 2015 and 2024: - -``` - -@genre:{comedy|horror} | @year:[2015 2024] - -``` - -The following query will return all books that either don't have a genre field, or have a genre field not equal to "comedy", -that are published between 2015 and 2024: - -``` --@genre:{comedy} @year:[2015 2024] - -``` - -## Example Vector Range Queries - -For these examples, the following index and data are used. The commands are entered at the `valkey-cli` prompt, which decodes the `\x` escapes of the vectors. The vectors of `p1`, `p2` and `p3` are (1, 0), (0, 2) and (3, 4), and the query vector is (0, 0), so the `L2` distances are 1, 4 and 25. - -``` -FT.CREATE idx SCHEMA category TAG v VECTOR HNSW 6 TYPE FLOAT32 DIM 2 DISTANCE_METRIC L2 -HSET p1 category shoes v "\x00\x00\x80?\x00\x00\x00\x00" -HSET p2 category shirts v "\x00\x00\x00\x00\x00\x00\x00@" -HSET p3 category shoes v "\x00\x00@@\x00\x00\x80@" -``` - -The keys within distance 5, closest first, with their distance: - -``` -FT.SEARCH idx "@v:[VECTOR_RANGE 5 $vec]=>{$YIELD_DISTANCE_AS: dist}" PARAMS 2 vec "\x00\x00\x00\x00\x00\x00\x00\x00" SORTBY dist RETURN 1 dist DIALECT 2 -1) (integer) 2 -2) "p1" -3) 1) "dist" - 2) "1" -4) "p2" -5) 1) "dist" - 2) "4" -``` - -A vector range matcher combined with a tag matcher, with the radius given as a parameter: - -``` -FT.SEARCH idx "@category:{shoes} @v:[VECTOR_RANGE $r $vec]" PARAMS 4 r 30 vec "\x00\x00\x00\x00\x00\x00\x00\x00" NOCONTENT DIALECT 2 -1) (integer) 2 -2) "p1" -3) "p3" -``` - -The closest distance per category: - -``` -FT.AGGREGATE idx "@v:[VECTOR_RANGE 30 $vec]=>{$YIELD_DISTANCE_AS: dist}" PARAMS 2 vec "\x00\x00\x00\x00\x00\x00\x00\x00" GROUPBY 1 @category REDUCE MIN 1 @dist AS closest SORTBY 2 @closest ASC DIALECT 2 -1) (integer) 2 -2) 1) category - 2) "shoes" - 3) closest - 4) "1" -3) 1) category - 2) "shirts" - 3) closest - 4) "4" -``` diff --git a/topics/search-scoring-examples.md b/topics/search-scoring-examples.md deleted file mode 100644 index f789ffc0..00000000 --- a/topics/search-scoring-examples.md +++ /dev/null @@ -1,274 +0,0 @@ ---- -title: "Valkey Search - Scoring Examples" -description: Worked scoring example and recipes to tune the ranking of Valkey Search results ---- - -These examples use the scores described in [Search - Scoring](search-scoring.md). -They require Valkey Search 1.3.0 or later. -They omit `SCORER`, so they use the scorer set by `search.default-scorer` (default `BM25STD`). - -# Read and Check Scores - -In this example, you build a four-product index, check one score against the formula, and see how stemming, extra clauses, and a document score change the scores. - -1. Create an index with a text field, a tag field, a numeric field, and a document score field: - - ``` - > FT.CREATE products ON HASH PREFIX 1 product: SCORE_FIELD boost SCHEMA title TEXT color TAG price NUMERIC - OK - ``` - -2. Add four products: - - ``` - > HSET product:1 title "red running shoes" color red price 80 - (integer) 3 - > HSET product:2 title "trail running shoes" color blue price 120 - (integer) 3 - > HSET product:3 title "blue rain jacket" color blue price 150 - (integer) 3 - > HSET product:4 title "wool socks" color red price 15 - (integer) 3 - ``` - -3. Search for `jacket` and return the scores: - - ``` - > FT.SEARCH products jacket WITHSCORES NOCONTENT - 1) (integer) 1 - 2) "product:3" - 3) "1.16080248356" - ``` - - The reply contains one key and its score. - -4. Compute the score by hand. - The index has `N = 4` keys. One key contains `jacket`, so `n = 1`. - `product:3` contains `jacket` once, so `f = 1`. Its title has 3 words, so `dl = 3`. - The titles have 3, 3, 3, and 2 words, so `avgdl = 11 / 4 = 2.75`. - - ``` - IDF = ln(1 + (4 - 1 + 0.5) / (1 + 0.5)) = 1.20397 - TF part = (1 * 2.2) / (1 + 1.2 * (0.25 + 0.75 * 3 / 2.75)) = 0.96414 - term score = 1.20397 * 0.96414 = 1.16080 - ``` - - The TF part is the part of the [term score formula](search-scoring.md#term-score) after `IDF`. The `weight` is 1.0. - - The document score of `product:3` is 1.0, because the key has no `boost` field and the index has no `SCORE` option. - The final score is thus 1.16080, which agrees with the reply. - -5. Search for `running` with and without `VERBATIM`: - - ``` - > FT.SEARCH products running WITHSCORES NOCONTENT - 1) (integer) 2 - 2) "product:1" - 3) "1.33658659458" - 4) "product:2" - 5) "1.33658659458" - > FT.SEARCH products running WITHSCORES NOCONTENT VERBATIM - 1) (integer) 2 - 2) "product:1" - 3) "0.668293297291" - 4) "product:2" - 5) "0.668293297291" - ``` - - `running` is the only indexed word with the stem `run`, so the exact-match bonus doubles the score. - -6. Combine a text clause with a tag clause and with a numeric clause, then run the text clause and the tag clause alone: - - ``` - > FT.SEARCH products "shoes @color:{red}" WITHSCORES NOCONTENT - 1) (integer) 1 - 2) "product:1" - 3) "2.00487995148" - > FT.SEARCH products "shoes @price:[0 100]" WITHSCORES NOCONTENT - 1) (integer) 1 - 2) "product:1" - 3) "1.33658659458" - > FT.SEARCH products shoes WITHSCORES NOCONTENT - 1) (integer) 2 - 2) "product:1" - 3) "1.33658659458" - 4) "product:2" - 5) "1.33658659458" - > FT.SEARCH products "@color:{red}" WITHSCORES NOCONTENT - 1) (integer) 2 - 2) "product:4" - 3) "0.780193567276" - 4) "product:1" - 5) "0.668293297291" - ``` - - The first query scores `product:1` at 2.00487995148. - This is the score of `shoes` (1.33658659458) plus the score of `@color:{red}` (0.668293297291). - The second query scores `product:1` at 1.33658659458, the same as `shoes` alone, because the numeric clause contributes 0. - -7. Set a document score of 0.5 on `product:1` and search again: - - ``` - > HSET product:1 boost 0.5 - (integer) 1 - > FT.SEARCH products running WITHSCORES NOCONTENT - 1) (integer) 2 - 2) "product:2" - 3) "1.33658659458" - 4) "product:1" - 5) "0.668293297291" - ``` - - The score of `product:1` is half of its previous score, so `product:1` now sorts after `product:2`. - -# Tune the Ranking - -The recipes in this section use this index and data: - -``` -> FT.CREATE p ON HASH PREFIX 1 p: SCHEMA title TEXT body TEXT color TAG sales NUMERIC -OK -> HSET p:1 title "rain jacket" body "a light coat" color red sales 10 -(integer) 4 -> HSET p:2 title "wool coat" body "warm jacket for winter" color blue sales 900 -(integer) 4 -> HSET p:3 title "red hat" body "matches any jacket" color red sales 50 -(integer) 4 -> HSET p:4 title "blue scarf" body "soft wool" color blue sales 5 -(integer) 4 -``` - -The query `jacket` matches `p:1` with a score of 0.374, and `p:2` and `p:3` with a score of 0.341 each: - -``` -> FT.SEARCH p jacket WITHSCORES NOCONTENT -1) (integer) 3 -2) "p:1" -3) "0.373659491539" -4) "p:2" -5) "0.341167360544" -6) "p:3" -7) "0.341167360544" -``` - -## Find Out Why a Key Has Its Score - -Valkey Search does not return a breakdown of a score. -To find the contribution of each clause, run each clause as a separate query with `WITHSCORES`. -The scores of the clauses of an AND add up to the score of the full query. - -For example, `jacket @color:{red}` gives `p:1` a score of 1.100. -`jacket` alone gives 0.374, and `@color:{red}` alone gives 0.726: - -``` -> FT.SEARCH p "jacket @color:{red}" WITHSCORES NOCONTENT -1) (integer) 2 -2) "p:1" -3) "1.09981369972" -4) "p:3" -5) "1.00417780876" -> FT.SEARCH p "@color:{red}" WITHSCORES NOCONTENT -1) (integer) 2 -2) "p:1" -3) "0.726154208183" -4) "p:3" -5) "0.663010418415" -``` - -## Make Matches in One Field Count More - -To make a match in the title count more than a match in the body, put a `$weight` on the title clause: - -``` -> FT.SEARCH p "(@title:jacket) => {$weight: 3.0} | (@body:jacket)" WITHSCORES NOCONTENT -1) (integer) 3 -2) "p:1" -3) "1.12097847462" -4) "p:2" -5) "0.341167360544" -6) "p:3" -7) "0.341167360544" -``` - -The score of `p:1`, which has `jacket` in its title, increases from 0.374 to 1.121. -The scores of `p:2` and `p:3`, which have `jacket` only in the body, stay at 0.341. - -## Filter Without a Change to the Ranking - -A numeric clause contributes 0, so it filters keys without a change to their scores. -A tag clause adds its own score, so it can change the order of the results. -To filter by a tag without a change to the scores, give the tag clause `$weight: 0`, for example `jacket (@color:{red}) => {$weight: 0}`. -You can also filter in an `FT.AGGREGATE` stage instead of in the query: - -``` -> FT.AGGREGATE p jacket ADDSCORES LOAD 2 @__key @color FILTER "@color == 'red'" SORTBY 2 @__score DESC -1) (integer) 2 -2) 1) __key - 2) "p:1" - 3) __score - 4) "0.373659491539" - 5) color - 6) "red" -3) 1) __key - 2) "p:3" - 3) __score - 4) "0.341167360544" - 5) color - 6) "red" -``` - -The records for `p:1` and `p:3` keep the scores 0.374 and 0.341 that the query `jacket` gives them. -The `LOAD` stage reads the `color` field of each key that matches `jacket`. -This costs more than a filter in the query, which does not read the keys. - -## Promote Keys with a Stored Value - -To rank some keys above others for every query, store a number in each key and name its field with `SCORE_FIELD`. -Valkey Search multiplies the query score of each key by this number. -A key without the field gets the `SCORE` value of the index, which is 1.0 by default. -Thus a value of 2 doubles the score of a key, and a value of 0.5 halves it. -See [Document Score](search-scoring.md#document-score). - -Use this method when the value changes less often than the queries run, for example a product rating. - -## Combine Relevance with Popularity at Query Time - -To combine the score with a numeric field at query time, compute a new value with `APPLY` and sort by it: - -``` -> FT.AGGREGATE p jacket ADDSCORES LOAD 2 @__key @sales APPLY "@__score * log(2 + @sales)" AS rank SORTBY 2 @rank DESC -1) (integer) 3 -2) 1) __key - 2) "p:2" - 3) __score - 4) "0.341167360544" - 5) sales - 6) "900" - 7) rank - 8) "2.32151237533" -3) 1) __key - 2) "p:3" - 3) __score - 4) "0.341167360544" - 5) sales - 6) "50" - 7) rank - 8) "1.34803539034" -4) 1) __key - 2) "p:1" - 3) __score - 4) "0.373659491539" - 5) sales - 6) "10" - 7) rank - 8) "0.928508955282" -``` - -The records are in the order `p:2` (rank 2.322), `p:3` (rank 1.348), and `p:1` (rank 0.929). -`p:1` has the highest score, but `p:2` has many more sales. -The logarithm keeps a large sales value from hiding the score. - -## Combine Text Results with Vector Results - -To rank keys by a text query and by vector similarity together, use [`FT.HYBRID`](../commands/ft.hybrid.md). -See [Score Fusion in Hybrid Search](search-scoring.md#score-fusion-in-hybrid-search). diff --git a/topics/search-scoring.md b/topics/search-scoring.md deleted file mode 100644 index d072f1c5..00000000 --- a/topics/search-scoring.md +++ /dev/null @@ -1,373 +0,0 @@ ---- -title: "Valkey Search - Scoring" -description: How Valkey Search computes relevance scores and uses them to order query results ---- - -A score is a number that Valkey Search computes for each key that matches a query. -A higher score means a better match. -By default, `FT.SEARCH` orders results by score. -A KNN query whose filter has no text or tag clause orders results by vector distance instead. -A `SORTBY` clause overrides both orders. -For a worked example and recipes to tune the ranking, see [Search - Scoring Examples](search-scoring-examples.md). - -# Version Requirement - -Relevance scoring requires Valkey Search 1.3.0 or later. -In earlier releases: - -- `FT.SEARCH` has no `WITHSCORES` or `SCORER` option. -- `FT.CREATE` rejects `SCORE_FIELD` and accepts only `SCORE 1.0`. -- The `FT.HYBRID` command does not exist. - -# What Is a Score? - -A score is a value that shows how relevant a key is to a query. -Valkey Search measures relevance in three ways: - -- Text and tag clauses get a relevance score. A higher score is a better match. See [Text Fields](#text-fields). -- For KNN queries whose filter has no text or tag clause, the vector distance measures relevance. A smaller distance is a better match. See [Vector Fields](#vector-fields). -- `FT.HYBRID` fuses the results of a text search and a vector search into one score. See [Score Fusion in Hybrid Search](#score-fusion-in-hybrid-search). - -The clauses of an `FT.SEARCH` query select the score measure, and that measure sets the default sort order: - -| Query shape | Score measure | Default sort order | -| :--- | :--- | :--- | -| Text or tag clauses, with or without numeric clauses | `BM25STD` score | By score, highest first | -| Only numeric or vector range clauses, or only tag clauses in an index whose schema has no `TEXT` field | 0 for every key | Unspecified | -| KNN query without a filter | Vector distance, in `___score` | By distance, nearest first | -| KNN query with a text or tag clause in its filter | `BM25STD` score of the filter | By score, highest first | -| KNN query with only numeric clauses in its filter | Vector distance, in `___score` | By distance, nearest first | -| Any of the above with `SORTBY` | Unchanged | By the `SORTBY` field | - -The relevance score compares a key with the other keys in the index. -It has no upper limit, and its value depends on the contents of the index as well as on the key and the query. -Thus a score is useful to compare keys in the result of one query, but not to compare results across queries. - -The score of a key can change when the key itself does not change: - -- Another key is added, updated, or deleted. Each of these changes the number of keys, the number of keys that contain each term, and the average key length. See [Text Fields](#text-fields) for how the formula uses them. -- The query changes. Each matched clause adds to the score, so a query with more clauses usually gives higher scores. -- The query uses `$weight`, or the index uses `SCORE` or `SCORE_FIELD`. - -For example: - -``` -> FT.CREATE r ON HASH PREFIX 1 r: SCHEMA title TEXT -OK -> HSET r:1 title "rain jacket" -(integer) 1 -> HSET r:2 title "wool coat" -(integer) 1 -> HSET r:3 title "red hat" -(integer) 1 -> HSET r:4 title "blue scarf" -(integer) 1 -> FT.SEARCH r jacket WITHSCORES NOCONTENT -1) (integer) 1 -2) "r:1" -3) "1.20397281647" -> HSET r:5 title "jacket" -(integer) 1 -> FT.SEARCH r jacket WITHSCORES NOCONTENT -1) (integer) 2 -2) "r:5" -3) "1.0700173378" -4) "r:1" -5) "0.837404847145" -> DEL r:5 -(integer) 1 -> FT.SEARCH r jacket WITHSCORES NOCONTENT -1) (integer) 1 -2) "r:1" -3) "1.20397281647" -``` - -The score of `r:1` decreases from 1.204 to 0.837 after `r:5` is added, although `r:1` did not change. -After `r:5` is deleted, the score of `r:1` is 1.204 again. - -A new score takes effect as soon as Valkey Search indexes the added, updated, or deleted key. - -A fixed score threshold, for example "show only results with a score above 1.0", can behave differently for different queries and as the index changes. -If you use a threshold, test it with the queries and the data that you expect. - -# How Each Field Type Is Scored - -Each clause of a query contributes a score that depends on the type of the field that it matches: - -| Field type | Contribution to the score | -| :--- | :--- | -| `TEXT` | A `BM25STD` score for each matched term. | -| `TAG` | A `BM25STD` score for each matched tag value, with a term frequency of 1. | -| `NUMERIC` | 0. A numeric clause filters keys. It does not change their order. | -| `VECTOR` | The vector distance, returned in `___score`. It does not add to the relevance score. | - -## Text Fields - -The `BM25STD` scorer gives each matched text term a score. These factors change the score: - -- A rare term contributes more than a common term. -- More occurrences of a term increase the score, but each additional occurrence adds less than the previous one. -- A long key gets a lower score than a short key with the same number of occurrences. A search for `jacket` thus ranks the title "rain jacket" above the title "lightweight waterproof rain jacket with hood". - -Stop words are not indexed, so they do not count toward the length of a key. -See [Text Field Format](search-data-formats.md#text-fields) for how Valkey Search splits text into words, removes stop words, and finds word stems. -For the formula and its constants, see [Term Score](#term-score). - -### Stemming Adds an Exact-Match Bonus - -If the queried field uses stemming and the query does not use `VERBATIM`, one term can match several words that have the same stem. -For example, `running` matches `running`, `runs`, and `run`. -A key that contains the exact query word gets a higher score than a key that contains only a different form of the word. -A `$weight` on the term multiplies the scores of all forms of the word. - -### Prefix, Suffix, and Fuzzy Terms - -A prefix term (`run*`), a suffix term (`*ing`), or a fuzzy term (`%runing%`) can match many indexed words. -For each key, the term contributes the score of one matched word. -A term that matches many words in a key thus scores no higher than a term that matches one. - -### Phrases, Slop, and Match-All - -A quoted phrase (`"red running"`) is scored as an AND of its words. -The quoted words are not stemmed. -`SLOP` and `INORDER` change which keys match, but not their scores. -The match-all query `*` ranks short keys above long keys. - -## Tag Fields - -A tag clause such as `@color:{red}` gets a `BM25STD` score, as a text term does. -Each matched tag value counts once per key. A rare tag value scores higher than a common one, and a key with more words in its `TEXT` fields scores lower. Only fields that the schema declares as `TEXT` count. -If the index schema has no `TEXT` field, every tag clause scores 0. - -For example: - -``` -> FT.CREATE t ON HASH PREFIX 1 t: SCHEMA title TEXT color TAG -OK -> HSET t:1 title "rain jacket" color red -(integer) 2 -> HSET t:2 title "warm winter wool coat" color red -(integer) 2 -> HSET t:3 title "blue hat" color blue -(integer) 2 -> FT.SEARCH t "@color:{red}" WITHSCORES NOCONTENT -1) (integer) 2 -2) "t:1" -3) "0.523548364639" -4) "t:2" -5) "0.390191704035" -> FT.SEARCH t "@color:{blue}" WITHSCORES NOCONTENT -1) (integer) 1 -2) "t:3" -3) "1.09256923199" -> FT.CREATE tagonly ON HASH PREFIX 1 t: SCHEMA color TAG -OK -> FT.SEARCH tagonly "@color:{red}" WITHSCORES NOCONTENT -1) (integer) 2 -2) "t:1" -3) "0" -4) "t:2" -5) "0" -``` - -`t:1` and `t:3` both have 2-word titles. -`t:3` scores higher because `blue` is on one key and `red` is on two. -`t:2` scores lower than `t:1` because its title is longer. -The `tagonly` index has no `TEXT` field, so every key scores 0. - -A clause that matches more than one tag value, such as `@color:{red|blue}`, adds the scores of all the matched values that the key has. -A tag prefix, such as `@color:{bl*}`, is an exception. It contributes the score of one matched value, as a text prefix term does. - -## Numeric Fields - -A numeric clause such as `@price:[0 100]` contributes 0. -It removes the keys that are outside the range and does not change the order of the other keys. - -## Vector Fields - -A vector query measures the distance between the query vector and each indexed vector. -A smaller distance is a better match. -See [Vector Distance](#vector-distance) for the distance formulas of `L2`, `IP`, and `COSINE`. - -A KNN query (`*=>[KNN ...]`) sorts its results by distance and returns the distance in the `___score` field, unless `NOCONTENT` is given or a `RETURN` clause does not list that field. -A KNN query can have a filter with no text or tag clause, such as `(@price:[0 100])=>[KNN ...]`. -Then the score of each result is its distance, and the results stay sorted by distance. -`WITHSCORES` does not return the distance. It reports 0, so read the distance from `___score`. -A KNN query can have a filter that contains a text or tag clause, such as `(shoes)=>[KNN ...]` or `(@color:{red})=>[KNN ...]`. -`WITHSCORES` then reports the score of the filter, and the results are sorted by that score. - -A vector range clause (`@:[VECTOR_RANGE ...]`) does not add to the relevance score. -See [Vector Range Match](search-query.md#vector-range-match) for how to return its distance. - -# Where Scores Appear and How They Are Used - -These options return scores to the client: - -| Command | Option | Result | -| :--- | :--- | :--- | -| [`FT.SEARCH`](../commands/ft.search.md) | `WITHSCORES` | The score follows each key name in the reply. | -| [`FT.AGGREGATE`](../commands/ft.aggregate.md) | `ADDSCORES` | Each record contains a `__score` field. Later stages can use it as `@__score`. | -| [`FT.HYBRID`](../commands/ft.hybrid.md) | `COMBINE ... YIELD_SCORE_AS` | Without a `LOAD` clause, each record contains the fused score, under `__score` or under the alias that you name. With a `LOAD` clause, the fused score appears only if you name it with `YIELD_SCORE_AS` or load `@__score`. | -| `FT.SEARCH` with a KNN query | `AS ` | Each result contains the vector distance, under `___score` or under ``, unless `NOCONTENT` is given or a `RETURN` clause does not list that name. A smaller distance is a better match. See [Vector Fields](#vector-fields). | - -`SCORER ` selects the scoring function for `FT.SEARCH`, `FT.AGGREGATE`, and the `SEARCH` arm of `FT.HYBRID`. -When `SCORER` is omitted, the [`search.default-scorer`](search-configurables.md) configuration is used (default `BM25STD`). -The only supported value now is `BM25STD`. Any other value returns an error. - -## How Scores Order Results - -For the default sort order of each query shape, see the table in [What Is a Score?](#what-is-a-score). -In a KNN query with a text or tag clause in its filter, such as `(shoes)=>[KNN 10 @vec $v]`, the KNN clause selects the nearest keys, and the score of the filter then orders them. - -The sort occurs before `LIMIT`. -Thus, when results are sorted by score, `LIMIT 0 10` returns the 10 keys with the highest scores. - -`FT.AGGREGATE` does not sort by score automatically. -To sort its records by score, use `ADDSCORES` and `SORTBY 2 @__score DESC`. - -# How Scores Can Be Modified - -The final score is the score of the whole query tree, multiplied by the document score of the key. -The document score is a number for each key that does not depend on the query: - -``` -score = document score * query score -``` - -The query score combines the scores of the clauses in the query. -See [How Scores Combine](#how-scores-combine). - -## Query Weights - -The query `jacket (@color:{red}) => {$weight: 2.0}` gives this score. -In this formula, the jacket score is the score of `jacket`, and the red score is the score of `@color:{red}`: - -``` -score = document score * (jacket score + 2 * red score) -``` - -The `$weight` attribute multiplies the score of the clause that it is attached to. -The weight must be 0 or greater. A clause with a weight of 0 still filters keys, but adds 0 to the score. -A weight on a single term multiplies the score of the term. -If the term is stemmed, the weight also multiplies the scores of the other forms of the word. See [Stemming Adds an Exact-Match Bonus](#stemming-adds-an-exact-match-bonus). -A weight on a group of terms multiplies the sum of the group. - -## Document Score - -The document score comes from the index definition: - -- `SCORE_FIELD ` sets the document score of each key to the value of that field. -- `SCORE ` sets the document score of the keys that do not have a valid `SCORE_FIELD` value. If the index has no `SCORE_FIELD`, `SCORE` applies to all keys. -- If the index definition has neither option, the document score is 1.0. - -Use the document score to promote or demote keys independently of the query, for example to rank in-stock products above other products. - -# How Scores Combine - -A query is a tree of clauses. -Valkey Search computes the score of a key from the bottom of the tree to the top: - -- An AND of clauses (`shoes @color:{red}`) adds the scores of all its clauses. -- An OR of clauses (`shoes | jacket`) adds the scores of the clauses that match the key. A clause that does not match the key contributes nothing. -- A negated clause (`-socks`) contributes 0. - -# Score Fusion in Hybrid Search - -The [`FT.HYBRID`](../commands/ft.hybrid.md) command runs two searches on one index: a text, tag, or numeric search and a vector search. -It then fuses the two result lists into one list. -The `SEARCH` arm computes scores as `FT.SEARCH` does, with the `BM25STD` scorer. -The `VSIM` arm converts each vector distance into a similarity. -For `L2` and `COSINE`, a higher similarity is a better match. -For `IP`, a higher similarity is a worse match. -`RRF` uses ranks, so the `IP` direction does not affect it. -`LINEAR` and `FUNCTION` use the similarity value directly. - -The `COMBINE` clause selects how the two arms fuse: - -- `RRF` (the default) uses the rank of a key in each arm, not its score. The two arms can use scores on different scales. -- `LINEAR` adds the scores of the two arms with weights that you set. -- `FUNCTION` computes the fused score with an expression that you write. - -See [Fusion methods](../commands/ft.hybrid.md#fusion-methods) for the formulas and the options. - -# Scores in Cluster Mode - -In cluster mode, each shard computes scores from its own keys. -It uses the number of keys, the number of keys that contain each term, and the average key length on that shard, not in the whole index. -Thus the same key can get a different score in cluster mode than on a single node. -The results from all shards are then sorted together by these scores, so the merged order can compare scores that were computed from different statistics. - -# How the Score Is Computed - -## Term Score - -The `BM25STD` scorer gives each matched text term this score: - -``` -term score = weight * IDF * (f * (k1 + 1)) / (f + k1 * (1 - b + b * dl / avgdl)) -IDF = ln(1 + (N - n + 0.5) / (n + 0.5)) -``` - -| Symbol | Value | -| :--- | :--- | -| `N` | The number of keys in the index. | -| `n` | The number of keys that contain the term. | -| `f` | The number of times that the term occurs in the key, in the `TEXT` fields that the clause queries. | -| `dl` | The number of words in the key, in all of its `TEXT` fields, after stop word removal. | -| `avgdl` | The average `dl` of the keys in the index. | -| `k1` | 1.2. This constant limits how much repeated occurrences of a term increase the score. | -| `b` | 0.75. This constant sets how much the length of a key decreases the score. | -| `weight` | The `$weight` query attribute of the clause. The default is 1.0. | - -## Stemming Parts - -A stemmed term ([Stemming Adds an Exact-Match Bonus](#stemming-adds-an-exact-match-bonus)) is the sum of up to three parts. -Each part has its own `f` and its own `IDF`: - -1. The word exactly as written in the query. -2. The stem itself, if it is a different word that occurs in the index. For `running`, this part is `run`. -3. All indexed words that have the stem, other than the stem itself. For `running`, this part is `running` and `runs` together. Its `f` is the sum of the occurrences of these words in the key. Its `n` is the number of keys that contain at least one of them. - -The word as written in the query is in part 1 and also in part 3. -Assume that `running` is the only indexed word with the stem `run`. -Then, with the default weight of 1, a query for `running` scores twice as high as the same query with `VERBATIM`. - -A `$weight` on the term multiplies all three parts. - -A word that is its own stem, such as `jacket`, is never in part 3. -For a query for `jacket`, a key that contains `jacket` gets part 1, and a key that contains `jackets` gets part 3. - -## Prefix, Suffix, and Fuzzy Term Values - -A prefix, suffix, or fuzzy term contributes the score of one matched word. -That word uses its own `f` and `IDF`. -If a key contains more than one matched word, the word that is used is not specified. - -## Phrase and Match-All Values - -Each word of a quoted phrase contributes only part 1 of [Stemming Parts](#stemming-parts). -The match-all query `*` gives each key one term score with `IDF` = 1 and `f` = 1. - -## Tag Values - -A tag clause such as `@color:{red}` is scored with the same `BM25STD` formula, with these changes: - -- `f` is always 1. -- `n` is the number of keys that have the tag value. -- `dl` is the number of words in all of the key's `TEXT` fields, and `avgdl` is the average `dl` over the index. - -If the index schema has no `TEXT` field, `avgdl` is 0, so every tag clause scores 0. - -## Vector Distance - -This table shows how Valkey Search computes the distance between two vectors `X` and `Y`: - -| Metric | Distance | Range | -| :--- | :--- | :--- | -| `L2` | `sum((x[i] - y[i])^2)`, the squared Euclidean distance | 0 or greater | -| `IP` | `1 - dot(X, Y)` | Any value. It is negative when `dot(X, Y)` is greater than 1. | -| `COSINE` | `1 - dot(X, Y) / (magnitude(X) * magnitude(Y))` | 0 to 2 | - -## Per-Shard Values - -In cluster mode, `N`, `n`, and `avgdl` are the values for the keys on that shard, not for the whole index. diff --git a/topics/search.md b/topics/search.md deleted file mode 100644 index b4f03ce5..00000000 --- a/topics/search.md +++ /dev/null @@ -1,116 +0,0 @@ ---- -title: "Valkey Search - Overview" -description: Valkey Search Module Overview ---- - -**Valkey-Search** (BSD-3-Clause), provided as a Valkey module, is a high-performance Search engine -optimized for AI-driven / Search / Analytics / Recommendation System related workloads. It delivers single-digit millisecond -latency and high QPS, capable of handling billions of vectors with over 99% recall as part of vector searches. It also provides -support for hybrid / pure non vector workloads including Numeric, Tag, and Full-text searches. - -Valkey-Search allows users to create indexes and perform searches, incorporating complex filters. -Users can index data using either **[Valkey Hash](hashes.md)** or **[Valkey-JSON](valkey-json.md)** data types. -The vector queries support Approximate Nearest Neighbor (ANN) search with HNSW and exact matching using K-Nearest Neighbors (KNN). - -## Use-Cases Where **Valkey-Search** Shines - -Valkey-Search's ability to search billions of vectors with millisecond latencies makes it ideal for real-time applications such as: - -- Personalized Recommendations – Deliver instant, highly relevant recommendations based on real-time user interactions. -- Fraud Detection & Security – Identify anomalies and suspicious activity with ultra-fast similarity matching. -- Conversational AI & Chatbots – Enhance response accuracy and relevance by leveraging rapid vector-based retrieval. -- Image & Video Search – Enable multimedia search through real-time similarity detection. -- GenAI & Semantic Search – Power advanced AI applications with efficient vector retrieval for natural language understanding. - - -## Supported Commands - -```plaintext -FT.CREATE -FT.DROPINDEX -FT.INFO -FT._LIST -FT.SEARCH -FT.AGGREGATE -FT.HYBRID -FT.CURSOR -``` - -For a detailed description of the supported commands, examples and configuration options, see the [Command Reference](../commands/#search). - -## Indexes - -A Valkey index is similar to a table in a relational database. The rows of the table are Valkey keys and the columns of the table are populated from data extracted from those keys. -Query expressions are constructed like a filter that uses the data in the columns to identify keys. The actual implementation is based on content-driven indexes, not linear filtering. Each index is given a unique name by the application and each Valkey database has a separate namespace of indexes. - -Indexes exist separate from the Valkey database. Updates of the database trigger updates of one or more indexes which are done by background threads. Query operations are also performed by background threads optionally switching to the main thread in order to access the Valkey database. The consistency model between these two domains is further described below. - -Indexes are created through the [`FT.CREATE`](../commands/ft.create.md) command which defines the rows and columns of the table-like abstraction. The command creates an empty index which can then be populated with data. Applications don't directly put data into an index, rather mutation operations on keys within the declared keyspace of an index automatically update the index with the value of that key. This update operation happens at the key level, i.e., even if only part of a key is mutated, the entire key is updated in the index. In other words, on an index of hash keys, a command like `HSET` which modifies a field of a key causes the entire key to be updated. - -## Data Ingestion - -Index updates are side effects of data mutation, based on prefix matching and, if the index was created with a `FILTER` expression, on that expression (see [`FT.CREATE`](../commands/ft.create.md)). A Valkey keyspace notification is used to capture a copy of the data associated with a key mutation. If this key belongs to multiple indexes, then the captured data goes into the mutation queue for each index independently. The client which executed the mutation command is blocked until all indexes are updated. - -Processing of the mutation queue does not respect the order of mutations. If multiple clients are updating different keys the updates may happen in any order not necessarily related to the order in which the mutation commands were executed. If a previous update for the same key is already in the mutation queue then these can be combined. An exception to the reordering rules applies to keys which are updated as part of a multi/exec block or a Lua script. These keys are always ingested as a group which cannot be split or reordered. - -## Index Creation and Backfill - -The automatic ingestion only applies to keys which are modified _after_ the creation of an index. But what about keys that exist _before_ the creation of an index? These keys cannot be instantly inserted into the index. By default, the creation of an index initiates an internal background process which scans the keyspace to locate and insert preexisting keys into the index. This process, known as backfilling, can be monitored via the `FT.INFO` command. The backfill process runs once after the creation of the index. Once it has completed it will not be initiated again. The backfill process does not directly change the behavior of an index. Applications may continue to modify indexed keys and they will be updated in the same way as if no backfill was executing. Query operations can freely be executed, but will only contain the results from keys which are currently in the index, i.e., all keys modified after creation of the index and _some_ of the keys that existed before creation of the index. - -The backfill process can be quite lengthy on a large system, even if no keys are found. Applications that know there are no preexisting keys or that no preexisting keys need to be inserted into the index, can skip the backfill process by specifying `SKIPINITIALSCAN` on the `FT.CREATE` command. - -The snapshot process (save or full sync) only partially preserves the state of the backfilling process. The process is able to save the fact that a backfill is in progress, but does not save the backfill cursor (because a `SCAN` cursor isn't valid across reloads). -Thus on reload a backfilling index must restart the backfill at the beginning. However, because the indexes for vector fields are saved and restored, the indexed content of vector fields (the really slow part) is preserved. - -## Query Operations - -Query commands operate by blocking the client and sending the query to the background threads to locate a set of keys. Then the client is unblocked and control resumes on the main thread which can access the database to generate the final result. If a key is modified by another client while a query is in progress then that key may or may not be included in the query result. In no case will a key be returned which does not satisfy the query expression. - -By default, queries rank the matching keys by a relevance score. KNN queries without a text or tag filter rank keys by vector distance instead, and a `SORTBY` clause overrides both orders. See [Search - Scoring](search-scoring.md) for how scores are computed. - -## Save/Restore - -A generated RDB file (either due to an explicit save or full-sync operation) contains index definitions (index metadata), any vector field indexes, and a list of the keys currently in the index. On a load operation, each index is recreated from the definitions, any vector field indexes are reloaded, and any non-vector fields are rebuilt from the loaded Valkey database using the list of keys. If the index had a backfill in progress at the time of the save, then on completion of a load a backfill will be initiated for it. - -## Index Replication - -Indexes are node-local. Each node, regardless of whether it's a primary or a replica maintains its own index independently. Indexes on replicas are updated by key mutations transmitted on the replication channel and thus are subject to replication lag just like the Valkey database itself. -No additional replication channel traffic is generated for updates. The index backfill process is also node-local, meaning just because one node (a primary) in a replication group has completed its backfill the other nodes may not have. - -## Cluster Mode - -Search fully supports cluster mode and uses gRPC and protobuf for intra-cluster communication, requiring system configuration to make this additional port available. The gRPC port address is set based on the main Valkey port address. The gRPC port number is usually the Valkey port number plus 20294 (for the default port: 6379 + 20294 = 26673), unless the Valkey port is 6378 in which case the offset is 20295 (6378 + 20295 = 26673 also). - -In cluster mode, Valkey distributes keys according to the hash algorithm of the keyname. This placement of data is not affected by the presence of the search module or any search indexes. Since search commands operate at the index level -- not the key level -- search is responsible for dealing with the distribution of data, performing intra-cluster RPC to execute commands as needed. Thus the application interface to search operates the same in cluster and non-cluster mode. - -Search uses a simple architecture where index definitions are replicated on every node but the corresponding index only contains the data which is co-resident on that node. Index update operations remain wholly local to a node and will scale horizontally (save/restore operations also wholly node local). Vertical scaling is also effective because of the multi threaded architecture of search. - -Query operations are performed by one node of each shard on its local index and the results are transparently merged together to form a full command response. Query operations are subject to increasing overhead as the cluster shard count increases, so they may scale sub-linearly with increasing shard count. - -Search recognizes that certain data patterns can be optimized. In particular, it recognizes that if the data for an index is confined to a single slot, then only a single node needs to perform a search operation. Operations on single-slot indexes do not experience increased overhead as cluster size increases and thus will scale horizontally, vertically, and through replicas. - -Client-side routing of query operations can have a profound effect on performance. For indexes with data on all shards, performance is improved if the query operations are distributed across the cluster. Any well-known load balancing algorithm should be fine, i.e., round-robin, random, etc. For indexes that are confined to a single slot, routing a query to a node that contains that slot is optimal. To simplify the logic of a client, the system restricts the assignment of index names as follows. - -Index names without a hash tag are considered to be cluster-wide indexes (even if the prefix list is confined to a single slot). Index names with a hash tag are considered to be single-slot indexes. The prefix list of a single-slot index must consist solely of prefixes which contain the same hash tag or an error will be generated by the `FT.CREATE` command. - -## Index Consistency - -The Search architecture relies on having identical index definitions distributed across the cluster. This is implemented with an eventually consistent cross-shard protocol. The protocol relies on a Merkle-tree checksum of all indexes defined on a node being broadcast over the cluster bus periodically. Nodes which discover a mismatch in the checksum contact each other and negotiate a resolution using version numbers and last-writer-wins timestamps, one index at a time. If a node loses the negotiation for an index, it will delete its version of the index and recreate it using the winning definition. - -On top of the eventual consistency machinery the individual commands also perform additional consistency checks on the involved index, typically retrying operations until consistency is achieved or a timeout occurs, terminating the command with a consistency error message. - -The metadata mutation commands (`FT.CREATE` and `FT.DROPINDEX`) use the consistency machinery described above. The commands operate by mutating the local copy of the metadata and then triggering the convergence protocol. If convergence cannot be achieved within a bounded period of time the command is terminated with an error. No attempt is made to undo any failed metadata mutation. The most likely cause of failure is a shard-down or network partition situation. - -The `FT.INFO` command has options that allow aggregation of index statistics and status across the cluster. - -## Query Consistency - -The query operations: `FT.SEARCH`, `FT.AGGREGATE` and `FT.HYBRID` can only be executed by nodes that share the same index definition and slot ownership map. Cross-shard query commands contain a checksum of the coordinator's index definition and slot ownership. If a receiving node's index checksum or slot ownership checksum mismatches then the query is rejected and the coordinator will retry the operation. If a shard fails or times out then by default (`search.enable-partial-results` is `yes`) a result is generated from the subset of the cross-shard query operations that succeeded; an error is returned only if none succeeded. For `FT.HYBRID` this applies to each arm separately: if no shard succeeds for one arm, the query returns an error. Once the command's own timeout expires, however, an `FT.AGGREGATE` query with an `APPLY`, `FILTER`, `GROUPBY`, `LIMIT` or `SORTBY` stage returns an error rather than processing the partial result, and so does every `FT.HYBRID` query. Likewise, by default (`search.enable-consistent-results` is `no`) results from nodes with different views of the cluster are allowed; when the setting is `yes` such a query returns an error. `FT.SEARCH` can override the settings per query with `SOMESHARDS` or `ALLSHARDS` (any shard failure returns an error) and `INCONSISTENT` or `CONSISTENT`. `FT.AGGREGATE` and `FT.HYBRID` do not accept these options and always follow the two configuration settings. - -## Configuration Settings - -The Search module has a large list of configurable items. See [Search Configurations](../topics/search-configurables.md) for details. - -## INFO Fields - -See [Search Info Fields](../topics/search-observables.md) for details. diff --git a/topics/security.md b/topics/security.md deleted file mode 100644 index 99497d27..00000000 --- a/topics/security.md +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: "Security" -description: Security model and features in Valkey ---- - -This document provides an introduction to the topic of security from the point of -view of Valkey. -It covers the access control provided by Valkey, code security concerns, -attacks that can be triggered from the outside by selecting malicious inputs, and -other similar topics. - -To report a security vulnerability, email security@lists.valkey.io. -Do **not** open a public GitHub issue. -See the [security policy](https://github.com/valkey-io/valkey/blob/unstable/SECURITY.md). - -## Security model - -Valkey is designed to be accessed by trusted clients inside trusted environments. -This means that usually it is not a good idea to expose the Valkey instance -directly to the internet or, in general, to an environment where untrusted -clients can directly access the Valkey TCP port or UNIX socket. - -For instance, in the common context of a web application implemented using Valkey -as a database, cache, or messaging system, the clients inside the front-end -(web side) of the application will query Valkey to generate pages or -to perform operations requested or triggered by the web application user. - -In this case, the web application mediates access between Valkey and -untrusted clients (the user browsers accessing the web application). - -In general, untrusted access to Valkey should -always be mediated by a layer implementing ACLs, validating user input, -and deciding what operations to perform against the Valkey instance. - -## Network security - -Access to the Valkey port should be denied to everybody but trusted clients -in the network, so the servers running Valkey should be directly accessible -only by the computers implementing the application using Valkey. - -In the common case of a single computer directly exposed to the internet, such -as a virtualized Linux instance (Linode, EC2, ...), the Valkey port should be -firewalled to prevent access from the outside. -Clients will still be able to access Valkey using the loopback interface. - -Note that it is possible to bind Valkey to a single interface by adding a line -like the following to the `valkey.conf` file: - -```txt -bind 127.0.0.1 -``` - -Failing to protect the Valkey port from the outside can have a big security -impact because of the nature of Valkey. -For instance, a single [`FLUSHALL`](../commands/flushall.md) command can be used by an external attacker to delete the whole data set. - -## Protected mode - -Many users fail to protect Valkey instances from being accessed -from external networks and many instances are simply left exposed on the internet with public IPs. -Valkey enters a special mode called **protected mode** when it is -executed with the default configuration (binding all the interfaces) and -without any password in order to access it. -In this mode, Valkey only replies to queries from the -loopback interfaces, and replies to clients connecting from other -addresses with an error that explains the problem and how to configure -Valkey properly. - -It is expected that protected mode decreases the security issues caused -by unprotected Valkey instances executed without proper administration. -However, the system administrator can still ignore the error given by Valkey and -disable protected mode or manually bind all the interfaces. - -## Authentication - -Valkey provides two ways to authenticate clients. -The recommended authentication method is via Access Control Lists, allowing named users to be created and assigned fine-grained permissions. -Read more about [Access Control Lists](acl.md). - -The legacy authentication method is enabled by editing the `valkey.conf` file, and providing a database password using the `requirepass` setting. -This password is then used by all clients. - -When the `requirepass` setting is enabled, Valkey will refuse any query by -unauthenticated clients. -A client can authenticate itself by sending the -[`AUTH`](../commands/auth.md) command followed by the password. - -The password is set by the system administrator in clear text inside the -`valkey.conf` file. -It should be long enough to prevent brute force attacks for two reasons: - -* Valkey is very fast at serving queries. -Many passwords per second can be tested by an external client. -* The Valkey password is stored in the `valkey.conf` file and inside the client configuration. -Since the system administrator does not need to remember it, the password can be very long. - -The goal of the authentication layer is to optionally provide a layer of -redundancy. -If firewalling or any other system implemented to protect Valkey -from external attackers fails, an external client will still not be able to -access the Valkey instance without knowledge of the authentication password. - -Since the [`AUTH`](../commands/auth.md) command, like every other Valkey command, -is sent unencrypted unless TLS is enabled, it does not protect against an attacker -that has enough access to the network to perform eavesdropping. - -## TLS support - -Valkey has optional support for TLS on all communication channels, including -client connections, replication links, and the Valkey Cluster bus protocol. -Read more about [TLS support](tls.md). - -## Attacks triggered by malicious inputs from external clients - -There is a class of attacks that an attacker can trigger without direct access to the instance. -For example, an attacker might insert data into Valkey that triggers pathological (worst-case) -algorithm complexity on data structures implemented inside Valkey internals. - -An attacker could supply, via a web form, a set of strings that -are known to hash to the same bucket in a hash table in order to turn the -O(1) expected time (the average time) to the O(N) worst case. -This can consume more CPU than expected and ultimately cause a Denial of Service. - -To prevent this specific attack, Valkey uses a per-execution, pseudo-random -seed to the hash function. - -Valkey implements the [`SORT`](../commands/sort.md) command using the `qsort` algorithm. -Currently, the algorithm is not randomized, so it is possible to trigger a quadratic -worst-case behavior by carefully selecting the right set of inputs. - -## String escaping and NoSQL injection - -The Valkey protocol has no concept of string escaping, so injection -is impossible under normal circumstances using a normal client library. -The protocol uses prefixed-length strings and is completely binary safe. - -Since Lua scripts executed by the [`EVAL`](../commands/eval.md) and [`EVALSHA`](../commands/evalsha.md) commands follow the -same rules, those commands are also safe. - -While it would be a strange use case, the application should avoid composing the body of the Lua script from strings obtained from untrusted sources. - -## Code security - -Internally, Valkey uses well-known practices for writing secure code to -prevent buffer overflows, format bugs, and other memory corruption issues. - -Valkey does not require root privileges to run. -It is recommended to run it as an unprivileged `valkey` user that is only used for this purpose. diff --git a/topics/sentinel-clients.md b/topics/sentinel-clients.md deleted file mode 100644 index e8eae99c..00000000 --- a/topics/sentinel-clients.md +++ /dev/null @@ -1,152 +0,0 @@ ---- -title: "Sentinel client spec" -description: How to build clients for Valkey Sentinel ---- - -Valkey Sentinel is a monitoring solution for Valkey instances that handles -automatic failover of Valkey primaries and service discovery (who is the current -primary for a given group of instances?). Since Sentinel is both responsible -for reconfiguring instances during failovers, and providing configurations to -clients connecting to Valkey primaries or replicas, clients are required to have -explicit support for Valkey Sentinel. - -This document is targeted at Valkey clients developers that want to support Sentinel in their clients implementation with the following goals: - -* Automatic configuration of clients via Sentinel. -* Improved safety of Valkey Sentinel automatic failover. - -For details about how Valkey Sentinel works, please check the [Valkey Documentation](sentinel.md), as this document only contains information needed for Valkey client developers, and it is expected that readers are familiar with the way Valkey Sentinel works. - -## Valkey service discovery via Sentinel - -Valkey Sentinel identifies every primary with a name like "stats" or "cache". -Every name actually identifies a *group of instances*, composed of a primary -and a variable number of replicas. - -The address of the Valkey primary that is used for a specific purpose inside a network may change after events like an automatic failover, a manually triggered failover (for instance in order to upgrade a Valkey instance), and other reasons. - -Normally Valkey clients have some kind of hard-coded configuration that specifies the address of a Valkey primary instance within a network as IP address and port number. However if the primary address changes, manual intervention in every client is needed. - -A Valkey client supporting Sentinel can automatically discover the address of a Valkey primary from the primary name using Valkey Sentinel. So instead of a hard coded IP address and port, a client supporting Sentinel should optionally be able to take as input: - -* A list of ip:port pairs pointing to known Sentinel instances. -* The name of the service, like "cache" or "timelines". - -This is the procedure a client should follow in order to obtain the primary address starting from the list of Sentinels and the service name. - -Step 1: connect to the first Sentinel ---- - -The client should iterate the list of Sentinel addresses. For every address it should try to connect to the Sentinel, using a short timeout (in the order of a few hundreds of milliseconds). On errors or timeouts the next Sentinel address should be tried. - -If all the Sentinel addresses were tried without success, an error should be returned to the client. - -The first Sentinel replying to the client request should be put at the start of the list, so that at the next reconnection, we'll try first the Sentinel that was reachable in the previous connection attempt, minimizing latency. - -Step 2: ask for primary address ---- - -Once a connection with a Sentinel is established, the client should retry to execute the following command on the Sentinel: - - SENTINEL get-master-addr-by-name master-name - -Where *master-name* should be replaced with the actual service name specified by the user. - -The result from this call can be one of the following two replies: - -* An ip:port pair. -* A null reply. This means Sentinel does not know this primary. - -If an ip:port pair is received, this address should be used to connect to the Valkey primary. Otherwise if a null reply is received, the client should try the next Sentinel in the list. - -Step 3: call the ROLE command in the target instance ---- - -Once the client discovered the address of the primary instance, it should -attempt a connection with the primary, and call the `ROLE` command in order -to verify the role of the instance is actually a primary. - -If the instance is not a primary as expected, the client should wait a short amount of time (a few hundreds of milliseconds) and should try again starting from Step 1. - -Handling reconnections -=== - -Once the service name is resolved into the primary address and a connection is established with the Valkey primary instance, every time a reconnection is needed, the client should resolve again the address using Sentinels restarting from Step 1. For instance Sentinel should contacted again the following cases: - -* If the client reconnects after a timeout or socket error. -* If the client reconnects because it was explicitly closed or reconnected by the user. - -In the above cases and any other case where the client lost the connection with the Valkey server, the client should resolve the primary address again. - -Sentinel failover disconnection -=== - -When Valkey Sentinel changes the configuration of -an instance, for example promoting a replica to a primary, demoting a primary to -replicate to the new primary after a failover, or simply changing the primary -address of a stale replica instance, it sends a `CLIENT KILL type normal` -command to the instance in order to make sure all the clients are disconnected -from the reconfigured instance. This will force clients to resolve the primary -address again. - -If the client will contact a Sentinel with yet not updated information, the verification of the Valkey instance role via the `ROLE` command will fail, allowing the client to detect that the contacted Sentinel provided stale information, and will try again. - -Note: it is possible that a stale primary returns online at the same time a client contacts a stale Sentinel instance, so the client may connect with a stale primary, and yet the ROLE output will match. However when the primary is back again Sentinel will try to demote it to replica, triggering a new disconnection. The same reasoning applies to connecting to stale replicas that will get reconfigured to replicate with a different primary. - -Connecting to replicas -=== - -Sometimes clients are interested to connect to replicas, for example in order to scale read requests. This protocol supports connecting to replicas by modifying step 2 slightly. Instead of calling the following command: - - SENTINEL get-master-addr-by-name master-name - -The clients should call instead: - - SENTINEL replicas primary-name - -In order to retrieve a list of replica instances. - -Symmetrically the client should verify with the `ROLE` command that the -instance is actually a replica, in order to avoid scaling read queries with -the primary. - -Connection pools -=== - -For clients implementing connection pools, on reconnection of a single connection, the Sentinel should be contacted again, and in case of a primary address change all the existing connections should be closed and connected to the new address. - -Error reporting -=== - -The client should correctly return the information to the user in case of errors. Specifically: - -* If no Sentinel can be contacted (so that the client was never able to get the reply to `SENTINEL get-master-addr-by-name`), an error that clearly states that Valkey Sentinel is unreachable should be returned. -* If all the Sentinels in the pool replied with a null reply, the user should be informed with an error that Sentinels don't know this primary name. - -Sentinels list automatic refresh -=== - -Optionally once a successful reply to `get-master-addr-by-name` is received, a client may update its internal list of Sentinel nodes following this procedure: - -* Obtain a list of other Sentinels for this primary using the command `SENTINEL sentinels `. -* Add every ip:port pair not already existing in our list at the end of the list. - -It is not needed for a client to be able to make the list persistent updating its own configuration. The ability to upgrade the in-memory representation of the list of Sentinels can be already useful to improve reliability. - -Subscribe to Sentinel events to improve responsiveness -=== - -The [Sentinel documentation](sentinel.md) shows how clients can connect to -Sentinel instances using Pub/Sub in order to subscribe to changes in the -Valkey instances configurations. - -This mechanism can be used in order to speedup the reconfiguration of clients, -that is, clients may listen to Pub/Sub in order to know when a configuration -change happened in order to run the three steps protocol explained in this -document in order to resolve the new Valkey primary (or replica) address. - -However update messages received via Pub/Sub should not substitute the -above procedure, since there is no guarantee that a client is able to -receive all the update messages. - -> NOTE: If not for backward compatibility, the Valkey project no longer uses the words "master" and "slave". Unfortunately in the given commands these words are part of the protocol, so we’ll be able to remove such occurrences only when this API will be naturally deprecated. diff --git a/topics/sentinel.md b/topics/sentinel.md deleted file mode 100644 index ac81b0fb..00000000 --- a/topics/sentinel.md +++ /dev/null @@ -1,1245 +0,0 @@ ---- -title: "High availability with Valkey Sentinel" -description: High availability for non-clustered Valkey ---- - -## Usage - -**`valkey-sentinel`** _/path/to/sentinel.conf_ - -**`valkey-server`** _/path/to/sentinel.conf_ **`--sentinel`** - -## Description - -Valkey Sentinel provides high availability for Valkey when not using [Valkey Cluster](cluster-tutorial.md). - -Valkey Sentinel also provides other collateral tasks such as monitoring, -notifications and acts as a configuration provider for clients. - -This is the full list of Sentinel capabilities at a macroscopic level (i.e. the *big picture*): - -* **Monitoring**. Sentinel constantly checks if your primary and replica instances are working as expected. -* **Notification**. Sentinel can notify the system administrator, or other computer programs, via the API, that something is wrong with one of the monitored Valkey instances. -* **Automatic failover**. If a primary is not working as expected, Sentinel can start a failover process where a replica is promoted to primary, the other additional replicas are reconfigured to use the new primary, and the applications using the Valkey server are informed about the new address to use when connecting. -* **Configuration provider**. Sentinel acts as a source of authority for clients service discovery: clients connect to Sentinels in order to ask for the address of the current Valkey primary responsible for a given service. If a failover occurs, Sentinels will report the new address. - -## Sentinel as a distributed system - -Valkey Sentinel is a distributed system: - -Sentinel itself is designed to run in a configuration where there are multiple Sentinel processes cooperating together. The advantage of having multiple Sentinel processes cooperating are the following: - -1. Failure detection is performed when multiple Sentinels agree about the fact a given primary is no longer available. This lowers the probability of false positives. -2. Sentinel works even if not all the Sentinel processes are working, making the system robust against failures. There is no fun in having a failover system which is itself a single point of failure, after all. - -The sum of Sentinels, Valkey instances (primaries and replicas) and clients -connecting to Sentinel and Valkey, are also a larger distributed system with -specific properties. In this document concepts will be introduced gradually -starting from basic information needed in order to understand the basic -properties of Sentinel, to more complex information (that are optional) in -order to understand how exactly Sentinel works. - -## Sentinel quick start - -Valkey Sentinel is included in Valkey. - -### Running Sentinel - -If you are using the `valkey-sentinel` executable (or if you have a symbolic -link with that name to the `valkey-server` executable) you can run Sentinel -with the following command line: - - valkey-sentinel /path/to/sentinel.conf - -Otherwise you can use directly the `valkey-server` executable starting it in -Sentinel mode: - - valkey-server /path/to/sentinel.conf --sentinel - -Both ways work the same. - -However **it is mandatory** to use a configuration file when running Sentinel, as this file will be used by the system in order to save the current state that will be reloaded in case of restarts. Sentinel will simply refuse to start if no configuration file is given or if the configuration file path is not writable. - -Sentinels by default run **listening for connections to TCP port 26379**, so -for Sentinels to work, port 26379 of your servers **must be open** to receive -connections from the IP addresses of the other Sentinel instances. -Otherwise Sentinels can't talk and can't agree about what to do, so failover -will never be performed. - -### Fundamental things to know about Sentinel before deploying - -1. You need at least three Sentinel instances for a robust deployment. -2. The three Sentinel instances should be placed into computers or virtual machines that are believed to fail in an independent way. So for example different physical servers or Virtual Machines executed on different availability zones. -3. Sentinel + Valkey distributed system does not guarantee that acknowledged writes are retained during failures, since Valkey uses asynchronous replication. However there are ways to deploy Sentinel that make the window to lose writes limited to certain moments, while there are other less secure ways to deploy it. -4. You need Sentinel support in your clients. Popular client libraries have Sentinel support, but not all. -5. There is no HA setup which is safe if you don't test from time to time in development environments, or even better, if you can in production environments, if they work. You may have a misconfiguration that will become apparent only when it's too late (at 3am when your primary stops working). -6. **Sentinel, Docker, or other forms of Network Address Translation or Port Mapping should be mixed with care**: Docker performs port remapping, breaking Sentinel auto discovery of other Sentinel processes and the list of replicas for a primary. Check the [section about _Sentinel and Docker_](#sentinel-docker-nat-and-possible-issues) later in this document for more information. - -### Configuring Sentinel - -The Valkey source distribution contains a file called `sentinel.conf` -that is a self-documented example configuration file you can use to -configure Sentinel, however a typical minimal configuration file looks like the -following: - - sentinel monitor mymaster 127.0.0.1 6379 2 - sentinel down-after-milliseconds mymaster 60000 - sentinel failover-timeout mymaster 180000 - sentinel parallel-syncs mymaster 1 - - sentinel monitor resque 192.168.1.3 6380 4 - sentinel down-after-milliseconds resque 10000 - sentinel failover-timeout resque 180000 - sentinel parallel-syncs resque 5 - -You only need to specify the primaries to monitor, giving to each separated -primary (that may have any number of replicas) a different name. There is no -need to specify replicas, which are auto-discovered. Sentinel will update the -configuration automatically with additional information about replicas (in -order to retain the information in case of restart). The configuration is -also rewritten every time a replica is promoted to primary during a failover -and every time a new Sentinel is discovered. - -The example configuration above basically monitors two sets of Valkey -instances, each composed of a primary and an undefined number of replicas. -One set of instances is called `mymaster`, and the other `resque`. - -The meaning of the arguments of `sentinel monitor` statements is the following: - - sentinel monitor - -For the sake of clarity, let's check line by line what the configuration -options mean: - -The first line is used to tell Valkey to monitor a primary called *mymaster*, -that is at address 127.0.0.1 and port 6379, with a quorum of 2. Everything -is pretty obvious but the **quorum** argument: - -* The **quorum** is the number of Sentinels that need to agree about the fact the primary is not reachable, in order to really mark the primary as failing, and eventually start a failover procedure if possible. -* However **the quorum is only used to detect the failure**. In order to actually perform a failover, one of the Sentinels need to be elected leader for the failover and be authorized to proceed. This only happens with the vote of the **majority of the Sentinel processes**. - -So for example if you have 5 Sentinel processes, and the quorum for a given -primary is set to the value of 2, this is what happens: - -* If two Sentinels agree at the same time about the primary being unreachable, one of the two will try to start a failover. -* If there are at least a total of three Sentinels reachable, the failover will be authorized and will actually start. - -In practical terms this means during failures **Sentinel never starts a failover if the majority of Sentinel processes are unable to talk** (aka no failover in the minority partition). - -### Other Sentinel options - -The other options are almost always in the form: - - sentinel - -And are used for the following purposes: - -* `down-after-milliseconds` is the time in milliseconds an instance should not -be reachable (either does not reply to our PINGs or it is replying with an -error) for a Sentinel starting to think it is down. -* `parallel-syncs` sets the number of replicas that can be reconfigured to use -the new primary after a failover at the same time. The lower the number, the -more time it will take for the failover process to complete, however if the -replicas are configured to serve old data, you may not want all the replicas to -re-synchronize with the primary at the same time. While the replication -process is mostly non blocking for a replica, there is a moment when it stops to -load the bulk data from the primary. You may want to make sure only one replica -at a time is not reachable by setting this option to the value of 1. - -Additional options are described in the rest of this document and -documented in the example `sentinel.conf` file shipped with the Valkey -distribution. - -Configuration parameters can be modified at runtime: - -* Master-specific configuration parameters are modified using `SENTINEL SET`. -* Global configuration parameters are modified using `SENTINEL CONFIG SET`. - -See the [_Reconfiguring Sentinel at runtime_ section](#reconfiguring-sentinel-at-runtime) for more information. - -### Example Sentinel deployments - -Now that you know the basic information about Sentinel, you may wonder where -you should place your Sentinel processes, how many Sentinel processes you need -and so forth. This section shows a few example deployments. - -We use ASCII art in order to show you configuration examples in a *graphical* -format, this is what the different symbols means: - - +--------------------+ - | This is a computer | - | or VM that fails | - | independently. We | - | call it a "box" | - +--------------------+ - -We write inside the boxes what they are running: - - +--------------------+ - | Valkey primary M1 | - | Valkey Sentinel S1 | - +--------------------+ - -Different boxes are connected by lines, to show that they are able to talk: - - +-------------+ +-------------+ - | Sentinel S1 |---------------| Sentinel S2 | - +-------------+ +-------------+ - -Network partitions are shown as interrupted lines using slashes: - - +-------------+ +-------------+ - | Sentinel S1 |------ // ------| Sentinel S2 | - +-------------+ +-------------+ - -Also note that: - -* Primaries are called M1, M2, M3, ..., Mn. -* Replicas are called R1, R2, R3, ..., Rn (R stands for *replica*). -* Sentinels are called S1, S2, S3, ..., Sn. -* Clients are called C1, C2, C3, ..., Cn. -* When an instance changes role because of Sentinel actions, we put it inside square brackets, so [M1] means an instance that is now a primary because of Sentinel intervention. - -Note that we will never show **setups where just two Sentinels are used**, since -Sentinels always need **to talk with the majority** in order to start a -failover. - -#### Example 1: just two Sentinels, DON'T DO THIS - - +----+ +----+ - | M1 |---------| R1 | - | S1 | | S2 | - +----+ +----+ - - Configuration: quorum = 1 - -* In this setup, if the primary M1 fails, R1 will be promoted since the two Sentinels can reach agreement about the failure (obviously with quorum set to 1) and can also authorize a failover because the majority is two. So apparently it could superficially work, however check the next points to see why this setup is broken. -* If the box where M1 is running stops working, also S1 stops working. The Sentinel running in the other box S2 will not be able to authorize a failover, so the system will become not available. - -Note that a majority is needed in order to order different failovers, and later propagate the latest configuration to all the Sentinels. Also note that the ability to failover in a single side of the above setup, without any agreement, would be very dangerous: - - +----+ +------+ - | M1 |----//-----| [M1] | - | S1 | | S2 | - +----+ +------+ - -In the above configuration we created two primaries (assuming S2 could failover -without authorization) in a perfectly symmetrical way. Clients may write -indefinitely to both sides, and there is no way to understand when the -partition heals what configuration is the right one, in order to prevent -a *permanent split brain condition*. - -So please **deploy at least three Sentinels in three different boxes** always. - -#### Example 2: basic setup with three boxes - -This is a very simple setup, that has the advantage to be simple to tune -for additional safety. It is based on three boxes, each box running both -a Valkey process and a Sentinel process. - - - +----+ - | M1 | - | S1 | - +----+ - | - +----+ | +----+ - | R2 |----+----| R3 | - | S2 | | S3 | - +----+ +----+ - - Configuration: quorum = 2 - -If the primary M1 fails, S2 and S3 will agree about the failure and will -be able to authorize a failover, making clients able to continue. - -In every Sentinel setup, as Valkey uses asynchronous replication, there is -always the risk of losing some writes because a given acknowledged write -may not be able to reach the replica which is promoted to primary. However in -the above setup there is a higher risk due to clients being partitioned away -with an old primary, like in the following picture: - - +----+ - | M1 | - | S1 | <- C1 (writes will be lost) - +----+ - | - / - / - +------+ | +----+ - | [M2] |----+----| R3 | - | S2 | | S3 | - +------+ +----+ - -In this case a network partition isolated the old primary M1, so the -replica R2 is promoted to primary. However clients, like C1, that are -in the same partition as the old primary, may continue to write data -to the old primary. This data will be lost forever since when the partition -will heal, the primary will be reconfigured as a replica of the new primary, -discarding its data set. - -This problem can be mitigated using the following Valkey replication -feature, that allows to stop accepting writes if a primary detects that -it is no longer able to transfer its writes to the specified number of replicas. - - min-replicas-to-write 1 - min-replicas-max-lag 10 - -With the above configuration (please see the self-commented `valkey.conf` example in the Valkey distribution for more information) a Valkey instance, when acting as a primary, will stop accepting writes if it can't write to at least 1 replica. Since replication is asynchronous *not being able to write* actually means that the replica is either disconnected, or is not sending us asynchronous acknowledges for more than the specified `max-lag` number of seconds. - -Using this configuration, the old Valkey primary M1 in the above example, will become unavailable after 10 seconds. When the partition heals, the Sentinel configuration will converge to the new one, the client C1 will be able to fetch a valid configuration and will continue with the new primary. - -However there is no free lunch. With this refinement, if the two replicas are -down, the primary will stop accepting writes. It's a trade off. - -#### Example 3: Sentinel in the client boxes - -Sometimes we have only two Valkey boxes available, one for the primary and -one for the replica. The configuration in the example 2 is not viable in -that case, so we can resort to the following, where Sentinels are placed -where clients are: - - +----+ +----+ - | M1 |----+----| R1 | - | | | | | - +----+ | +----+ - | - +------------+------------+ - | | | - | | | - +----+ +----+ +----+ - | C1 | | C2 | | C3 | - | S1 | | S2 | | S3 | - +----+ +----+ +----+ - - Configuration: quorum = 2 - -In this setup, the point of view Sentinels is the same as the clients: if -a primary is reachable by the majority of the clients, it is fine. -C1, C2, C3 here are generic clients, it does not mean that C1 identifies -a single client connected to Valkey. It is more likely something like -an application server, a Rails app, or something like that. - -If the box where M1 and S1 are running fails, the failover will happen -without issues, however it is easy to see that different network partitions -will result in different behaviors. For example Sentinel will not be able -to setup if the network between the clients and the Valkey servers is -disconnected, since the Valkey primary and replica will both be unavailable. - -Note that if C3 gets partitioned with M1 (hardly possible with -the network described above, but more likely possible with different -layouts, or because of failures at the software layer), we have a similar -issue as described in Example 2, with the difference that here we have -no way to break the symmetry, since there is just a replica and a primary, so -the primary can't stop accepting queries when it is disconnected from its replica, -otherwise the primary would never be available during replica failures. - -So this is a valid setup but the setup in the Example 2 has advantages -such as the HA system of Valkey running in the same boxes as Valkey itself -which may be simpler to manage, and the ability to put a bound on the amount -of time a primary in the minority partition can receive writes. - -#### Example 4: Sentinel client side with less than three clients - -The setup described in the Example 3 cannot be used if there are less than -three boxes in the client side (for example three web servers). In this -case we need to resort to a mixed setup like the following: - - +----+ +----+ - | M1 |----+----| R1 | - | S1 | | | S2 | - +----+ | +----+ - | - +------+-----+ - | | - | | - +----+ +----+ - | C1 | | C2 | - | S3 | | S4 | - +----+ +----+ - - Configuration: quorum = 3 - -This is similar to the setup in Example 3, but here we run four Sentinels -in the four boxes we have available. If the primary M1 becomes unavailable -the other three Sentinels will perform the failover. - -In theory this setup works removing the box where C2 and S4 are running, and -setting the quorum to 2. However it is unlikely that we want HA in the -Valkey side without having high availability in our application layer. - -### Sentinel, Docker, NAT, and possible issues - -Docker uses a technique called port mapping: programs running inside Docker -containers may be exposed with a different port compared to the one the -program believes to be using. This is useful in order to run multiple -containers using the same ports, at the same time, in the same server. - -Docker is not the only software system where this happens, there are other -Network Address Translation setups where ports may be remapped, and sometimes -not ports but also IP addresses. - -Remapping ports and addresses creates issues with Sentinel in two ways: - -1. Sentinel auto-discovery of other Sentinels no longer works, since it is based on *hello* messages where each Sentinel announce at which port and IP address they are listening for connection. However Sentinels have no way to understand that an address or port is remapped, so it is announcing an information that is not correct for other Sentinels to connect. -2. Replicas are listed in the `INFO` output of a Valkey primary in a similar way: the address is detected by the primary checking the remote peer of the TCP connection, while the port is advertised by the replica itself during the handshake, however the port may be wrong for the same reason as exposed in point 1. - -Since Sentinels auto detect replicas using primaries `INFO` output information, -the detected replicas will not be reachable, and Sentinel will never be able to -failover the primary, since there are no good replicas from the point of view of -the system, so there is currently no way to monitor with Sentinel a set of -primary and replica instances deployed with Docker, **unless you instruct Docker -to map the port 1:1**. - -For the first problem, in case you want to run a set of Sentinel -instances using Docker with forwarded ports (or any other NAT setup where ports -are remapped), you can use the following two Sentinel configuration directives -in order to force Sentinel to announce a specific set of IP and port: - - sentinel announce-ip - sentinel announce-port - -Note that Docker has the ability to run in *host networking mode* (check the `--net=host` option for more information). This should create no issues since ports are not remapped in this setup. - -### IP Addresses and DNS names - -Older versions of Sentinel did not support host names and required IP addresses to be specified everywhere. -Starting with version 6.2, Sentinel has *optional* support for host names. - -**This capability is disabled by default. If you're going to enable DNS/hostnames support, please note:** - -1. The name resolution configuration on your Valkey and Sentinel nodes must be reliable and be able to resolve addresses quickly. Unexpected delays in address resolution may have a negative impact on Sentinel. -2. You should use hostnames everywhere and avoid mixing hostnames and IP addresses. To do that, use `replica-announce-ip ` and `sentinel announce-ip ` for all Valkey and Sentinel instances, respectively. - -Enabling the `resolve-hostnames` global configuration allows Sentinel to accept host names: - -* As part of a `sentinel monitor` command -* As a replica address, if the replica uses a host name value for `replica-announce-ip` - -Sentinel will accept host names as valid inputs and resolve them, but will still refer to IP addresses when announcing an instance, updating configuration files, etc. - -Enabling the `announce-hostnames` global configuration makes Sentinel use host names instead. This affects replies to clients, values written in configuration files, the `REPLICAOF` command issued to replicas, etc. - -This behavior may not be compatible with all Sentinel clients, that may explicitly expect an IP address. - -Using host names may be useful when clients use TLS to connect to instances and require a name rather than an IP address in order to perform certificate ASN matching. - -## A quick tutorial - -In the next sections of this document, all the details about [_Sentinel API_](#sentinel-api), -configuration and semantics will be covered incrementally. However for people -that want to play with the system ASAP, this section is a tutorial that shows -how to configure and interact with 3 Sentinel instances. - -Here we assume that the instances are executed at port 5000, 5001, 5002. -We also assume that you have a running Valkey primary at port 6379 with a -replica running at port 6380. We will use the IPv4 loopback address 127.0.0.1 -everywhere during the tutorial, assuming you are running the simulation -on your personal computer. - -The three Sentinel configuration files should look like the following: - - port 5000 - sentinel monitor mymaster 127.0.0.1 6379 2 - sentinel down-after-milliseconds mymaster 5000 - sentinel failover-timeout mymaster 60000 - sentinel parallel-syncs mymaster 1 - -The other two configuration files will be identical but using 5001 and 5002 -as port numbers. - -A few things to note about the above configuration: - -* The primary set is called `mymaster`. It identifies the primary and its replicas. Since each *primary set* has a different name, Sentinel can monitor different sets of primaries and replicas at the same time. -* The quorum was set to the value of 2 (last argument of `sentinel monitor` configuration directive). -* The `down-after-milliseconds` value is 5000 milliseconds, that is 5 seconds, so primaries will be detected as failing as soon as we don't receive any reply from our pings within this amount of time. - -Once you start the three Sentinels, you'll see a few messages they log, like: - - +monitor master mymaster 127.0.0.1 6379 quorum 2 - -This is a Sentinel event, and you can receive this kind of events via Pub/Sub -if you `SUBSCRIBE` to the event name as specified later in [_Pubsub Messages_ section](#pubsub-messages). - -Sentinel generates and logs different events during failure detection and -failover. - -Asking Sentinel about the state of a primary ---- - -The most obvious thing to do with Sentinel to get started, is check if the -primary it is monitoring is doing well: - - $ valkey-cli -p 5000 - 127.0.0.1:5000> sentinel master mymaster - 1) "name" - 2) "mymaster" - 3) "ip" - 4) "127.0.0.1" - 5) "port" - 6) "6379" - 7) "runid" - 8) "953ae6a589449c13ddefaee3538d356d287f509b" - 9) "flags" - 10) "master" - 11) "link-pending-commands" - 12) "0" - 13) "link-refcount" - 14) "1" - 15) "last-ping-sent" - 16) "0" - 17) "last-ok-ping-reply" - 18) "735" - 19) "last-ping-reply" - 20) "735" - 21) "down-after-milliseconds" - 22) "5000" - 23) "info-refresh" - 24) "126" - 25) "role-reported" - 26) "master" - 27) "role-reported-time" - 28) "532439" - 29) "config-epoch" - 30) "1" - 31) "num-slaves" - 32) "1" - 33) "num-other-sentinels" - 34) "2" - 35) "quorum" - 36) "2" - 37) "failover-timeout" - 38) "60000" - 39) "parallel-syncs" - 40) "1" - -As you can see, it prints a number of information about the primary. There are -a few that are of particular interest for us: - -1. `num-other-sentinels` is 2, so we know the Sentinel already detected two more Sentinels for this primary. If you check the logs you'll see the `+sentinel` events generated. -2. `flags` is just `master`. If the primary was down we could expect to see `s_down` or `o_down` flag as well here. -3. `num-slaves` is correctly set to 1, so Sentinel also detected that there is an attached replica to our primary. - -In order to explore more about this instance, you may want to try the following -two commands: - - SENTINEL replicas mymaster - SENTINEL sentinels mymaster - -The first will provide similar information about the replicas connected to the -primary, and the second about the other Sentinels. - -Obtaining the address of the current primary ---- - -As we already specified, Sentinel also acts as a configuration provider for -clients that want to connect to a set of primary and replicas. Because of -possible failovers or reconfigurations, clients have no idea about who is -the currently active primary for a given set of instances, so Sentinel exports -an API to ask this question: - - 127.0.0.1:5000> SENTINEL get-master-addr-by-name mymaster - 1) "127.0.0.1" - 2) "6379" - -### Testing the failover - -At this point our toy Sentinel deployment is ready to be tested. We can -just kill our primary and check if the configuration changes. To do so -we can just do: - - valkey-cli -p 6379 DEBUG sleep 30 - -This command will make our primary no longer reachable, sleeping for 30 seconds. -It basically simulates a primary hanging for some reason. - -If you check the Sentinel logs, you should be able to see a lot of action: - -1. Each Sentinel detects the primary is down with an `+sdown` event. -2. This event is later escalated to `+odown`, which means that multiple Sentinels agree about the fact the primary is not reachable. -3. Sentinels vote a Sentinel that will start the first failover attempt. -4. The failover happens. - -If you ask again what is the current primary address for `mymaster`, eventually -we should get a different reply this time: - - 127.0.0.1:5000> SENTINEL get-master-addr-by-name mymaster - 1) "127.0.0.1" - 2) "6380" - -So far so good... At this point you may jump to create your Sentinel deployment -or can read more to understand all the Sentinel commands and internals. - -## Sentinel API - -Sentinel provides an API in order to inspect its state, check the health -of monitored primaries and replicas, subscribe in order to receive specific -notifications, and change the Sentinel configuration at run time. - -By default Sentinel runs using TCP port 26379 (note that 6379 is the normal -Valkey port). Sentinels accept commands using the Valkey protocol, so you can -use `valkey-cli` or any other unmodified Valkey client in order to talk with -Sentinel. - -It is possible to directly query a Sentinel to check what is the state of -the monitored Valkey instances from its point of view, to see what other -Sentinels it knows, and so forth. Alternatively, using Pub/Sub, it is possible -to receive *push style* notifications from Sentinels, every time some event -happens, like a failover, or an instance entering an error condition, and -so forth. - -### Sentinel commands - -The `SENTINEL` command is the main API for Sentinel. The following is the list of its subcommands (minimal version is noted for where applicable): - -* **SENTINEL CONFIG GET ``** (`>= 6.2`) Get the current value of a global Sentinel configuration parameter. The specified name may be a wildcard, similar to the Valkey `CONFIG GET` command. -* **SENTINEL CONFIG SET `` ``** (`>= 6.2`) Set the value of a global Sentinel configuration parameter. -* **SENTINEL CKQUORUM ``** Check if the current Sentinel configuration is able to reach the quorum needed to failover a primary, and the majority needed to authorize the failover. This command should be used in monitoring systems to check if a Sentinel deployment is ok. -* **SENTINEL FLUSHCONFIG** Force Sentinel to rewrite its configuration on disk, including the current Sentinel state. Normally Sentinel rewrites the configuration every time something changes in its state (in the context of the subset of the state which is persisted on disk across restart). However sometimes it is possible that the configuration file is lost because of operation errors, disk failures, package upgrade scripts or configuration managers. In those cases a way to force Sentinel to rewrite the configuration file is handy. This command works even if the previous configuration file is completely missing. -* **SENTINEL FAILOVER `` [COORDINATED]** Force a failover as if the primary was not reachable, and without asking for agreement to other Sentinels (however a new version of the configuration will be published so that the other Sentinels will update their configurations).\ -In Valkey 9.0 and later, this command accepts a `COORDINATED` option. When used, Sentinel attempts to be elected as failover leader and will trigger a coordinated failover between the primary and one of its replicas. -* **SENTINEL GET-MASTER-ADDR-BY-NAME ``** Return the ip and port number of the primary with that name. If a failover is in progress or terminated successfully for this primary it returns the address and port of the promoted replica. -* **SENTINEL INFO-CACHE** Return cached `INFO` output from primaries and replicas. -* **SENTINEL IS-MASTER-DOWN-BY-ADDR ** Check if the primary specified by ip:port is down from current Sentinel's point of view. This command is mostly for internal use. -* **SENTINEL MASTER ``** Show the state and info of the specified primary. -* **SENTINEL MASTERS** Show a list of monitored primaries and their state. -* **SENTINEL MONITOR** Start Sentinel's monitoring. Refer to the [_Reconfiguring Sentinel at Runtime_ section](#reconfiguring-sentinel-at-runtime) for more information. -* **SENTINEL MYID** (`>= 6.2`) Return the ID of the Sentinel instance. -* **SENTINEL PENDING-SCRIPTS** This command returns information about pending scripts. -* **SENTINEL REMOVE** Stop Sentinel's monitoring. Refer to the [_Reconfiguring Sentinel at Runtime_ section](#reconfiguring-sentinel-at-runtime) for more information. -* **SENTINEL REPLICAS ``** Show a list of replicas for this primary, and their state. -* **SENTINEL SENTINELS ``** Show a list of sentinel instances for this primary, and their state. -* **SENTINEL SET** Set Sentinel's monitoring configuration. Refer to the [_Reconfiguring Sentinel at Runtime_ section](#reconfiguring-sentinel-at-runtime) for more information. -* **SENTINEL SIMULATE-FAILURE (crash-after-election|crash-after-promotion|help)** This command simulates different Sentinel crash scenarios. -* **SENTINEL RESET ``** This command will reset all the primaries with matching name. The pattern argument is a glob-style pattern. The reset process clears any previous state in a primary (including a failover in progress), and removes every replica and sentinel already discovered and associated with the primary. - -For connection management and administration purposes, Sentinel supports the following subset of Valkey's commands: - -* **ACL** (`>= 6.2`) This command manages the Sentinel Access Control List. For more information refer to the [ACL](acl.md) documentation page and the [_Sentinel Access Control List authentication_](#sentinel-access-control-list-authentication). -* **AUTH** Authenticate a client connection. For more information refer to the `AUTH` command and the [_Configuring Sentinel instances with authentication_ section](#configuring-sentinel-instances-with-authentication). -* **CLIENT** This command manages client connections. For more information refer to its subcommands' pages. -* **COMMAND** (`>= 6.2`) This command returns information about commands. For more information refer to the `COMMAND` command and its various subcommands. -* **HELLO** (`>= 6.0`) Switch the connection's protocol. For more information refer to the `HELLO` command. -* **INFO** Return information and statistics about the Sentinel server. For more information see the `INFO` command. -* **PING** This command simply returns PONG. -* **ROLE** This command returns the string "sentinel" and a list of monitored primaries. For more information refer to the `ROLE` command. -* **SHUTDOWN** Shut down the Sentinel instance. - -Lastly, Sentinel also supports the `SUBSCRIBE`, `UNSUBSCRIBE`, `PSUBSCRIBE` and `PUNSUBSCRIBE` commands. Refer to the [_Pub/Sub Messages_ section](#pubsub-messages) for more details. - -### Reconfiguring Sentinel at Runtime - -Sentinel provides an API in order to add, remove, or change the configuration of a given primary. Note that if you have multiple sentinels you should apply the changes to all to your instances for Valkey Sentinel to work properly. This means that changing the configuration of a single Sentinel does not automatically propagate the changes to the other Sentinels in the network. - -The following is a list of `SENTINEL` subcommands used in order to update the configuration of a Sentinel instance. - -* **SENTINEL MONITOR `` `` `` ``** This command tells the Sentinel to start monitoring a new primary with the specified name, ip, port, and quorum. It is identical to the `sentinel monitor` configuration directive in `sentinel.conf` configuration file, with the difference that you can't use a hostname in as `ip`, but you need to provide an IPv4 or IPv6 address. -* **SENTINEL REMOVE ``** is used in order to remove the specified primary: the primary will no longer be monitored, and will totally be removed from the internal state of the Sentinel, so it will no longer listed by `SENTINEL masters` and so forth. -* **SENTINEL SET `` [`