MongoDB -Add Health Check In ASP.NET Core API

MongoDB Add Health Check In ASPNET Core API

In this article, we shall check how to implement MongoDB -Add Health Check In ASP.NET Core API or MVC applications.

Implementing a health check is mandatory in many stages of the application development life cycle. It helps you to keep track of the health of numerous resources, databases, and services that your business application relies on in real-time.

This enables you to quickly troubleshoot and resolve technical or environmental issues.

Health check services and middleware in ASP.Net core allow us to validate APIs by allowing us to create health check routes. It also allows us to validate the health of other resources such as external service connections, external databases, and so on.

Example: Mongo Server database

Today in this article, we will cover below aspects,

These simple and easy-to-use feature lets you check the status of your resources and dependencies.

MongoDB Add Health Check- Getting started

If you already have an API, then please follow below two steps,

Create MongoDB health checks using IHealthCheck interface

Creating MongoDB health checks using the IHealthCheck interface is simple and it is explained in detail with high-level steps.

Step1 – Implement Mongo IHealthCheck interface

Here please implement the IHealthCheck interface and override the CheckHealthAsync method.

Here we are defining MongoHealth check using MongoClient and Mongo Database. We shall use the “ping” command to check the connectivity with the database.

public class MongoHealthCheck : IHealthCheck
    {
        private IMongoDatabase _db { get; set; }
        public MongoClient _mongoClient { get; set; }

        public MongoHealthCheck(IOptions<Mongosettings> configuration)
        {
            _mongoClient = new MongoClient(configuration.Value.Connection);

            _db = _mongoClient.GetDatabase(configuration.Value.DatabaseName);

        }

..

}

 

Let’s now define the CheckHealthAsync which is the IHealthCheck interface method implemented for MongoDB connection.

Below is the implementation of the method,

public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
         
            var healthCheckResultHealthy = await CheckMongoDBConnectionAsync();


            if (healthCheckResultHealthy)
            {
                return HealthCheckResult.Healthy("MongoDB health check success");
            }

            return HealthCheckResult.Unhealthy("MongoDB health check failure"); ;
        }

HealthCheckResult lets you return health as HealthyDegraded, or Unhealthy statuses.

CheckMongoDBConnectionAsync method is defined as below,

 private async Task<bool> CheckMongoDBConnectionAsync()
        {
            try
            {
               await _db.RunCommandAsync((Command<BsonDocument>)"{ping:1}");
            }

            catch (Exception)
            {
                return false;
            }

            return true;
        }

In the above method, for any connection failure, you shall get an exception that can be used to return the failure status of the method.

For more granular control the waited method can be used using Example – Wait(1000) where you can configure, how much time you want to wait before reporting the health status.

Step2 – Register MongoDB health check services

In Startup.ConfigureServices please add the HealthChecks as below,

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.Configure<Mongosettings>(options =>
            {
                options.Connection = Configuration.GetSection("MongoSettings:Connection").Value;
                options.DatabaseName = Configuration.GetSection("MongoSettings:DatabaseName").Value;
            });

            services.AddHealthChecks()
               .AddCheck<MongoHealthCheck>("MongoDBConnectionCheck");
            services.AddScoped<IMongoBookDBContext, MongoBookDBContext>();
        }

Below is a sample Configure method,

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseHealthChecks("/healthcheck");

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

Let’s execute the route “/health check” and we shall get the Mongo Health check success as below,

Health Check for MongoDB ASPNET Core

You shall be able to verify HealthyDegraded, or Unhealthy status accordingly.

References:

Summary

A health check is critical in multiple aspects and allows you to check the health of various resources, databases, services your application is dependent on. Today in this article, we looked at a simple approach of enabling Health Check for MongoDB ASP.NET Core application.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *