Skip to Content
Managed services

Connect to Valkey

Use the connection returned by the Console or API. It has the valkeys://user:password@host:port/0 format and should be provided to the application through the VALKEY_URL variable.

Required permissions

To obtain the connection through the API, use managed_service.connection.read on managed_service:<project-id>. To request credential rotation, use managed_service.credentials.rotate on the same ID. To turn public access on or off, use managed_service.exposure.update. owner has full access; assistant, member, and organization API Keys need the corresponding grant.

Security rules

  • Always use TLS and validate the host certificate.
  • Keep the default user and password out of source code.
  • Never use options that disable TLS, certificate, or hostname validation.
  • Reuse one connection or pool per process; do not create a new connection for every command.
  • Rotation is asynchronous and idempotent: the API accepts the request with 202 and an Idempotency-Key header, and the new connection is delivered only when the operation completes. Use GET /v1/managed-services/:id/linked-applications to find out which applications use the service. Then replace the protected variable and restart workers that keep old connections.

By default, the connection host and port are public. If public access is off, that address stops accepting connections, the GET /v1/managed-services/:id/connection response returns exposure: "private", and the application must connect through the internal address of a private connection, following the TLS rules for the internal address. The username, password, and database 0 stay the same.

Some libraries accept only redis:// or rediss://. Replacing valkeys:// with rediss:// changes only the scheme expected by the library; TLS remains required.

Node.js and TypeScript

Install the compatible client:

npm install iovalkey
import Redis from 'iovalkey'

const rawUrl = process.env.VALKEY_URL
if (!rawUrl) throw new Error('VALKEY_URL is required')

const parsed = new URL(rawUrl)
if (parsed.protocol !== 'valkeys:') throw new Error('VALKEY_URL must use valkeys://')

const client = new Redis({
  host: parsed.hostname,
  port: Number(parsed.port),
  username: decodeURIComponent(parsed.username),
  password: decodeURIComponent(parsed.password),
  tls: { servername: parsed.hostname },
})

await client.set('healthcheck', 'ok', 'EX', 60)
console.log(await client.get('healthcheck'))
await client.quit()

Python

Install valkey-py:

python -m pip install valkey
import os
from urllib.parse import urlparse
from valkey import Valkey

raw_url = os.environ["VALKEY_URL"]
parsed = urlparse(raw_url)
if parsed.scheme != "valkeys":
    raise ValueError("VALKEY_URL must use valkeys://")

client = Valkey(
    host=parsed.hostname,
    port=parsed.port,
    username=parsed.username,
    password=parsed.password,
    db=0,
    ssl=True,
    ssl_check_hostname=True,
    decode_responses=True,
)

client.set("healthcheck", "ok", ex=60)
print(client.get("healthcheck"))
client.close()

Other clients

The packages below are recommended or compatible Valkey options. In every case, extract host, port, username, and password from VALKEY_URL, enable TLS, and validate the hostname.

LanguageInstallationClient
Gogo get github.com/valkey-io/valkey-govalkey-go
Javaio.valkey:valkey-javavalkey-java
PHPredis extension, included in the PHP runtimephpredis
PHPcomposer require predis/predisPredis
.NETValkey GLIDE packageValkey GLIDE C#
Rubygem install redisredis
Rustcargo add redis --features tokio-native-tls-compredis

Minimal Go example, adapting the scheme because valkey-go accepts rediss://:

package main

import (
  "context"
  "log"
  "os"
  "strings"

  valkey "github.com/valkey-io/valkey-go"
)

func main() {
rawURL := strings.Replace(os.Getenv("VALKEY_URL"), "valkeys://", "rediss://", 1)
client, err := valkey.NewClient(valkey.MustParseURL(rawURL))
if err != nil { log.Fatal(err) }
defer client.Close()
if err := client.Do(context.Background(), client.B().Ping().Build()).Error(); err != nil { log.Fatal(err) }
}

Java with valkey-java (a Jedis fork):

