SlideShare a Scribd company logo
10 Strategies for Developing Reliable
Jakarta EE & MicroProfile Applications
for the Cloud
Before We Begin
• Intermediate knowledge of:
• Jakarta /Java EE
• MicroProfile
• Distributed Concepts & Clustering
• Questions at the end
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
Payara Services Limited
• Payara Platform - Commercial Support
• OpenJDK Support via Azul Systems
Partnership
• Eclipse MicroProfile Founding Member
• EE4J Project Board Members
Jakarta EE
• Donated to the Eclipse Foundation
• Governed by the EE4J Project
• Open sourced TCKs
• Eclipse GlassFish 5.1 (No RI)
Eclipse MicroProfile
• Initially conceived for Microservices
• Cloud-Oriented
• Like Java EE, but less restrictions
• Also part of the Eclipse Foundation
http://microprofile.io/
Reliable Clustering
• Main Issue: Distribution App Development
• Clusters help to:
• Optimize resources
• High availability and reliability
• Divide the workload and simplify coding
Reliable Clustering
• Can Jakarta/Java EE help with reliable
clustering?
• YES !
• … However, a set of strategies are needed
Jakarta EE - Distribution
• Main challenges:
• No standard APIs
• Clustering is too specific !
• Specific Demands for Microservices
• Can Jakarta EE 9 (+) bring changes?
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>
Filling the Gaps
• Each provider must:
• Supply clustering mechanisms
• Design and promote distribution features
• Modernize and enhance their userbase productivity
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 (!)
Strategy #1 - Statelessness
• How should I handle state on my application ?
• Answer: Don’t
• Focus on stateless components!
Strategy #1 - Statelessness
• Less memory in the middleware
• Easy to coordinate, less code
• CDI: @RequestScoped
• EJB: @Stateless
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());
}
}
}
Strategy #2 - Singletons
• If state’s no good, singletons aren’t?
• No, singletons are recommended !
• Avoid over coordination of resources
• … Except in some cases
Strategy #2 - Singleton
• Make a singleton when:
• Concurrent modifications aren’t needed
• A single aspect of an app requires coordination
• CDI: @ApplicationScoped
• EJB: @Singleton
Strategy #2 - Singleton
@ApplicationScoped
public class TokenGenerator {
@Inject
@ConfigProperty(name = "mp.jwt.verify.issuer")
private String issuer;
public String generateFor(Attendee attendee){
try{
SignedJWT signedJWT = createSignedJWT(issuer);
return signedJWT.sign(new RSASSASigner(readPrivateKey("/META-INF/keys/privateKey.pem"))).serialize();
} catch(Exception ex){
throw new RuntimeException("Failed generating JWT", ex);
}
}
}
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”
Strategy #3 – “True” Singleton
• Payara Platform brings @Clustered
• Coordinates a single instance cluster-wide
• Other Platforms have similar solutions
• Caching can help (more later)
Strategy #3 – “True” Singleton
@ApplicationScoped
@Clustered(callPostConstructOnAttach = false)
public class SessionRatingService implements Serializable{
@PersistenceContext(unitName = "Vote")
EntityManager em;
@PostConstruct
public void longInitializationProcess(){
…
}
}
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
Strategy #4 - Caching
• No standard Java / Jakarta EE APIs
• Excellent Solutions: EhCache, Spring Cache
• JCache almost made it (!)
• Hard to optimize homebrew solutions
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);
}
}
Strategy #4 - Caching
• However, there are challenges:
• Coordinate data living in a cluster environment
• Invalidating data on demand
• Failover and data migration
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
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);
}
}
Strategy #4 – Caching
@ApplicationScoped
@CacheDefaults(cacheName = “ratings")
public class SessionRatingService {
@CacheResult
public SessionRating getRating(@CacheKey Integer id) {
return retrieveSessionFromDB(id);
}
}
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 !
Strategy #5 – CDI > EJB
@Singleton
public class SessionService {
@EJB
SpeakerDomainChecker domainChecker;
}
@ApplicationScoped
public class SessionService {
@Inject
SpeakerDomainChecker domainChecker;
}
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
Strategy #5 – CDI > EJB
@Stateless
public class AnalyticsDataTimer {
@Schedule(hour = "23", minute = "55", persistent = false)
public void gatherScreenBehaviorData(){
try {
List<ScreenBehaviorRecord> results = analyticsService.getViewBehaviorData(LocalDate.now());
appBehaviorService.persistScreenBehavior(results);
} catch (IOException ex) {
LOG.error("Error while gathering analytics data", ex);
}
}
}
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
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
Strategy #6 – JPA Caching
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2" xmlns="http://xmlns.jcp.org/xml/ns/persistence" …>
<persistence-unit name="Vote" transaction-type="JTA">
<jta-data-source>jdbc/voteDS</jta-data-source>
<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
Strategy #6 – JPA Caching
@Entity
@Cacheable
@NamedQuery(name = "SessionRating.getForSession",
query = "select sr from SessionRating sr where sr.sessionId = :id order by sr.rating")
public class SessionRating implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private Integer sessionId;
private Integer rating;
}
Strategy #6 – JPA Caching
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2" xmlns=“http://xmlns.jcp.org/xml/ns/persistence” ..,>
<persistence-unit name="Vote" transaction-type="JTA">
<jta-data-source>jdbc/voteDS</jta-data-source>
<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
<properties>
<property name="eclipselink.cache.coordination.protocol“
value="fish.payara.persistence.eclipselink.cache.coordination.HazelcastPublishingTransportManager"/>
<property name="eclipselink.cache.coordination.channel" value=“voteDSChannel"/>
</properties>
</persistence-unit>
</persistence>
Strategy #7 – Configuration
• Where is my app configuration located?
• How can I retrieve it?
• It should be easy and user-friendly
Strategy #7 – Configuration
• No Jakarta EE standard, sadly
• MicroProfile Configuration to the rescue!
• Highly extensible with sensible defaults API
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.
Strategy #7 - Configuration
@Inject
@ConfigProperty(name="demo.conference.speaker.venues", defaultValue = "Ocarina")
private List<String> venues;
Config configuration = ConfigProvider.getConfig();
String defaultVenue = configuration.getValue(“demo.conference.speaker.venues”, String.class);
StaticConfigurationbyDI
ProgrammaticLookup
Strategy #7 - Configuration
#Dockerfile (microservice-speaker)
FROM payara/micro
COPY microservice-speaker.war ${DEPLOY_DIR}
#CommandLine
docker run –p 8080:8080 –e “demo.conference.speaker.venues=OCARINA,ALFAJOR”
fturizo/microservice-speaker –clusterName speaker
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 !
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
Strategy #8 – Fault Tolerance
• Existing Tolerance Patterns
• Retry
• Fallback
• Bulkhead
• Circuit Breaker
• Timeout
• Asynchronous (overlapping with EJB’s)
Strategy #8 – Fault Tolerance
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Retry(maxRetries = 5, delay = 30, delayUnit = ChronoUnit.SECONDS)
public Response register(Attendee attendee){
Attendee result = attendeeService.create(attendee);
return Response.created(URI.create("/attendee/" + result.getId()))
.entity(result).build();
}
RetryExample
Strategy #8 – Fault Tolerance
@Retry(maxRetries = 3, delay = 1, delayUnit = ChronoUnit.MINUTES)
@Fallback(fallbackMethod = "cacheRating")
public SessionRating addRating(SessionRating rating, Attendee attendee) {
rating = rating.with(attendee,
dataService.getSessionSummary(rating.getSessionId()));
em.persist(rating);
em.flush();
return rating;
} FallbackExample
Strategy #8 – Fault Tolerance
public SessionRating cacheRating(SessionRating rating, Attendee attendee){
rating = rating.with(attendee);
cachedRatings.putIfAbsent(rating.getSessionId(), new ArrayList<>());
cachedRatings.get(rating.getSessionId()).add(rating);
return rating;
}
Retry-FallbackMethodExample
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
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)
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!
Strategy #9 – Stateless Security
JWTExample
Strategy #9 – Stateless Security
curl -X POST http://lb.payara.fish/microservice-vote/rating/
-H 'Content-Type: application/json’
–H ‘Authorization: Bearer
eyJraWQiOiJcL3ByaXZhdGVLZXkucGVtIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJhdWQiOiJhdHRlbmRlZXMiLCJzdWIiOiJBbGZyZWRvIE1vbGluYSIsInV
wbiI6ImFsZnJlZG8ubW9saW5hQGdtYWlsLmNvbSIsImF1dGhfdGltZSI6MTU1NDE2NjM2MiwiaXNzIjoiZGVtb3MucGF5YXJhLmZpc2giLCJncm91cHMiOlsiQ0FOX1ZPV
EUiXSwiZXhwIjoxNTU0MTc2MzYyLCJpYXQiOjE1NTQxNjYzNjIsImp0aSI6ImF0dC0xIn0.qXO0fbblsjusbo58DI0yDPua3uw1YnKR6VkIQOKP_SCACb5whpAEjD6iBVv
RQ7UUvoLiLIFisoGEoa_K17VjiyyDdDk6QGgI1tvYUMnaoQ’
-d '{"session-id" : 1, "rating" : 5}'
Strategy #9 – Stateless Security
@ApplicationPath("/")
@ApplicationScoped
@LoginConfig(authMethod = "MP-JWT")
@DeclareRoles(“ADMIN”, “CAN_VOTE”)
public class VoteApplication extends Application{
}
LoginDefinition
Strategy #9 – Stateless Security
#microprofile-config.properties
#MP JWT Settings
mp.jwt.verify.publickey.location = /META-INF/keys/publicKey.pem
mp.jwt.verify.issuer = demos.payara.fish
JWTConfiguration
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
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
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 !
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)
Strategy #10 – Metrics
• Current Types:
• Gauge
• Counter
• Meter
• Histogram
• Timer
Prometheus +Grafana
Strategy #10 – Metrics
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Metered(name = "session.creation.tries", absolute = true)
public Response create(Session session) {
session = sessionService.register(session);
return Response.created(URI.create("/" +session.getId()))
.entity(session).build();
}
MeteredExample
Strategy #10 – Metrics
@Inject
@Metric(name = "session.spaces", absolute = false)
Counter sessionSpaces;
…
@PostConstruct
public void init(){
sessionSpaces.inc(5);
}
CounterExample
Strategy #10 – Metrics
<config>
<vendor>
<metadata>
<name>system.cpu.load</name>
<mbean>java.lang:type=OperatingSystem/SystemCpuLoad</mbean>
<type>gauge</type>
<unit>none</unit>
<displayName>System CPU Load</displayName>
<description>Recent CPU usage for the whole system.</description>
</metadata>
</vendor>
</config>
CustomVendorMetrics-Payara
Q & A
More Resources
• Jakarta EE: https://jakarta.ee/
• Eclipse MicroProfile: https://microprofile.io/
• Payara Platform Documentation: https://docs.payara.fish/
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/
Many thanks!
Not using Payara yet?
Download Payara Server/Micro from:
https://payara.fish/downloads
Get Started
https://payara.fish/get-started/

