惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Cisco Talos Blog
Cisco Talos Blog
T
Threat Research - Cisco Blogs
P
Privacy International News Feed
S
Schneier on Security
P
Privacy & Cybersecurity Law Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
云风的 BLOG
云风的 BLOG
P
Proofpoint News Feed
Scott Helme
Scott Helme
人人都是产品经理
人人都是产品经理
G
GRAHAM CLULEY
O
OpenAI News
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
PCI Perspectives
PCI Perspectives
GbyAI
GbyAI
宝玉的分享
宝玉的分享
Y
Y Combinator Blog
T
Troy Hunt's Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
C
CXSECURITY Database RSS Feed - CXSecurity.com
腾讯CDC
C
Check Point Blog
Spread Privacy
Spread Privacy
L
LINUX DO - 最新话题
Recent Announcements
Recent Announcements
大猫的无限游戏
大猫的无限游戏
P
Palo Alto Networks Blog
Hacker News: Ask HN
Hacker News: Ask HN
M
MIT News - Artificial intelligence
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
The Hacker News
The Hacker News
H
Hacker News: Front Page
Microsoft Azure Blog
Microsoft Azure Blog
I
InfoQ
T
Tor Project blog
Martin Fowler
Martin Fowler
博客园 - 叶小钗
罗磊的独立博客
C
Cyber Attacks, Cyber Crime and Cyber Security
H
Heimdal Security Blog
V
Vulnerabilities – Threatpost
Simon Willison's Weblog
Simon Willison's Weblog
Latest news
Latest news
WordPress大学
WordPress大学
G
Google Developers Blog
N
Netflix TechBlog - Medium
S
Security Affairs
S
Secure Thoughts
Know Your Adversary
Know Your Adversary

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Java at the Edge: Managing Memory in Serverless and Modern APIs
JillThornhil · 2026-05-12 · via DEV Community

Modern APIs are trending more and more away from monolith architecture towards smaller, independent services. 

Serverless applications are currently at the cutting edge of this trend. Cloud providers now offer hosting for tiny, independent functions that run within the host’s own managed environment. Clients don’t need to manage the underlying infrastructure or worry about considerations such as scaling or security. Examples include AWS Lambda, Azure Functions and Google Cloud Functions.

Since these services are charged in direct proportion to the resources used, it’s highly important to make sure resources aren’t wasted. In this article, we’ll look at Java serverless memory optimization to find out how best to keep our running costs to a minimum.

Key Concepts Behind Serverless Applications

Serverless applications are functions that run in the host’s infrastructure in response to a trigger. Instead of paying for an environment, the client pays for actual usage. For the right type of application, this results in lower cloud costs, and a reduced requirement for in-house skills. Deployment is fast, and scaling is simple.

They’re ideal for small, on-request tasks, such as uploading a file to the server or responding to a click on a website. They’re designed for short-running tasks, and most cloud providers place a limit of 10 to 15 minutes run time per request. State is not predictably maintained between requests. They therefore don’t work for long-running batch jobs, complex operations or stateful tasks. These small functions are often known as lambdas.

To optimize serverless functions, we need to understand a little of how they’re managed within the host’s environment. The first time a function is triggered, the host must fire up a new JVM. The function itself may have start-up tasks, such as loading reference information. This is known as a cold start, and may take 3 to 10 seconds. When the task completes, the function remains loaded for a short time in its current state. If it’s triggered again during this time, the host will simply re-use this instance, resulting in a warm start, improving response time drastically.

Cold starts can severely affect performance for intermittently-used functions, but they don’t happen often on functions with a high traffic volume. Various techniques have been developed to mitigate the cold start problem, such as AWS SnapStart.

We have no way of knowing when we write the function whether it will be triggered by a cold start or a warm start, so we need to beware of data contamination by variables that were carried over with a warm start. It’s perfectly possible, for example, for memory leaks to persist over time and cause OutOfMemory errors.

How Are Serverless Charges Calculated?

Charges are directly proportional to the amount of memory configured for the function and the total time it runs during the accounting period. Cold starts are included in the run time. Two ways to reduce charges, therefore, are to reduce memory usage, and to reduce the run time for each trigger.

So, reducing memory is always good, right? Wrong! Sometimes reducing memory can actually increase charges:

  • Some tasks may run faster if they have more memory available, thereby reducing the run time.

  • Cloud providers generally allocate other resources, such as CPU time and network bandwidth, in proportion to the configured memory rather than allowing them to be configured (and charged) separately.  Again, extra CPU and bandwidth may result in decreased run time.

It’s actually really difficult to calculate the optimal memory size to find the sweet spot between reduced memory charges, and increased run time charges. 

Java serverless memory optimization usually requires a repeated cycle of configuration, analyzing diagnostics and fine tuning for best results.

Java Serverless Memory Optimization: Finding the Sweet Spot

There are four things we need to do to make sure our memory configuration is optimized to keep cloud costs to the minimum:

  • Minimize memory footprint;

  • Configure accurately;

  • Test thoroughly;

  • Monitor carefully and adjust as needed.

We’ll look at each of these in turn.

