Carlo Luisito
Carlo Luisito

Reputation: 229

.Net Core - Docker Linux memory usage keeps increasing

I am bit frustrated now what's wrong with my code, and I hope you guys can help me with it, so here are the things I have tried.

so I tried making the HttpClient static, and I tried using the IHttpClientFactory.CreateClient() and I even added this on my .csproj

<ServerGarbageCollection>false</ServerGarbageCollection>

Here is the sample code that I have been doing

public class TestController : BaseController
{
    private static HttpClient _httpClient = new();

    public TestController()
    {
    }

    [HttpGet("bills")]
    public async Task<IActionResult> GetBillsPresentment([FromQuery] GetBillPresentmentQuery query)
    {
        if (!query.AccountNumber.Contains("-"))
            query.AccountNumber = FormatAccountNumber(query.AccountNumber);

        var billDetails = await GetBillDetail(query.AccountNumber);

        if (billDetails == null)
            throw new ProviderProcessException(ProviderErrorCode.INVALID_ACCOUNT_NUMBER);

        return Ok(new BillPresentmentVm
        {
            User = new CustomerDto
            {
                CustomerName = billDetails.Name
            },
            Billing = new BillingDto
            {
                AccountNumber = query.AccountNumber,
                DueDate = DateTime.Parse(billDetails.LastReadDate).AddMonths(1),
                Outstanding = !string.IsNullOrEmpty(billDetails.Arrears) ? decimal.Parse(billDetails.Arrears) : null
            }
        });
    }

    private async Task<ResponseModel> GetBillDetail(string accountNumber)
    {
        try
        {
            var payload = new { accno = accountNumber };

            string json = JsonConvert.SerializeObject(payload);

            var buffer = System.Text.Encoding.UTF8.GetBytes(json);
            using var byteContent = new ByteArrayContent(buffer);
            byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            var response = await _httpClient.PostAsync("https://test.com", byteContent);

            if (!response.IsSuccessStatusCode)
                throw new ProviderProcessException(ProviderErrorCode.BILLING_CYCLE_UNAVAILABLE);

            var result = await response.Content.ReadAsStringAsync();

            if (result == "Accno not found!") return null;

            var data = JsonConvert.DeserializeObject<ResponseModel>(result);
            return data;
        }
        catch (Exception)
        {
            throw new ProviderProcessException(ProviderErrorCode.BILLING_CYCLE_UNAVAILABLE);
        }
    }

    private static string FormatAccountNumber(string accountNumber)
    {
        return string.Format("{0:#######-########}", Convert.ToInt64(accountNumber));
    }
}

And here's the docker memory usage enter image description here

The memory usage keeps increasing after a request. Can someone explains me why it is not decreasing?

Thank you very much in advance

Upvotes: 1

Views: 2782

Answers (2)

SaeedSysDev
SaeedSysDev

Reputation: 11

I use some thing like this and it works fine on large amount of requests per second and it use memory in normal way .

    public class ApiRepo : IApiRepo
    {
        private readonly IHttpClientFactory _HttpClientFactory;
        public ApiRepo (IHttpClientFactory httpClientFactory)
        {
            _HttpClientFactory = httpClientFactory;
        }

        public async Task<ResponseModel> PostMyObject(Myobject model, CancellationToken cancellationToken)
        {
            HttpClient httpClient = _HttpClientFactory.CreateClient("ApiDestinationURI");

            using HttpRequestMessage request = new(HttpMethod.Post, "/blah/blah");
            request.Content = new StringContent(JsonSerializer.Serialize(model));
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            HttpResponseMessage response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead, cancellationToken);
            response.EnsureSuccessStatusCode();
            string createdContent = await response.Content.ReadAsStringAsync();
            ResponseModel ResponseReturn = JsonSerializer.Deserialize<ResponseModel>(createdContent);
            return ResponseReturn;
        }
    }

Upvotes: 1

Related Questions