r/SoftwareEngineering • u/Glittering-Thanks-33 • Apr 01 '25
"Service" layer becoming too big. Do you know another architecture with one more layer ?
Hi
In my team, we work on several projects using this classical architecture with 3 layers: Controller/Service/Repository.
Controllers contains endpoints, handle http responses Services contain the business logic, transform the daga Repositories retrieves the data from db
For the Controllers and Repositories it works very well: we keep these files very clean and short, the methods are straightforward.
But the issue is with the Services, most of our services are becoming very big files, with massive public methods for each business logic, and lots of private helper methods of course.
We are all already trying to improve that, by trying to extract some related methods to a new Service if the current one becomes too big, by promoting Helper or Util classes containing reusable methods, etc.
And the solution that worked best to prevent big files: by using linger rules that limit the number of methods in a single file before allowing the merge of a pull request.
But even if we try, you know how it is... Our Services are always filled to the top of the limit, and the projects are starting to have many Services for lot of sub-logic. For example:
AccountService which was enough at the beginning is now full so now we have many other services like CurrentAccountService, CheckingAccountService, CheckingAccountLinkService, CheckingAccountLinkToWithdrawService, etc etc...
The service layer is becoming a mess.
I would like to find some painless and "automatic" way to solve this issue.
My idea would be to introduce a new kind of layer, this layer would be mandatory in the team and would permit to lighten the Service layer.
But what could this layer do ? Would the layer be between Controller and Service or beween Service and Repository ?
And most important question, have you ever heard of such architecture in any framework in general, with one more layer to lighten the Service layer ?
I don't want to reinvent the wheel, maybe some well tested architecture already exists.
Thanks for your help
33
u/Forward-Subject-6437 Apr 01 '25
Google Anemic Domain Model, that's the trap you've fallen into. Push behavior deeper (into your models) rather than introducing another layer.
3
u/fmabr Apr 02 '25
Your controller-service-repository (aka three layers architecture) is very useful and practical for small project but not recommended for projects that will evolve (as it seems the case) and become big projects.
Book recommendations:
Answering your question about if there is something you can add between the controller and the services. Yes, you can add a facade. Then the controller asks the facade, the facade get data from all the necessary services.
As others already mentioned, your project's problem is that your business logic is in your services not in your model. One of the most fundamental concepts of objects is to encapsulates data with the logic that operates on that data. But when using controller-service-repository we tend to move the logic to the services and we end up with an anemic model.
22
u/ap3xr3dditor Apr 01 '25
"write packages, not programs". This comes from Go but it can apply in any language. I think you could go pretty far by using this methodology without disturbing your 3 layer cake.
It took me a while to put it into practice but it's pretty obvious when you think about it. A library that you import doesn't feel big because it's self contained. In this way you can move whole blocks of logic within your service layer, just packaged behind well defined packages that expose as few implementation details as possible. Now, I don't envy the devs that will need to untangle the existing logic...
5
u/com2ghz Apr 02 '25
I see this pattern also in Java applications. Where developers group their classes by type. Which actually makes no sense since it will become messy with s larger codebase.
Having packages means you are encapsulating functionality. So basically what you want is grouping classes by functionality.
account
model
order
model
4
u/[deleted] Apr 01 '25 edited Apr 01 '25
Look into service facades to group multiple services into your architecture. Be careful with circular dependencies.
3
u/AdditionDue4797 Apr 02 '25
You posted this question already, so I'll give the same answer (unedited)
First, all business logic should be delegated to the domain model entities, as services should basically just for orchestration with other services (through interfaces), as well as for persisting the aggregate root and publishing events to any subscribers...
Second, I too experienced service implementations that got too big, and that, I would say, split them into query/command services, and if that really isn't enough, then look for patterns of cohesion/coupling, from there, you would further split so that methods that remain together are highly cohesive and that coupling is minimized by these subdivided services.
My two cents, as I left my previous job before I could do the above, so the above is just what crossed my mind when reading the post.
1
u/GandolfMagicFruits Apr 01 '25
How about splitting the main service layer into two or more mini service layer services, according to domain functionality.
2
u/[deleted] Apr 01 '25
Without more context this feels like a stab in the dark but have you checked out the chain of command pattern?
2
u/elch78 Apr 02 '25
In thing that hasn't been mentioned is decoupling. I remember the same situation roughly ten years ago. The god method that did 100 things in one method. The entry method was calling method on a lot of other services. Anytime something changed you had to touch the central method. This can be solved by decoupling the communication via events. One thing happens in your domain and emits a domain event that describes what has happened. Whatever business logic is interested in this event subscribes to it and can react If you happen to work with spring boot there is a feature called application events that dates back to the early spring versions. It is very lightweight and flexible.
2
u/Olreich Apr 02 '25
This sounds like the core of your problem. Are you sure that having smaller files that duplicate parts of the domain is helping you?
If accounts actually are that complicated to deal with, having all the functionality in one place could be beneficial, even if that single file is big.
As an experiment, I’d push all the account code back into the main account file and then start looking for repeating patterns in the logic. Once you’ve identified where you’re repeating a lot of the same work, encapsulate that functionality into a helper function (in the same file for now).
You’re probably dealing with a lot of Clean Code principles gone wrong as well, which might make it difficult to see where you’re duplicating functionality because the duplication is spread across helper methods. If that’s the case, try an experiment where any function that is called from only one place is welded back into the call-site. This might make it easier to see where the logic is being duplicated.
If you still can’t find a more compressed way to write the code by extracting chunks of functionality used in many places, then you’re dealing with a situation where the business logic is complex enough that you just have to deal with it. As time marches forward, push back against requirements that will complicate the logic, and instead change existing requirements to make the logic needed across the system more consistent.
2
u/FawnDillmiballz Apr 03 '25
Are you writing unit tests for your services? This usually forces me to break my services up quite a bit
2
u/CatolicQuotes Apr 04 '25
https://herbertograca.com/2017/07/03/the-software-architecture-chronicles/
2
u/Altruistic_Address57 Apr 04 '25
Try vertical slice architecture, for the start i think this video explain better https://youtu.be/L2Wnq0ChAIA?feature=shared
2
u/thisisjustascreename Apr 01 '25
I worked with a guy who swore by a 5 layer model for anything that exposed HTTP endpoints.
Obviously the Controller takes requests and validates and sanitizes the input DTO.
Below that was the Managers which mapped DTOs to domain objects and vice versa for responses.
Then the Service layer where the business logic happens operating on domain objects.
The Provider layer then maps the domain objects to entities and the Repositories do database stuff with them.
1
u/[deleted] Apr 02 '25
Break your program into micro services by creating an ontology with the service layer. Then you can refactor your service domains to share common infrastructure and reduce the file sizes that way.
1
u/chetan_nadgouda Apr 02 '25
Have you considered micro services architecture?
I can give you 2 starting points... Microservices - Wikipedia and Microservice Architecture – Introduction, Challenges & Best Practices | GeeksforGeeks
That way, your codebase can be split into manageable sizes. The width of your services will increase (as you will be managing more number of services. that should be ok as each one is expected to be small and then self manageable).
Let me know if you need any help with this. I have done a lot of refactoring of services in the past and would be happy to elaborate on this.
1
u/[deleted] Apr 04 '25
Use some separation, separate actions iself like Commands and Queries each command/query is single action and lives in separate file. You will have much more files but not that big single files.
1
u/LeadingFarmer3923 Apr 05 '25
I’m building a tool that solves this problem. Anyone interested, feel free to DM me
1
u/traderprof Apr 06 '25
It's a common challenge. Adding another layer might help, but often the root cause isn't the number of layers but unclear boundaries between responsibilities, similar to what Domain-Driven Design (DDD) addresses with Bounded Contexts.
Before introducing a new layer, it might be worth focusing on:
CheckingAccountLinkToWithdrawServiceexist separately fromCheckingAccountLinkService? What distinct business capability does it own?Sometimes, strengthening the understanding and documentation of the existing architecture can be more effective than adding complexity with new layers. Good knowledge management about why things are structured the way they are is key to preventing the "Service layer mess" as the system grows.
1
u/agrrrcode Apr 10 '25
Your team’s experience honestly caught me off-guard at how closely it mirrors what many of us face. As projects scale, the sheer volume of business logic tends to sneak up on us fast.
What you’re describing sounds like an unforeseen surge in domain complexity—definitely a common shortcoming of the classic 3-layer architecture. We often start with clean boundaries, but Services become dumping grounds for every possible use case over time.
I’ve seen some teams successfully address this by introducing an Application Layer (like in Domain-Driven Design or Clean Architecture), where each business flow gets its own Use Case or Handler. This helps push logic out of bloated services and brings back clarity and testability.
1
u/Infide_ May 29 '25
Ask 100 programmers a question get 100 answers.
I've seen runaway service architecture. The problem is thinking in "services". Not everything is a service. Network call? Ok, that's probably a service. But I've seen people doing the equivalent of adding two numbers together in a "math service". Ridiculous.
Try thinking object oriented, as if your app was running as a game or something.
var account = new Account(args);
account.Activate();
account.Close();
account.ProcessPayment(payment)
account.Reconcile();
etc...
1
u/Equivalent_Bet6932 Jun 04 '25
Split by business domain, not by technical layers, and your problems will go away.
1
u/bluemage-loves-tacos Oct 17 '25
I don't think you have a code issue, you have an issue with your domain either being too big and needing a split, or too much granularity in how you've setup your data.
That you have accounts services that are not only specific to a *type* of account, but some are for actions on that type, tells me you've not managed to abstract aware the details into their own sub-services.
No new architecture will help when you're top level services are too granular to begin with, you'll just have the same thing in a different shape.
For the different types, look at ports and adapters to start separating the types from the generic behaviours. When you can't (because maybe one type of account is entirely different, for example a bank account vs a github account), then you have domains that need separation.
This is a gigantic code small. Stop doing that. If you don't know *where* something belongs, it doesn't belong anywhere. "Helpers" and "utils" are synonymous with too much overlap in responsibilities. Fix the problem, don't add to it with more cruft. Those "helper" functions are going to create spaghetti code.
0
u/shifty_lifty_doodah Apr 02 '25 edited Apr 02 '25
You can have a separate class for each service method or subdomain. Sometimes handy.
‘’’ LoginHandler login; DeviceService devices; PoolService pools;
void handleLogin(request) return login.login(request)
void handlePoolCreate(request) return pools.handleCreate(request)
void handleDeviceRegister() return devices.handleRegister(request) ‘’’
0
u/[deleted] Apr 01 '25
[deleted] — view deleted comment
10
u/[deleted] Apr 02 '25 edited Apr 02 '25
[removed] — view removed comment