More Related Content

PPTX
Fun with Kubernetes and Payara Micro 5
PDF
Monitor Micro-service with MicroProfile metrics
PDF
Effective cloud-ready apps with MicroProfile
PDF
Secure JAX-RS
PDF
Oracle WebLogic 12c New Multitenancy features
PDF
Oracle SOA suite and Coherence dehydration
PDF
Gradual migration to MicroProfile
PPTX
WebLogic and GraalVM
Fun with Kubernetes and Payara Micro 5
Monitor Micro-service with MicroProfile metrics
Effective cloud-ready apps with MicroProfile
Secure JAX-RS
Oracle WebLogic 12c New Multitenancy features
Oracle SOA suite and Coherence dehydration
Gradual migration to MicroProfile
WebLogic and GraalVM

What's hot (19)

PDF
Oracle virtualbox basic to rac attack
PDF
Pro2516 10 things about oracle and k8s.pptx-final
PPT
WebLogic 12c - OMF Canberra June 2014
PPTX
Hands-on Performance Tuning Lab - Devoxx Poland
PPTX
Monitoring Oracle SOA Suite
PDF
MySQL as a Document Store
PDF
01 upgrade to my sql8
PDF
MySQL Manchester TT - 5.7 Whats new
PDF
5 steps to take setting up a streamlined container pipeline
PDF
MySQL Intro JSON NoSQL
PPTX
Bridging Oracle Database and Hadoop by Alex Gorbachev, Pythian from Oracle Op...
PDF
5 Keys to Oracle GoldenGate Implemenations
PDF
Oracle Enterprise Manager 12c: updates and upgrades.
PDF
MySQL NDB Cluster 8.0
PDF
Advanced queries on the Infinispan Data Grid
PDF
MySQL Enterprise Edition Overview
PDF
Oracle Enterprise Manager for MySQL
PPTX
Oracle GoldenGate on Docker
PDF
MySQL Tech Tour 2015 - Alt Intro
Oracle virtualbox basic to rac attack
Pro2516 10 things about oracle and k8s.pptx-final
WebLogic 12c - OMF Canberra June 2014
Hands-on Performance Tuning Lab - Devoxx Poland
Monitoring Oracle SOA Suite
MySQL as a Document Store
01 upgrade to my sql8
MySQL Manchester TT - 5.7 Whats new
5 steps to take setting up a streamlined container pipeline
MySQL Intro JSON NoSQL
Bridging Oracle Database and Hadoop by Alex Gorbachev, Pythian from Oracle Op...
5 Keys to Oracle GoldenGate Implemenations
Oracle Enterprise Manager 12c: updates and upgrades.
MySQL NDB Cluster 8.0
Advanced queries on the Infinispan Data Grid
MySQL Enterprise Edition Overview
Oracle Enterprise Manager for MySQL
Oracle GoldenGate on Docker
MySQL Tech Tour 2015 - Alt Intro
Ad

