Ever thought of implementing a modern cloud architecture with Jakarta EE and MicroProfile applications but don’t know which practices to follow? This talk will highlight 10 strategies that will help you implement robust scalable cloud-ready applications!
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
10 Strategies for Developing Reliable Jakarta EE & MicroProfile Applications for the Cloud
1. 10 Strategies for Developing Reliable
Jakarta EE & MicroProfile Applications
for the Cloud
2. Before We Begin
• Intermediate knowledge of:
• Jakarta /Java EE
• MicroProfile
• Distributed Concepts & Clustering
• Questions at the end
3. Fabio Turizo
• IT Professional with over 10(y) of experience
• Oracle Certified Professional Java SE 8
• Oracle Certified Master Java EE 6
• Software Architecture Enthusiast
• Toptal Network Freelancer
Senior Services Engineer
fabio.turizo@payara.fish
4. Payara Services Limited
• Payara Platform - Commercial Support
• OpenJDK Support via Azul Systems
Partnership
• Eclipse MicroProfile Founding Member
• EE4J Project Board Members
5. Jakarta EE
• Donated to the Eclipse Foundation
• Governed by the EE4J Project
• Open sourced TCKs
• Eclipse GlassFish 5.1 (No RI)
6. Eclipse MicroProfile
• Initially conceived for Microservices
• Cloud-Oriented
• Like Java EE, but less restrictions
• Also part of the Eclipse Foundation
http://microprofile.io/
7. Reliable Clustering
• Main Issue: Distribution App Development
• Clusters help to:
• Optimize resources
• High availability and reliability
• Divide the workload and simplify coding
8. Reliable Clustering
• Can Jakarta/Java EE help with reliable
clustering?
• YES !
• … However, a set of strategies are needed
9. Jakarta EE - Distribution
• Main challenges:
• No standard APIs
• Clustering is too specific !
• Specific Demands for Microservices
• Can Jakarta EE 9 (+) bring changes?
10. Jakarta EE - Distribution
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns=http://xmlns.jcp.org/xml/ns/javaee
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
…>
<description>My Web application</description>
<distributable></distributable>
</web-app>
11. Filling the Gaps
• Each provider must:
• Supply clustering mechanisms
• Design and promote distribution features
• Modernize and enhance their userbase productivity
12. No Silver Bullets
• No standards? No problem!
• 10 recommended strategies:
• Quality attributes for new applications
• But they aren’t silver bullets
• Payara Platform can help (!)
13. Strategy #1 - Statelessness
• How should I handle state on my application ?
• Answer: Don’t
• Focus on stateless components!
14. Strategy #1 - Statelessness
• Less memory in the middleware
• Easy to coordinate, less code
• CDI: @RequestScoped
• EJB: @Stateless
15. Strategy #1 - Statelessness
@Path("/calculate")
@RequestScoped
public class CalculatorResource {
@Inject Instance<CalculatorService> calculatorService;
@Inject Principal currentPrincipal;
@POST
@Path("/")
public void executeCalculation(CalculationRequestData data){
if(isCalculationPossible(currentPrincipal.getName())){
calculatorService.get().execute(data, currentPrincipal.getName());
}
}
}
16. Strategy #2 - Singletons
• If state’s no good, singletons aren’t?
• No, singletons are recommended !
• Avoid over coordination of resources
• … Except in some cases
17. Strategy #2 - Singleton
• Make a singleton when:
• Concurrent modifications aren’t needed
• A single aspect of an app requires coordination
• CDI: @ApplicationScoped
• EJB: @Singleton
19. Strategy #3 – “True” Singleton
• What about distributed environments ?
• Prevent multiple Instances across JVMs
• Avoid data redundancy and inconsistencies
• No standard CDI/EJB for a “true Singleton”
20. Strategy #3 – “True” Singleton
• Payara Platform brings @Clustered
• Coordinates a single instance cluster-wide
• Other Platforms have similar solutions
• Caching can help (more later)
21. Strategy #3 – “True” Singleton
@ApplicationScoped
@Clustered(callPostConstructOnAttach = false)
public class SessionRatingService implements Serializable{
@PersistenceContext(unitName = "Vote")
EntityManager em;
@PostConstruct
public void longInitializationProcess(){
…
}
}
22. Strategy #4 - Caching
• Statelessness is Good…
• … But there is always need to handle state
• Caching can handle this and:
• Prevent data re-processing
• Optimize resource management
23. Strategy #4 - Caching
• No standard Java / Jakarta EE APIs
• Excellent Solutions: EhCache, Spring Cache
• JCache almost made it (!)
• Hard to optimize homebrew solutions
24. Strategy #4 – Caching
@ApplicationScoped
public class SessionRatingService {
Map<Integer, SessionRating> cachedRatings;
public SessionRating getRating(Integer id) {
cachedRatings.putIfAbsent(id, retrieveSessionFromDB(id));
return cachedRatings.get(id);
}
}
25. Strategy #4 - Caching
• However, there are challenges:
• Coordinate data living in a cluster environment
• Invalidating data on demand
• Failover and data migration
26. Strategy #4 - Caching
• Distributed Caching in Payara Platform:
• JCache Support (javax.cache:cache-api)
• Proprietary APIs as well
• JCache not yet part of Jakarta EE
• Hazelcast as caching engine
27. Strategy #4 – Caching
@ApplicationScoped
public class SessionRatingService {
@Inject
Cache<Integer, SessionRating> cachedRatings;
public SessionRating getRating(Integer id) {
cachedRatings.putIfAbsent(id, retrieveSessionFromDB(id));
return cachedRatings.get(id);
}
}
28. Strategy #4 – Caching
@ApplicationScoped
@CacheDefaults(cacheName = “ratings")
public class SessionRatingService {
@CacheResult
public SessionRating getRating(@CacheKey Integer id) {
return retrieveSessionFromDB(id);
}
}
29. Strategy #5 CDI > EJB
• What component model should I use?
• CDI Modern, Flexible, Extensive
• EJB Resilient but obsolete
• Jakarta EE and MicroProfile are based on CDI !
30. Strategy #5 – CDI > EJB
@Singleton
public class SessionService {
@EJB
SpeakerDomainChecker domainChecker;
}
@ApplicationScoped
public class SessionService {
@Inject
SpeakerDomainChecker domainChecker;
}
31. Strategy #5 – CDI > EJB
• However, when using EJB timers:
• No CDI-equivalent for them yet
• For EJB Timers, keep in mind:
• Multiple instances can fire in a cluster
• Avoid persistent timers
33. Strategy #6 – JPA Caching
• Persisting Data needs to be cached too
• In the Jakarta EE World, JPA is key to this
• However, no standard APIs as well
34. Strategy #6 – JPA Caching
• JPA has 2 levels of caching
• L2 Cache offers fast data retrieval
• But, each vendor does it differently
• Payara Platform relies on EclipseLink
• And through Hazelcast Cache Coordination
38. Strategy #7 – Configuration
• Where is my app configuration located?
• How can I retrieve it?
• It should be easy and user-friendly
39. Strategy #7 – Configuration
• No Jakarta EE standard, sadly
• MicroProfile Configuration to the rescue!
• Highly extensible with sensible defaults API
40. Strategy #7 - Configuration
• MicroProfile Configuration allows:
• Rely on centralized data sources
• Sensible default values, to prevent inconsistencies
• @Inject values where needed
• … or programmatically look for them, too.
43. Strategy #8 – Fault Tolerance
• What should I do when a node fails ?
• Or a database is not reachable ?
• Or an external service is not working ?
• Or the system is at critical state ?
• Your app code needs to adapt
• MicroProfile Fault Tolerance to the rescue !
44. Strategy #8 – Fault Tolerance
• MicroProfile Fault Tolerance:
• Is a set of patterns that guide business logic flow
• Separates execution logic from execution itself
• Been designed on top of CDI
• Via vanilla interceptor annotations
49. Strategy #9 – Stateless Security
• When using stateless services how can I?
• Appropriately secure access to all resources
• Make sure that endpoints are available only to the right people
• Propagate all secured information to other services
50. Strategy #9 – Stateless Security
• Then, a good solution needs to make sure that:
• Each request is validated separately in isolation
• User data is idempotent and portable
• Each node in the cluster has the right tools to validate
information
• Consider: JSON Web Tokens (JWT)
51. Strategy #9 – Stateless Security
• JSON Web Tokens:
• Token-based Authentication/Authorization
• OpenID Connect compatible
• Based on the RFC7519 standard
• MicroProfile JWT Propagation to the rescue!
56. Strategy #9 – Stateless Security
@Path("/rating")
@RequestScoped
@RolesAllowed("CAN_VOTE")
public class SessionVoteResource {
@Inject
Principal jwtPrincipal;
@POST
public Response rate(SessionRating rating) {
Attendee currentUser = attendeeService.getByEmail(jwtPrincipal.getName())
return Response.ok(ratingService.addRating(rating, currentUser)).build();
}
}
RoleAccess&
PrincipalInjection
57. Strategy #9 – Stateless Security
@Inject
JsonWebToken token;
@GET
@Path("/summary/{session}")
public Response getSummaryForSession(@PathParam("session") Integer sessionId) {
if(!token.getGroups().contains(“ADMIN”)){
throw new WebApplicationException("Only admins can execute this operation", 403);
}
List<SessionRating> results = ratingService.getRatingsFor(sessionId);
return Response.ok().entity(createSummary(results)).build();
}
TokenInjection
58. Strategy #10 – Metrics
• Daily, can I:
• See how good / bad is the state of my system ?
• Optimize my environment based on real-time data
• Analyze the data generated by applications
• MicroProfile Metrics to the rescue !
59. Strategy #10 – Metrics
• Cloud-ready standard Metrics
• Based on the Prometheus format
• No bootstrapping code needed
• 3 scopes: base, vendor, application
• Each metric has metadata (tags)
60. Strategy #10 – Metrics
• Current Types:
• Gauge
• Counter
• Meter
• Histogram
• Timer
Prometheus +Grafana
65. More Resources
• Jakarta EE: https://jakarta.ee/
• Eclipse MicroProfile: https://microprofile.io/
• Payara Platform Documentation: https://docs.payara.fish/
66. Know about Payara Reef ?
• Have any local events ?
• Or JUG gatherings ?
• Payara can help with those !
• More information:
• https://www.payara.fish/about/reef-community-growth-program/
67. Many thanks!
Not using Payara yet?
Download Payara Server/Micro from:
https://payara.fish/downloads
Get Started
https://payara.fish/get-started/