I need my microservice to wait for the database to become available before proceeding. There is a sidecar Cloud SQL proxy involved that requires some time for the database connection.
My current approach involves a for loop that retries connecting after a defined interval, but it doesn't seem to wait properly before reconnecting.
class Database {
static async connectDatabase() {
try {
const maxRetries = 20;
const retryDelay = async (currentRetry, maxRetries) => {
return new Promise((resolve) =>
setTimeout(function () {
logger.info(`Retry attempt: ${currentRetry}, ${maxRetries} retries left.`);
}, 1000));
};
for (let i = 1; i <= maxRetries; i++) {
try {
// Establish database connection
await SequelizeConnection.authenticate()
.then(() => {
logger.info("*** Database connection established successfully.");
})
.catch(async (err) => {
logger.info("Error in connect database function: ", err);
throw err;
});
await SeqzelizeConnectionHealthcheck.authenticate()
.then(() => {
logger.info("*** Healthcheck database connection established successfully.");
})
.catch(async (err) => {
logger.error("Error in healthcheck connection function: ", err);
throw err;
});
} catch (error) {
logger.error("Error in connectDB retry function");
await retryDelay(i, maxRetries - i);
}
}
} catch (error) {
logger.error("Error in connect database function: ", error);
}
}
}
I've attempted using retry libraries and creating a retry wrapper function, but haven't had success with either method.