Similar to 10 Strategies for Developing Reliable Jakarta EE & MicroProfile Applications for the Cloud (20)

PDF
High Performance Java EE with JCache and CDI
PDF
Spring One 2 GX 2014 - CACHING WITH SPRING: ADVANCED TOPICS AND BEST PRACTICES
PPTX
Top 50 java ee 7 best practices [con5669]
PDF
Java2 days 5_agile_steps_to_cloud-ready_apps
PPTX
Supercharge JavaEE applications using JCache
PPT
Cluster your application using CDI and JCache - Jonathan Gallimore
PPTX
From cache to in-memory data grid. Introduction to Hazelcast.
PDF
Migrating traditional Java EE Applications to mobile
PPTX
High performance java ee with j cache and cdi
PDF
310-053 Exam-Sun Certified Enterprise Architect, Java, EE5 Upgrade
PPT
Clustered Architecture Patterns Delivering Scalability And Availability
PDF
Caching for Microservices Architectures: Session II - Caching Patterns
PDF
Elastic and Cloud-ready Applications with Payara Micro
PDF
Elastic and Cloud-ready Applications with Payara Micro
PDF
Elastic and Cloud-ready Applications with Payara Micro
PPTX
Caching In Java- Best Practises and Pitfalls
PPTX
JavaPerformanceChapter_1
PDF
Simple Pure Java
PPT
13 caching latest
PDF
Strategies for Developing Web Applications with Java (1).pdf
High Performance Java EE with JCache and CDI
Spring One 2 GX 2014 - CACHING WITH SPRING: ADVANCED TOPICS AND BEST PRACTICES
Top 50 java ee 7 best practices [con5669]
Java2 days 5_agile_steps_to_cloud-ready_apps
Supercharge JavaEE applications using JCache
Cluster your application using CDI and JCache - Jonathan Gallimore
From cache to in-memory data grid. Introduction to Hazelcast.
Migrating traditional Java EE Applications to mobile
High performance java ee with j cache and cdi
310-053 Exam-Sun Certified Enterprise Architect, Java, EE5 Upgrade
Clustered Architecture Patterns Delivering Scalability And Availability
Caching for Microservices Architectures: Session II - Caching Patterns
Elastic and Cloud-ready Applications with Payara Micro
Elastic and Cloud-ready Applications with Payara Micro
Elastic and Cloud-ready Applications with Payara Micro
Caching In Java- Best Practises and Pitfalls
JavaPerformanceChapter_1
Simple Pure Java
13 caching latest
Strategies for Developing Web Applications with Java (1).pdf
Ad

