iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🍃

Implementing a Multi-Region DataSource for Amazon Aurora DSQL

に公開
2025/01/07

javax.sql.DataSource with 99.999% Availability

Multi-region Amazon Aurora DSQL offers 99.999% availability. Because it is an active-active configuration with constant data synchronization, applications can process requests regardless of which region they connect to. While it is naturally faster to connect to an endpoint in the same region, there are cases where connecting to a distant region is acceptable if the additional latency is only around 100-200 milliseconds.

So, I have created a custom DataSource implementation to achieve the following architecture.

Features of the Custom DataSource Implementation

The experimental DataSource implementation has the following features:

  1. Inherits from org.springframework.jdbc.datasource.AbstractDataSource.
  2. It does not have connection pooling functionality itself. Connection pooling is achieved by wrapping it with HikariCP.
  3. It determines the next connection destination from Aurora DSQL endpoints using a round-robin approach.
  4. It calls the isValid() method on the obtained connection to verify its health.
  5. If connection or health check fails, it throws a SQLException to notify the exception.
  6. When a SQLException is thrown, the entire method is retried.
  7. During retries, a different endpoint from the one that threw the exception is used (due to the round-robin logic).

The java.sql.DataSource#getConnection() method to be implemented looks like the code below. The retry logic is implemented solely by adding the @Retryable annotation.

    /**
     * Implementation of {@link javax.sql.DataSource#getConnection(String, String)}
     */
    @Retryable(retryFor = SQLException.class, maxAttempts = 4, backoff = @Backoff(delay = 0))
    @Override
    public Connection getConnection(final String username, final String password) throws SQLException {

        // Determine the next connection destination from DSQL endpoints using round-robin
        final int index = this.counter.getAndUpdate(v -> v == Integer.MAX_VALUE ? 0 : v + 1);
        final String region = this.regions[index % this.regions.length];
        final String endpoint = regionalEndpoints.get(region);

        try {
            // Get the token used for connection from the cache. Generate a new one if it has expired
            final String token = this.tokenCache.compute(endpoint,
                    (k, v) -> v == null || v.isExpired(System.currentTimeMillis())
                            ? new CacheEntry(
                                    this.generateAuthToken(endpoint, region, this.dsqlTokenExpirationSeconds),
                                    this.dsqlTokenExpirationSeconds * 900 + System.currentTimeMillis())
                            : v).getToken();

            // Obtain a new connection using the selected endpoint and token
            final Connection connection = regionalDataSources.get(region).getConnection(username, token);
            if (!connection.isValid(this.connectionTimeout)) {
                // If the obtained connection is not healthy, throw a SQLException to notify the exception
                // When an exception occurs, this entire method is retried, attempting to get a connection from a different region
                throw new SQLException("The connection obtained from the DataSource is invalid.");
            }

            // Return the connection if it is healthy
            this.logger.debug("get a new connection from: " + region + ", connection=" + connection.toString());
            return connection;
        } catch (SQLException e) {
            this.logger.debug("a sql exception occurred at: " + region + ", message=" + e.getMessage());
            throw e;
        }
    }

Obtaining and Caching Connection Tokens

Currently, Amazon Aurora DSQL uses time-limited tokens obtained via an API for connections instead of fixed passwords. Since the token acquisition API needs to be called individually for each region, rather than holding a single password as a DataSource, I implemented it to obtain a token whenever a connection is acquired.

However, issuing a new token for every single connection would be high overhead, so I incorporated a mechanism to reuse tokens cached in memory during their validity period.

HikariCP Configuration Wrapping the Custom DataSource

The connection pooling functionality is not handled by the custom DataSource; instead, it is delegated to HikariCP, the default connection pooling feature of Spring Framework.

    @Bean
    @Primary
    public DataSource dataSource(@Qualifier("rawDataSource") final DataSource rawDataSource) {

        final HikariDataSource ds = new HikariDataSource();
        ds.setDataSource(rawDataSource); // Wrap the custom DataSource implementation
        ds.setExceptionOverrideClassName(DsqlExceptionOverride.class.getName()); // Optimize exception handling for Aurora DSQL

        return ds;
    }

It might be easily overlooked since it cannot be configured via properties, but HikariCP actually allows you to pass an external DataSource for obtaining connections. This enables a division of labor where obtaining new connections is left to the external DataSource, while HikariCP itself focuses on the logic for pooling the obtained connections.

Additionally, since there are cases where we want to retry without closing the connection when a subclass of SQLException is thrown, I have overridden HikariCP's exception handling and optimized it for Aurora DSQL. For detailed implementation, please refer to the following:
https://docs.aws.amazon.com/ja_jp/aurora-dsql/latest/userguide/SECTION_program-with-java-apps.html#SECTION_program-with-java-apps-exceptions

Retry Logic

I have not written any logic for retrying connection acquisition at all. The only thing I did was add the @Retryable annotation. This annotation is provided by a project called Spring Retry. Since this library has a proven track record of being used in other Spring Framework libraries such as Spring Batch and Spring Integration, I think it can be adopted with a certain level of confidence.
https://github.com/spring-projects/spring-retry

I have also provided an experimental implementation using the combination of Spring Retry and Aurora DSQL here.
https://zenn.dev/akring/articles/1fc39ead4f6604

Summary

In this way, I was able to create a DataSource implementation that can seamlessly select and use endpoints across multiple regions very easily. While there is plenty of room to make the endpoint selection logic smarter—such as prioritizing endpoints in the region where the application is running or removing endpoints that consistently error out from the selection pool—the current implementation seems sufficient for a start.

While I have some concerns about whether it is truly okay for it to be this easy to implement, I believe the implementation has become extremely simple thanks to being freed from traditional issues, such as endpoints changing based on the presence of write operations or having to be mindful of data synchronization latency. After all, since any connection in the connection pool allows for reading and writing data by executing SQL in exactly the same way, I was able to build something that works even with a crude selection method like round-robin. Aurora DSQL is quite powerful and interesting.

Discussion