var uri = java.net.URI.create(System.getenv("VALKEY_URL").replaceFirst("^valkeys", "rediss"));
var credentials = uri.getUserInfo().split(":", 2);
var host = uri.getHost();
var port = uri.getPort();
var username = java.net.URLDecoder.decode(credentials[0], java.nio.charset.StandardCharsets.UTF_8);
var password = java.net.URLDecoder.decode(credentials[1], java.nio.charset.StandardCharsets.UTF_8);
var pool = new io.valkey.JedisPool(
    new io.valkey.JedisPoolConfig(), host, port, 5000, username, password, 0, true);
try (var client = pool.getResource()) {
    client.set("healthcheck", "ok");
    System.out.println(client.get("healthcheck"));
} finally {
    pool.close();
}

PHP with phpredis, the redis extension that ships with the Zenifra PHP runtime. The tls:// scheme verifies the certificate and hostname:

<?php
$url = parse_url(getenv('VALKEY_URL'));
$redis = new Redis();
$redis->connect('tls://' . $url['host'], $url['port']);
$redis->auth([rawurldecode($url['user']), rawurldecode($url['pass'])]);
$redis->set('healthcheck', 'ok');
echo $redis->get('healthcheck'), PHP_EOL;

In Laravel, set REDIS_URL to the console URI. Laravel 13 accepts the valkeys:// scheme and verifies the certificate; if your version does not recognize that scheme, change it to rediss://.

PHP with Predis; the tls scheme keeps certificate and hostname verification enabled:

<?php
$parts = parse_url(getenv('VALKEY_URL'));
$client = new Predis\Client([
    'scheme' => 'tls',
    'host' => $parts['host'],
    'port' => (int) $parts['port'],
    'username' => rawurldecode($parts['user']),
    'password' => rawurldecode($parts['pass']),
    'ssl' => ['verify_peer' => true, 'verify_peer_name' => true],
]);
$client->set('healthcheck', 'ok');
echo $client->get('healthcheck'), PHP_EOL;
$client->disconnect();

Valkey GLIDE for .NET (do not use this client in Alpine runtimes):

var rawUrl = Environment.GetEnvironmentVariable("VALKEY_URL")
    ?? throw new InvalidOperationException("VALKEY_URL is required");
var uri = new Uri(rawUrl.Replace("valkeys://", "rediss://", StringComparison.Ordinal));
var credentials = uri.UserInfo.Split(':', 2);
var host = uri.Host;
var port = uri.Port;
var username = Uri.UnescapeDataString(credentials[0]);
var password = Uri.UnescapeDataString(credentials[1]);
var config = new GlideClientConfiguration {
    Addresses = [new NodeAddress(host, port)],
    UseTls = true,
    Credentials = new ServerCredentials(username, password),
};
await using var client = await GlideClient.CreateClientAsync(config);
await client.SetAsync("healthcheck", "ok");
Console.WriteLine(await client.GetAsync("healthcheck"));

Ruby with the redis gem:

require "openssl"
require "redis"

url = ENV.fetch("VALKEY_URL").sub("valkeys://", "rediss://")
client = Redis.new(url: url, ssl_params: { verify_mode: OpenSSL::SSL::VERIFY_PEER })
client.set("healthcheck", "ok")
puts client.get("healthcheck")
client.close

Rust with the redis crate and the tokio-native-tls-comp feature:

use redis::AsyncCommands;

let url = std::env::var("VALKEY_URL")?.replacen("valkeys://", "rediss://", 1);
let client = redis::Client::open(url)?;
let mut connection = client.get_multiplexed_async_connection().await?;
connection.set::<_, _, ()>("healthcheck", "ok").await?;
println!("{}", connection.get::<_, String>("healthcheck").await?);

For Java, PHP, .NET, Ruby, and Rust, keep the system certificate store, use the returned hostname for SNI, and issue PING before starting a worker. Check the installed client version for constructor and option names without disabling TLS validation.

Test the connection

With valkey-cli, validation should be explicit:

valkey-cli -u "${VALKEY_URL/valkeys:/rediss:}" --tls ping

The expected response is PONG. Do not put the password directly in shell history; use your platform’s secret mechanism or VALKEYCLI_AUTH in a temporary process.

Next steps

Last updated on

On this page