More from Payara (20)

PPTX
Easy Java Integration Testing with Testcontainers​
PPTX
Payara Cloud - Cloud Native Jakarta EE.pptx
PPTX
Jakarta Concurrency: Present and Future
PPTX
GlassFish Migration Webinar 2022 Current version.pptx
PDF
Securing Microservices with MicroProfile and Auth0v2
PDF
Reactive features of MicroProfile you need to learn
PDF
A step-by-step guide from traditional Java EE to reactive microservice design
PDF
Transactions in Microservices
PDF
What's new in Jakarta EE and Eclipse GlassFish (May 2019)
PDF
Previewing Payara Platform 5.192
PDF
Gradual Migration to MicroProfile
PDF
Monitor Microservices with MicroProfile Metrics
PDF
Java2 days -_be_reactive_and_micro_with_a_microprofile_stack
PDF
Rapid development tools for java ee 8 and micro profile [GIDS]
PDF
Ondrej mihalyi be reactive and micro with a micro profile stack
PDF
Bed con Quest for JavaEE
PPTX
Payara Micro from Raspberry Pi to Cloud
PPTX
Microprofile and EE4J update
PDF
Devoxx Easily scale enterprise applications using distributed data grids
PPTX
Demystifying microservices for JavaEE developers by Steve Millidge.
Easy Java Integration Testing with Testcontainers​
Payara Cloud - Cloud Native Jakarta EE.pptx
Jakarta Concurrency: Present and Future
GlassFish Migration Webinar 2022 Current version.pptx
Securing Microservices with MicroProfile and Auth0v2
Reactive features of MicroProfile you need to learn
A step-by-step guide from traditional Java EE to reactive microservice design
Transactions in Microservices
What's new in Jakarta EE and Eclipse GlassFish (May 2019)
Previewing Payara Platform 5.192
Gradual Migration to MicroProfile
Monitor Microservices with MicroProfile Metrics
Java2 days -_be_reactive_and_micro_with_a_microprofile_stack
Rapid development tools for java ee 8 and micro profile [GIDS]
Ondrej mihalyi be reactive and micro with a micro profile stack
Bed con Quest for JavaEE
Payara Micro from Raspberry Pi to Cloud
Microprofile and EE4J update
Devoxx Easily scale enterprise applications using distributed data grids
Demystifying microservices for JavaEE developers by Steve Millidge.

