In a typical server software design, business logic will generally invoke "services" (such as a database or web service).

When I design such a system, I tend to think of each service as a singleton which is created when the system starts up and handles multiple concurrent requests throughout the lifetime, usually not storing details of any particular request within itself.

However, there is an alternative design whereby a new instance of the service is instantiated for each request. Personally I would normally use the term "handler" instead of "service" for this.

It seems to me both patterns can work equally well. Is there a reason to prefer one over the other, or a de-facto best practice regarding this?


There is no standard or best practice here. Web applications have different architectures and lifetimes than desktop applications. Web applications tend to create one instance of those services per HTTP request. Reasons for this vary by tech stack.

For PHP web applications, the web app is initialized, executed and torn down with each request. Web applications in the .NET, Java and Ruby tech stacks get initialized with the first request to the server, and then multiple users are served from worker threads under the main server thread. Even within the realm of web applications, scope and lifetime of the code and its data varies.

Desktop applications tend to get initialized when first opened. Things within the application can live between user interactions and execution of use cases. Closing the application doesn't always kill everything. Some leave processes running in memory on purpose. Other times part of the application will start up as soon as you log in. Again, scope and lifetime varies.

Use whichever one gives you the best balance of code performance and maintainability.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.