Memory spikes killing my workersđź’€ need scaling advice

So I’ve got this Node.js SaaS that’s processing way more data than I originally planned for and my infrastructure is starting to crack…

Current setup (hosted on 1 EC2):

  • Main API container (duplicated, behind load balancer)
  • Separate worker container handling background tasks

The problem: Critical tasks are not executed fast enough + memory spikes making my worker container being restarted 6-7x per day.

What the workers handle:

  • API calls to external services (some slow/unpredictable)
  • Heavy data processing and parsing
  • Document generation
  • Analysis tasks that crunch through datasets

Some jobs are time-critical (like onboardings) and others can take hours.

What I’m considering:

  1. Managed Redis (AWS ElastiCache)
  2. Switching to SQS

What approach should I take and why? How should I scale my workers based on the workload?

Thanks :folded_hands:


Related discussions:

"Real" IPv6 Support in AWS?
Can't register an ECS service with an ALB
How does ALB (with new routing to IP-on premise) compare to balancers like f5 and others?
Network Load Balancer required port 80 to be publicly open on nodes from target group?
re:Invent, besides new AWS services, I am eager to see how AWS will apply the UI/UX to show all the services in the management console ...
Question: AWS Application Load Balancer With Multiple IIS Sites Using SSL Certificates and SNI
Redirect to Cloudfront.
Application taking too load to start - ELB healthcheck terminates the instance
AWS Load balancer with round robin and sticky sessions
Got a huge bill, trying to understand why
Elastic Load Balancing Announces Support for Redirects and Fixed Responses for Application Load Balancer (HTTP -> HTTPS redirects are here!)
Whats the correct broadcast to all containers pattern?
Invoking Lambda with ALB vs API Gateway..
Question about NLB + Security groups
ECS container ALB health check failing
Reverse LB look by Instance
How do you ELB between instances in different subnets within one AZ?
Using ECS to deploy a service running a job scheduling software like Sidekiq or celery
DNS Service Discovery in Fargate
Is it safe to have drastically different instance types in an EC2 Spot Fleet? Is ECS smart enough to balance?
How to save costs by reusing ALB across several microservices
How to identify all external entry points on AWS account for penn testing?
Ideal setup of ECS cluster with Traefik and ALB
[Announcement] Lightsail now offers a CDN to optimize your website delivery
AWS Network Load Balancer now supports IPv6
Anybody use Load Balancers with SSL / TLS certificate and have it provide a strangers SSL certificate??
aws cognito with application load balancer
EC2 IIS hosted web app says Insecure?
Securing Cloudfront/S3 static React site to ALB Communication
SSL Termination at API Gateway?
Direct Connect Public VIF to services hosted in AWS EC2
How to add load balancer from different AWS account as a value in alias A Record in Route53
TLS 1.3 with ELB and ALB: The Wait is Over!
How to expose pods on nodes in private subnets via ALB/NLB?
moving from on prem to aws, I need to restrict access to a loadbalancer for around 5000 IP adressess - what is the best practise here?
Security architecture Q: At what point do you not rely just on your central firewall?
I've just spent hours trying to sort out multiple accounts for my environments, what am I misunderstanding?
Will I Incur ALB Costs During a DoS Attack with AWS Shield Standard & WAF on ALB?
AWS adds rewrite support for ALB
App Runner alternative
Centilytics | Intelligent Cloud Management on LinkedIn: How do AWS Elastic Load Balancers work?
Inquire on Adrian Cantrill's Course
Took the exam, failed by small margin
SAP-C02 Divisive Question
Build my second project - Architected a two-tier Secure and Scalable AWS Infrastructure with Terraform!
Passed SAA-C03
Helpful website for learning about load balancers
AP-SouthEast-2 connectivity issues for ELB and EC2
NLB using HTTP Health Checks
Public static IP for SFTP traffic to ELB
Help with ELB health check
Websockets with Internal Application Load Balancer
Integrating pagerduty or any alerting services with AWS.

For background tasks it sounds like you could use AWS Batch with Fargate or EC2 Spot instances.

Rewrite your workers in Rust (probably best option) or Go (very good option). Or at least try one that’s been creating issues, and just do one of them as a POC. I think you’ll find the issues go away nearly entirely.

Its unclear what your question is.

Are you saying you need more compute resources (bigger instance/ aws batch serverless ,…) so handle memory spikes

