What is the best way for you to offload the database insert so that the web response comes back faster?

Customization

I have a web service that takes its inputs through a REST interface. A REST call does not return any meaningful data, so everything that is passed to the web service is written only to the database, and that’s all. This is the analytics service that my company uses to internally process special requests for web requests that are received on their web page. Therefore, it is very important that the response takes as little time as possible in order to return as much as possible.

I have optimized the code as much as possible to make the answer as fast as possible. However, the time that the database remains open continues to open the connection longer than I want before the response is sent back to the web client.

This code looks basically like that, by the way, this is ASP.NET MVC, using the Entity Framework running on IIS 7, if that matters.

public ActionResult Add(/*..bunch of parameters..*/) {

    using (var db = new Entities()) {
        var log = new Log {
            // populate Log from parameters
        }
        db.AddToLogs(log);
        db.SaveChanges();
    }

    return File(pixelImage, "image/gif");
}

Question

Is there a way to disable database loading in another process, so the response to the client returns almost instantly?

I was thinking of packing everything in a block usingin another thread to make the database insert asynchronous, but I don't know if this was the best way to free the response back to the client.

What would you advise if you tried to achieve this goal?

+3
source share
5 answers

, . . " ", , . , , , . , , .

( /URL-), CLR , - :

...
var log = new Log {// populate Log from parameters}
ThreadPool.QueueUserWorkItem(stateInfo=>{
  var queueLog = stateInfo as Log;
  using (var db = new Entities()) 
  { 
     db.AddToLogs(queuedLog);
     db.SaveChanges(); 
  }
}, log);
...

, ASP, . :

  • , , "" , " " ( ).
  • ( )
  • CLR, ,

SqlCommand.BeginExecuteXXX AsynchronousProcessing true. , AFAIK EF , SqlClient (SqlConnection, SqlCommand). , , (= ) .

, / / . ( ), ( IO, -- -) / . , , .

+3

, , , .

singleton, ITask. ITask .

+1

, , . , , .

, , .

, , .

, .

- (JMS Java-land, dunno .NET, , , -).

+1

, , , . ( ). NOP , .

, "" - ​​ , , ?

, NOP , .

0

: , 100% , ?

:

  • .
  • The response is sent to the client.
  • Server Failure
  • Data was not stored in the database.

You also need to check how many milliseconds you save by starting a new thread instead of saving to the database.

The added cost of complexity and maintenance is probably too high compared to saving response time. And the response time savings are probably so small that they won't be noticed.

0
source

Source: https://habr.com/ru/post/1725202/


All Articles