Tuesday, August 12, 2025

Redis ClusterRedirectException Explanation : ClusterRedirectException: Redirect: slot 14865 to 10.170.15.31:6379

Redis ClusterRedirectException Explanation
Understanding Redis ClusterRedirectException in Spring & AWS

❓ The Exception

org.springframework.data.redis.ClusterRedirectException: Redirect: slot 14865 to 10.170.15.31

This error occurs when you're using a Redis Cluster (e.g. AWS ElastiCache in cluster mode), and the client tries to access a Redis slot that is managed by a different node.

🔍 What Does It Mean?

  • Redis Cluster splits the keyspace into 16,384 hash slots.
  • Each Redis node handles a subset of these slots.
  • If your client accesses a key from the wrong node, Redis returns a MOVED redirect.
  • Spring Data Redis receives this and throws a ClusterRedirectException.

📦 Example Scenario

  • You try to access a key that hashes to slot 14865.
  • Your client contacts a node that does not own that slot.
  • Redis replies with:
    MOVED 14865 10.170.15.31:6379

🚨 Why This Happens

  • Your client may not be fully cluster-aware.
  • You’re using Jedis or Spring Redis without proper cluster configuration.
  • Only a single node was configured, so slot ownership is unknown to the client.

✅ Proper Configuration (Lettuce)

Use LettuceConnectionFactory with a RedisClusterConfiguration:

@Bean
public LettuceConnectionFactory redisConnectionFactory() {
    RedisClusterConfiguration clusterConfig = new RedisClusterConfiguration();
    clusterConfig.clusterNode("10.170.15.31", 6379);
    clusterConfig.clusterNode("10.170.15.32", 6379);
    return new LettuceConnectionFactory(clusterConfig);
}
    

✅ For Jedis Users

@Bean
public JedisConnectionFactory jedisConnectionFactory() {
    RedisClusterConfiguration clusterConfig = new RedisClusterConfiguration();
    clusterConfig.clusterNode("10.170.15.31", 6379);
    clusterConfig.clusterNode("10.170.15.32", 6379);
    return new JedisConnectionFactory(clusterConfig);
}
    
⚠️ Do not use spring.redis.host and spring.redis.port for Redis Cluster. This connects as a standalone instance and does not support slot redirection.

🧠 Best Practices

  • Use cluster-aware clients like Lettuce or JedisCluster.
  • Configure multiple cluster nodes for failover and topology discovery.
  • Use spring.redis.cluster.nodes instead of host/port in application.properties.
spring.redis.cluster.nodes=10.170.15.31:6379,10.170.15.32:6379
spring.redis.timeout=60000
    
✅ A properly configured client will automatically follow Redis redirects and update its slot cache.
Redis Cluster Mode + Spring Data Redis · Explanation by ChatGPT · August 2025

How to Use RECOMPILE with JPA Query?

How to Use RECOMPILE with JPA Query?

How to Use RECOMPILE with JPA Query?

In JPA, there is no direct way to add SQL Server’s RECOMPILE hint because JPA abstracts database specifics. However, you can achieve similar behavior by using native queries with the OPTION (RECOMPILE) hint or by using stored procedures with WITH RECOMPILE.

1. Using Native Query with OPTION (RECOMPILE)

You can append the SQL Server hint directly in your native SQL query:

String sql = "SELECT * FROM Orders WHERE CustomerID = ?1 OPTION (RECOMPILE)";
Query query = entityManager.createNativeQuery(sql, Order.class);
query.setParameter(1, customerId);
List<Order> results = query.getResultList();

2. Using Stored Procedure with WITH RECOMPILE

Create your stored procedure with the WITH RECOMPILE option:

CREATE PROCEDURE GetOrders
    @CustomerID INT
WITH RECOMPILE
AS
BEGIN
    SELECT * FROM Orders WHERE CustomerID = @CustomerID;
END

Then call it from JPA:

StoredProcedureQuery spQuery = entityManager.createStoredProcedureQuery("GetOrders", Order.class);
spQuery.registerStoredProcedureParameter("CustomerID", Integer.class, ParameterMode.IN);
spQuery.setParameter("CustomerID", customerId);
List<Order> results = spQuery.getResultList();