or a better multiprocessing (so important quick tasks are performed in a timely way) eg a separate queue

…

What was the decision behind hosting it on a single ec2 ?

The memory spikes could be a number of application level issues, do they happen at a set timeframe or are they random?

Are your api calls asynchronous ? Do you have timeouts on them? All these things can cause a constraint on cpu resource.

I would look at moving your service to ECS Fargate if it’s handling tasks that are critical, a single ec2 isn’t going to give you the resilience you need.

For a starter I would recommend separating your API from your workers by placing them on separate instances. And for more resilience dockerize both and use an AWS managed service like ECS or Elastic Beanstalk (simple setup). That way a single api/worker failure won’t tear down your entire app.

And for the workers, I would (like you said) look into SQS or Bullmq to queue your worker jobs. That enables you to better manage your jobs and see what causes your memory spikes.

Try to figure out the memory spikes / crashing first before doing anything arch / design related. There could be a problem there and then you are just shifting your problem around.

will try!

You underestimated the necessary resources required to run your apps. Not uncommon really, but your reaction is. If an app is crashing 7 times a day, you can either fix the code, provision a larger node, or build better infra to handle the capacity problem. Throwing more cloudy solutions to fix a problem of your own making is what AWS is betting on.

Are you generating files in memory? 90% of the time I’ve had to fix issues with memory it’s caused by that.

So generally it seems like you’ve got a lot right! Separate API and workers is going to make scaling this an awful lot easier!

First of consider moving over to Fargate. If have the API auto scale based on CPU/memory to make sure it stays responsive. I would go with the SQS option for queueing jobs, because you can auto scale your workers based on queue length, and that way you keep background job processing responsive.

It’s not clear exactly how the background jobs work, i.e. is it always one type of job, or are there multiple different jobs? Basically I would go with one queue per job type, and have dedicated workers assigned to their own queue, but if that creates extra work, a single queue/worker combo will do fine

Longer term, depending on how the whole system works I might be tempted to convert the API to API gateway. You can use it to validate requests without code and place items direct into SQS. Other endpoints can use lambda functions. For the reports, save them S3 and then in the API return a redirect to a pre-signed S3 url so user can download easily without exposing the bucket itself. These are future suggestions though, for now just moving away from EC2 and into Fargate with SQS buffering should take you an awfully long way

OP is unclear, but it doesn’t sound like there’s a memory leak, there’s just either “bad” programming (holding entire documents in memory perhaps too long) or just lack of scaling in the design.

OP could spend a lot of time rewriting to Rust but it wouldn’t solve the underlying mathematical problem that requests/sec * avg request time * avg document size is close to the memory limit.

I do think rewriting to Rust could be helpful though, but it’s further down the list of priorities. To me, #1 is stopping the bleeding, give everything more RAM to stop dropping requests. #2 is to switch to passing documents as s3 URIs and then migrate the background workers to Lambda.

i don’t think using another cloud service is going to fix your underlying issue of a poorly designed application. if you dm me we can talk about the shift aspect of lift and shift but i’d need to see the details

Fargate is going to be more expensive and you still have to configure it to scale. While it removes the overhead of managing EC2, it does not remove the issue for OP.

node.js is a poor choice for time-critical heavy data processing

You can try to patch over that by throwing more hardware at it to buy time but if the SaaS keeps growing you’ll hit a wall eventually forcing a rewrite of at least the core logic in something more suitable

Use Lambda. You already know Node.js and can keep your web server since it probably won’t need scaling for a bit if you put the workers elsewhere.

Ideally, have the web sever put messages for workers in a queue (or multiple queues if you have different priority levels) and use Lambda to work it/them. This isn’t an idea setup, but it’s an easy step from where you are and allows workers to scale from zero to whatever you need when spikes happen.

Noted! Migrating everything to lambdas would require serious refactoring and probably I would need to open DB?

As a software engineer I’d rather spin up a second instance in minutes to hours than a week or weeks doing a risky language rewrite of my core application.

Yeah, don’t migrate everything — just the worker code that runs in the background. The Lambda can connect to the same VPC that contains the DB, so it doesn’t need to be “open” in that sense.

As a temporary measure, I’d be right there with you. But, that’s temporary. And if they were really risk adverse, it wouldn’t be a single instance architecture based on Node.js. Obviously their tolerance for risk is already quite high.