Recently uploaded (20)

PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Empathic Computing: Creating Shared Understanding
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Machine learning based COVID-19 study performance prediction
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPT
Teaching material agriculture food technology
PDF
Approach and Philosophy of On baking technology
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
NewMind AI Monthly Chronicles - July 2025
PPTX
Cloud computing and distributed systems.
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Empathic Computing: Creating Shared Understanding
Unlocking AI with Model Context Protocol (MCP)
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Machine learning based COVID-19 study performance prediction
Per capita expenditure prediction using model stacking based on satellite ima...
Mobile App Security Testing_ A Comprehensive Guide.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Teaching material agriculture food technology
Approach and Philosophy of On baking technology
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Dropbox Q2 2025 Financial Results & Investor Presentation
NewMind AI Monthly Chronicles - July 2025
Cloud computing and distributed systems.
Understanding_Digital_Forensics_Presentation.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication

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
  • 18. Strategy #2 - Singleton @ApplicationScoped public class TokenGenerator { @Inject @ConfigProperty(name = "mp.jwt.verify.issuer") private String issuer; public String generateFor(Attendee attendee){ try{ SignedJWT signedJWT = createSignedJWT(issuer); return signedJWT.sign(new RSASSASigner(readPrivateKey("/META-INF/keys/privateKey.pem"))).serialize(); } catch(Exception ex){ throw new RuntimeException("Failed generating JWT", ex); } } }
  • 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
  • 32. Strategy #5 – CDI > EJB @Stateless public class AnalyticsDataTimer { @Schedule(hour = "23", minute = "55", persistent = false) public void gatherScreenBehaviorData(){ try { List<ScreenBehaviorRecord> results = analyticsService.getViewBehaviorData(LocalDate.now()); appBehaviorService.persistScreenBehavior(results); } catch (IOException ex) { LOG.error("Error while gathering analytics data", ex); } } }
  • 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
  • 35. Strategy #6 – JPA Caching <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.2" xmlns="http://xmlns.jcp.org/xml/ns/persistence" …> <persistence-unit name="Vote" transaction-type="JTA"> <jta-data-source>jdbc/voteDS</jta-data-source> <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode> <properties> <property name="javax.persistence.schema-generation.database.action" value="create"/> </properties> </persistence-unit> </persistence>
  • 36. Strategy #6 – JPA Caching @Entity @Cacheable @NamedQuery(name = "SessionRating.getForSession", query = "select sr from SessionRating sr where sr.sessionId = :id order by sr.rating") public class SessionRating implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private Integer sessionId; private Integer rating; }
  • 37. Strategy #6 – JPA Caching <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.2" xmlns=“http://xmlns.jcp.org/xml/ns/persistence” ..,> <persistence-unit name="Vote" transaction-type="JTA"> <jta-data-source>jdbc/voteDS</jta-data-source> <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode> <properties> <property name="eclipselink.cache.coordination.protocol“ value="fish.payara.persistence.eclipselink.cache.coordination.HazelcastPublishingTransportManager"/> <property name="eclipselink.cache.coordination.channel" value=“voteDSChannel"/> </properties> </persistence-unit> </persistence>
  • 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.
  • 41. Strategy #7 - Configuration @Inject @ConfigProperty(name="demo.conference.speaker.venues", defaultValue = "Ocarina") private List<String> venues; Config configuration = ConfigProvider.getConfig(); String defaultVenue = configuration.getValue(“demo.conference.speaker.venues”, String.class); StaticConfigurationbyDI ProgrammaticLookup
  • 42. Strategy #7 - Configuration #Dockerfile (microservice-speaker) FROM payara/micro COPY microservice-speaker.war ${DEPLOY_DIR} #CommandLine docker run –p 8080:8080 –e “demo.conference.speaker.venues=OCARINA,ALFAJOR” fturizo/microservice-speaker –clusterName speaker
  • 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
  • 45. Strategy #8 – Fault Tolerance • Existing Tolerance Patterns • Retry • Fallback • Bulkhead • Circuit Breaker • Timeout • Asynchronous (overlapping with EJB’s)
  • 46. Strategy #8 – Fault Tolerance @POST @Consumes(MediaType.APPLICATION_JSON) @Retry(maxRetries = 5, delay = 30, delayUnit = ChronoUnit.SECONDS) public Response register(Attendee attendee){ Attendee result = attendeeService.create(attendee); return Response.created(URI.create("/attendee/" + result.getId())) .entity(result).build(); } RetryExample
  • 47. Strategy #8 – Fault Tolerance @Retry(maxRetries = 3, delay = 1, delayUnit = ChronoUnit.MINUTES) @Fallback(fallbackMethod = "cacheRating") public SessionRating addRating(SessionRating rating, Attendee attendee) { rating = rating.with(attendee, dataService.getSessionSummary(rating.getSessionId())); em.persist(rating); em.flush(); return rating; } FallbackExample
  • 48. Strategy #8 – Fault Tolerance public SessionRating cacheRating(SessionRating rating, Attendee attendee){ rating = rating.with(attendee); cachedRatings.putIfAbsent(rating.getSessionId(), new ArrayList<>()); cachedRatings.get(rating.getSessionId()).add(rating); return rating; } Retry-FallbackMethodExample
  • 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!
  • 52. Strategy #9 – Stateless Security JWTExample
  • 53. Strategy #9 – Stateless Security curl -X POST http://lb.payara.fish/microservice-vote/rating/ -H 'Content-Type: application/json’ –H ‘Authorization: Bearer eyJraWQiOiJcL3ByaXZhdGVLZXkucGVtIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJhdWQiOiJhdHRlbmRlZXMiLCJzdWIiOiJBbGZyZWRvIE1vbGluYSIsInV wbiI6ImFsZnJlZG8ubW9saW5hQGdtYWlsLmNvbSIsImF1dGhfdGltZSI6MTU1NDE2NjM2MiwiaXNzIjoiZGVtb3MucGF5YXJhLmZpc2giLCJncm91cHMiOlsiQ0FOX1ZPV EUiXSwiZXhwIjoxNTU0MTc2MzYyLCJpYXQiOjE1NTQxNjYzNjIsImp0aSI6ImF0dC0xIn0.qXO0fbblsjusbo58DI0yDPua3uw1YnKR6VkIQOKP_SCACb5whpAEjD6iBVv RQ7UUvoLiLIFisoGEoa_K17VjiyyDdDk6QGgI1tvYUMnaoQ’ -d '{"session-id" : 1, "rating" : 5}'
  • 54. Strategy #9 – Stateless Security @ApplicationPath("/") @ApplicationScoped @LoginConfig(authMethod = "MP-JWT") @DeclareRoles(“ADMIN”, “CAN_VOTE”) public class VoteApplication extends Application{ } LoginDefinition
  • 55. Strategy #9 – Stateless Security #microprofile-config.properties #MP JWT Settings mp.jwt.verify.publickey.location = /META-INF/keys/publicKey.pem mp.jwt.verify.issuer = demos.payara.fish JWTConfiguration
  • 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
  • 61. Strategy #10 – Metrics @POST @Consumes(MediaType.APPLICATION_JSON) @Metered(name = "session.creation.tries", absolute = true) public Response create(Session session) { session = sessionService.register(session); return Response.created(URI.create("/" +session.getId())) .entity(session).build(); } MeteredExample
  • 62. Strategy #10 – Metrics @Inject @Metric(name = "session.spaces", absolute = false) Counter sessionSpaces; … @PostConstruct public void init(){ sessionSpaces.inc(5); } CounterExample
  • 63. Strategy #10 – Metrics <config> <vendor> <metadata> <name>system.cpu.load</name> <mbean>java.lang:type=OperatingSystem/SystemCpuLoad</mbean> <type>gauge</type> <unit>none</unit> <displayName>System CPU Load</displayName> <description>Recent CPU usage for the whole system.</description> </metadata> </vendor> </config> CustomVendorMetrics-Payara
  • 64. Q & A
  • 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/