3. Notes

  • JPA query hints cannot add SQL Server-specific RECOMPILE options.
  • Native queries provide the most direct control over SQL syntax and hints.
  • Stored procedures with WITH RECOMPILE let SQL Server handle plan recompilation.

Summary

To use RECOMPILE in JPA, prefer native queries with OPTION (RECOMPILE) or call stored procedures created with WITH RECOMPILE. This approach forces SQL Server to generate fresh execution plans, helping avoid parameter sniffing issues.

What is Query Sniffing in MS SQL Server?

What is Query Sniffing in MS SQL Server?

What is Query Sniffing in MS SQL Server?

Query sniffing, often called parameter sniffing, is a behavior in SQL Server where the query optimizer “sniffs” the parameter values passed to a stored procedure or parameterized query the first time it compiles the execution plan.

How It Works

When you execute a stored procedure or parameterized query, SQL Server looks at the actual parameter values during the first execution. It uses these values to create an execution plan optimized for those specific parameters. This plan is then cached and reused for subsequent executions — even if those later executions have very different parameter values.

Why Is This Important?

If the parameter values vary widely and need different execution strategies, reusing the same plan may cause poor performance because the cached plan might be perfect for the initial parameters but inefficient for others.

Example

CREATE PROCEDURE GetOrdersByCustomer
    @CustomerID INT
AS
BEGIN
    SELECT * FROM Orders WHERE CustomerID = @CustomerID;
END

Suppose the first execution uses @CustomerID = 1, which has only a few orders. SQL Server generates a plan optimized for a small result set. Later, the procedure is executed with @CustomerID = 1000, who has thousands of orders. The cached plan may still be optimized for small sets, resulting in slow queries.

How to Detect Parameter Sniffing Issues

  • Queries that run fast sometimes and slow other times with different parameters.
  • Execution plans reused but not optimal for all parameter values.
  • Large differences between estimated and actual row counts.

How to Fix or Avoid Parameter Sniffing

Method Description
OPTION (RECOMPILE) Forces a new plan compilation for each execution.
WITH RECOMPILE Stored procedure recompiles on every execution.
OPTIMIZE FOR hint Tells optimizer to use a specific parameter value.
Use local variables Prevents optimizer from sniffing parameters directly.
Plan guides Advanced control over query optimization.
Query rewrite Splitting queries or procedures based on parameter patterns.

Summary

Parameter sniffing is a performance optimization feature but can cause unexpected slowdowns when data or parameters vary greatly. Understanding and managing it properly helps maintain consistent query performance.

What is RECOMPILE in SQL Server?

What is RECOMPILE in SQL Server?

What is RECOMPILE in SQL Server?

In SQL Server, RECOMPILE is an option that forces the query optimizer to not reuse a previously cached execution plan and instead generate a new execution plan every time the query or stored procedure runs.

Why Use RECOMPILE?

Normally, SQL Server caches execution plans to improve performance by avoiding the overhead of recompiling queries every time.

But sometimes, the cached plan is not optimal for all parameter values — this is especially true when:

  • Parameter sniffing causes a bad plan to be reused.
  • Data distribution changes significantly.
  • Query performance varies widely depending on input parameters.

In these cases, using RECOMPILE forces SQL Server to create a fresh execution plan tailored to the current parameter values, which can improve query performance.

How to Use RECOMPILE

1. At the query level (using a query hint):

SELECT * FROM Orders WHERE CustomerID = @CustomerID
OPTION (RECOMPILE);

2. At the stored procedure level:

CREATE PROCEDURE GetOrders
    @CustomerID INT
WITH RECOMPILE
AS
BEGIN
    SELECT * FROM Orders WHERE CustomerID = @CustomerID;
END

3. Using the system stored procedure sp_recompile:

EXEC sp_recompile 'GetOrders';

Pros and Cons

Pros Cons
Gets a fresh, optimized plan each time Extra CPU overhead for recompilation
Avoids poor performance from bad cached plans May slow down queries if overused

Summary

RECOMPILE forces SQL Server to generate a fresh execution plan each time, helping to avoid performance problems caused by parameter sniffing or stale plans.

Use it when query performance varies widely with different parameters, but be careful since it increases CPU usage.

AWS Global vs Regional Services AWS Global vs Regional Services Category Global Services...