1. Reducing Java Memory Footprint for Faster Serverless Performance

Any excess memory used by the application means we’re paying cloud costs for something we don’t need. Yes, every kilobyte does count! Here are some areas to look at.

  • Eliminate memory leaks.  See this article to learn how to check whether memory is leaking, and diagnose and fix the problem: Java Memory Leaks: The Definitive Guide.

  • Use memory-saving coding techniques. An incredible amount of heap memory in most Java applications is, in fact, wasted by poor coding. See this article: How Much Memory Is My Application Wasting?

  • Reduce memory-heavy dependencies. Third party libraries are often very resource-hungry. Opt for lightweight lambda-friendly frameworks such as  Micronaut or Quarkus.

  • Don’t write complex, multi-function lambdas. A lambda should be simple and deal with a single task.

  • Consider using GraalVM. This allows us to pre-compile the application, which results in a tiny footprint and much faster execution.

2. Setting Optimal Memory and CPU Allocation for Java Functions

There are several areas to look at when configuring serverless applications.

  • Configuring the JVM:

    • The heap size must be configured accurately using the -Xms (initial heap size) and -Xmx (maximum heap size) command line arguments. For lambdas, the initial and maximum size should be set to the same, as we don’t want to waste precious run time (and money!) in resizing the heap on a cold start. If heap settings are set too low, the GC will become inefficient, and we risk OutOfMemory errors. If they’re set too high, the extra memory allocated is simply wasted and will incur costs. Alternatively, it may be a good idea to use the -MaxRAMPercentage to scale the heap memory according to the available RAM. Lambdas usually run in a container, with cgroup configured according to the lambda settings. Setting the heap as a percentage of available RAM will avoid having to reconfigure the JVM as well as the lambda.
    • Choose and configure the most suitable garbage collection algorithm. Since memory sizes less than 3-4GB are unlikely to be allocated more than one vCPU, serial GC works best for these tasks (-XX:+UseSerialGC). For memory sizes larger than this, G1GC is usually the best choice (-XX:+UseG1GC).
    • Enable GC logging. This uses very little overhead, and it’s one of the most valuable troubleshooting artifacts. Since persistent storage is not easily available, the logs should be sent to stdout, which is preserved in the cloud logs. Use tagging so the GC logs can be easily filtered out from these logs. Typically, the argument is -Xlog:gc*:stdout:time,level,tags.
  • Configuring the lambda: Useful options include:

    • Set the required memory size: remember, the heap only accounts for about 70% of the total JVM memory requirements;
    • Set a realistic timeout. If, for some reason, the application hangs, we don’t want to pay high costs for running time;
    • Diagnostic requirements. This is essential for fine-tuning, monitoring, and raising alerts.

Since it’s so difficult to predict optimum offsets between memory and CPU requirements, the best way to approach this is to configure, test, monitor and compare performance with different settings.

3. How to Benchmark and Test Java Serverless Memory Usage

Lambdas must be thoroughly tested, both for functionality and for performance. Cloud providers usually offer useful testing environments, including:

  • Downloadable local emulators. These are perfect for unit and functional testing. 

  • Cloud-based staging/test environments. These are useful for load testing, performance monitoring, and testing alongside other services. 

  • Beta testing in the live environment. We can restrict the initial release to a trusted user base to make sure everything is working as it should.

4. Observability for Java Serverless: Memory, GC, and Performance Metrics

Monitoring and diagnostics play a key role in Java serverless memory optimization.

However, it’s not usually possible to use standard diagnostic tools in a serverless environment, so we have to adapt our strategy.

Cloud providers usually supply their own set of monitoring tools, allowing us to obtain information on:

  • Memory usage;

  • Execution duration;

  • Cold starts;

  • Downstream latency;

  • Retry behavior.

This lets us adapt our configuration to achieve peak efficiency, and also lets us proactively detect any developing problems.

For more diagnostics, we can enable Java Flight Recorder in the JVM and use Java Mission Control to interpret results. This is especially useful in stage testing and beta testing.

If JMX is enabled during testing on a local emulator, we can link to the running application with profiling tools. This lets us observe behavior, take heap dumps, and carry out other diagnostic tasks. During early testing, it’s a good idea to submit a heap dump to a tool such as HeapHero, which not only lets us explore memory usage but also gives a full analysis of wasted memory.

In both live and test environments, GC logs should be regularly monitored using a tool such as GCeasy. These logs let us detect problems before they affect live performance. Memory leaks, GC overload and key performance indicators can all be picked up from the logs in time to prevent production issues.

Conclusion

Java serverless memory optimization is tricky. Achieving the best performance usually requires fine-tuning configurations while monitoring regularly. There is always a trade-off between keeping memory low and reducing run time by adding more resources. This is difficult to estimate and is best achieved by carefully monitoring and adjusting settings.

We can keep the application’s memory footprint low by eliminating memory leaks and waste, keeping functions small, and using lightweight frameworks. It’s also worth considering creating pre-compiled object code using facilities such as GraalVM.

Serverless applications are only cost-effective if resources are kept to a minimum, so it’s worth putting effort into achieving the best results.