<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Bhavik Kothari on Medium]]></title>
        <description><![CDATA[Stories by Bhavik Kothari on Medium]]></description>
        <link>https://medium.com/@bkkothari2255?source=rss-20e3c0874a59------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dvuTfM_WNoVG6PSDF29u1A.jpeg</url>
            <title>Stories by Bhavik Kothari on Medium</title>
            <link>https://medium.com/@bkkothari2255?source=rss-20e3c0874a59------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 07:57:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bkkothari2255/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Architect’s Guide to OSGi Schedulers & Sling Jobs: From Anti-Patterns to Cloud-Ready Execution]]></title>
            <link>https://medium.com/@bkkothari2255/the-architects-guide-to-osgi-schedulers-sling-jobs-from-anti-patterns-to-cloud-ready-execution-8d76f45d9e32?source=rss-20e3c0874a59------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d76f45d9e32</guid>
            <category><![CDATA[aemasacloudservice]]></category>
            <category><![CDATA[scheduler]]></category>
            <category><![CDATA[osgi]]></category>
            <category><![CDATA[sling]]></category>
            <category><![CDATA[aem-architect]]></category>
            <dc:creator><![CDATA[Bhavik Kothari]]></dc:creator>
            <pubDate>Wed, 20 May 2026 10:38:34 GMT</pubDate>
            <atom:updated>2026-05-20T23:14:36.016Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Core Problem: Why Your Scheduler Is Broken in the Cloud</h3><p>Adobe Experience Manager as a Cloud Service (AEMaaCS) runs in a <strong>clustered, auto-scaling environment</strong>. Every author and publish node is a peer. When you use the legacy Runnable-based OSGi Scheduler, <strong>every node in the cluster runs the job simultaneously</strong>. This causes:</p><ul><li>Duplicate content processing (e.g., replication fired N times)</li><li>Race conditions on JCR writes</li><li>Unpredictable side effects at scale</li></ul><p>The Adobe Archetype <a href="https://github.com/adobe/aem-project-archetype/pull/1331/changes">PR #1331</a> formally removes SimpleScheduledTask (the Runnable pattern) and replaces it with SimpleJobConsumer + SimpleJobScheduler.</p><p>in this article we will explore exactly why, how, and what best practices every AEM Architect must follow.</p><h3>The Two-Class Architecture: Separating Concerns</h3><p>The Sling Job pattern enforces a clean <strong>separation of concerns</strong> across exactly two classes:</p><pre>┌──────────────────────────────────────────────────────────────────┐<br>│  SimpleJobScheduler                                              │<br>│  &quot;WHEN to run&quot; — OSGi Component with @Designate config           │<br>│  Uses: JobManager to schedule via cron                           │<br>└─────────────────────────────┬────────────────────────────────────┘<br>                              │  fires topic: &quot;my/sample/job&quot;<br>                              ▼<br>┌──────────────────────────────────────────────────────────────────┐<br>│  SimpleJobConsumer                                               │<br>│  &quot;WHAT to do&quot; — implements JobConsumer                           │<br>│  Guaranteed single execution across cluster                      │<br>└──────────────────────────────────────────────────────────────────┘</pre><p>This mirrors the proven Command Pattern: <strong>the scheduler</strong> is <strong>the invoker</strong>, <strong>the job consumer</strong> is <strong>the command handler</strong>.</p><h3>The Legacy Anti-Pattern (What NOT to Do)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*mGd6vGrTniAkOSQ3W9GLVQ.png" /><figcaption>OSGi Runnable Anti Pattern</figcaption></figure><pre>// ANTI-PATTERN: Do NOT use in AEMaaCS<br>@Component(service = Runnable.class)<br>@Designate(ocd = SimpleScheduledTask.Config.class)<br>public class SimpleScheduledTask implements Runnable {<br><br>    @ObjectClassDefinition(name = &quot;A scheduled task&quot;)<br>    public static @interface Config {<br>        @AttributeDefinition(name = &quot;Cron-job expression&quot;)<br>        String scheduler_expression() default &quot;0 0 0 * * ?&quot;;<br><br>        @AttributeDefinition(name = &quot;Concurrent&quot;)<br>        boolean scheduler_concurrent() default false;<br><br>        @AttributeDefinition(name = &quot;A parameter&quot;)<br>        String myParameter() default &quot;&quot;;<br>    }<br><br>    @Override<br>    public void run() {<br>        // THIS RUNS ON EVERY CLUSTER NODE SIMULTANEOUSLY<br>        logger.debug(&quot;Running on all nodes: {}&quot;, config.myParameter());<br>    }<br><br>}</pre><p><strong>Why this fails:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae7d685567eedbc82253e26a4f1746c9/href">https://medium.com/media/ae7d685567eedbc82253e26a4f1746c9/href</a></iframe><h3>The Cloud-Ready Pattern — JobConsumer</h3><p>Reference: aem-project-archetype <a href="https://github.com/adobe/aem-project-archetype/pull/1331/changes">PR #1331</a>, SimpleJobConsumer.java</p><figure><img alt="Sling Job Consumer" src="https://cdn-images-1.medium.com/max/1024/1*CuMaKQjOnxgESqrWTiPQkg.png" /><figcaption>Sling Job Consumer Pattern (AEMasCS)</figcaption></figure><pre>// CORRECT: Cloud-ready best practice - Sling Job Consumer<br>package com.myproject.core.jobs;<br><br>import org.apache.sling.event.jobs.Job;<br>import org.apache.sling.event.jobs.consumer.JobConsumer;<br>import org.osgi.service.component.annotations.Component;<br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br><br>/**<br> * JobConsumer: Defines WHAT to do when a job fires.<br> * Sling guarantees this runs on exactly ONE node in the cluster.<br> *<br> * Topic: &quot;my/sample/job&quot;<br> *<br> * @see &lt;a href=&quot;https://sling.apache.org/documentation/bundles/apache-sling-eventing-and-job-handling.html&quot;&gt;<br> *     Sling Eventing and Job Handling&lt;/a&gt;<br> */<br>@Component(<br>    service = JobConsumer.class,<br>    immediate = true,<br>    property = {<br>        JobConsumer.PROPERTY_TOPICS + &quot;=my/sample/job&quot;<br>    }<br>)<br>public class SimpleJobConsumer implements JobConsumer {<br><br>    private final Logger logger = LoggerFactory.getLogger(getClass());<br><br>    @Override<br>    public JobResult process(Job job) {<br><br>        logger.debug(&quot;SimpleJobConsumer processing job: &#39;{}&#39;&quot;, job.getTopic());<br>        <br>        try {<br><br>            // Read typed properties passed by the Scheduler<br>            String myParameter = job.getProperty(&quot;myParameter&quot;, String.class);<br><br>            // ---- Business logic here ----<br><br>            doWork(myParameter);<br><br>            // -----------------------------<br><br>            return JobResult.OK; // Job succeeded - removed from queue<br>        } catch (Exception e) {<br><br>            logger.error(&quot;Job processing failed for topic &#39;{}&#39;: {}&quot;, job.getTopic(), e.getMessage(), e);<br>            <br>            return JobResult.FAILED; // Triggers retry based on retry config<br>        }<br>    }<br><br>    private void doWork(String parameter) {<br>        // Implement actual logic here<br><br>        logger.info(&quot;Processing with parameter: {}&quot;, parameter);<br>    }<br>}</pre><h3>Key Design Decisions</h3><p><strong>JobResult is your retry contract:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/201a7c1f55005e2943305f7844531627/href">https://medium.com/media/201a7c1f55005e2943305f7844531627/href</a></iframe><p><strong>Best Practice:</strong> Never return CANCEL for transient failures (network, JCR lock). Return FAILED so Sling can retry with backoff. Only use CANCEL for unrecoverable business failures (e.g., malformed input that will never succeed).</p><h3>The Cloud-Ready Pattern — JobScheduler</h3><p>Reference: aem-project-archetype <a href="https://github.com/adobe/aem-project-archetype/pull/1331/changes">PR #1331</a>,, SimpleJobScheduler.java</p><pre>// CORRECT: Scheduler that fires Sling Jobs via JobManager<br>package com.myproject.core.schedulers;<br><br>import org.apache.sling.event.jobs.JobManager;<br>import org.apache.sling.event.jobs.ScheduledJobInfo;<br>import org.osgi.service.component.annotations.*;<br>import org.osgi.service.metatype.annotations.*;<br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br>import java.util.Collection;<br>import java.util.HashMap;<br>import java.util.Map;<br><br><br>/**<br> * JobScheduler: Defines WHEN to run by placing a job on the Sling Job Queue.<br> * Does NOT implement Runnable - it only orchestrates scheduling.<br> *<br> * Pattern: Separated from JobConsumer to follow Single Responsibility Principle.<br> */<br>@Designate(ocd = SimpleJobScheduler.Config.class)<br>@Component(immediate = true)<br>public class SimpleJobScheduler {<br><br>    // ============================================================<br>    // OSGi Configuration - editable in /system/console/configMgr<br>    // ============================================================<br>    @ObjectClassDefinition(<br>        name = &quot;My Project - Simple Job Scheduler&quot;,<br>        description = &quot;Schedules the my/sample/job Sling Job on a cron expression&quot;<br>    )<br>    public static @interface Config {<br><br>        @AttributeDefinition(<br>            name = &quot;Enabled&quot;,<br>            description = &quot;Enable or disable the scheduled job. Safe to disable without code deploy.&quot;<br>        )<br>        boolean enabled() default false; // Default OFF - intentional safety gate<br><br>        @AttributeDefinition(<br>            name = &quot;Cron Expression&quot;,<br>            description = &quot;Quartz cron format. Default: every day at midnight. &quot; +<br>                          &quot;See: http://www.quartz-scheduler.org/documentation/quartz-2.3.0/tutorials/crontrigger.html&quot;<br>        )<br>        String scheduler_expression() default &quot;0 0 0 * * ?&quot;;<br><br>        @AttributeDefinition(<br>            name = &quot;My Parameter&quot;,<br>            description = &quot;Runtime parameter passed to the Job Consumer&quot;<br>        )<br>        String myParameter() default &quot;&quot;;<br><br>    }<br><br>    private final Logger logger = LoggerFactory.getLogger(getClass());<br><br>    // Job topic constant - single source of truth (shared with Consumer)<br>    static final String JOB_TOPIC = &quot;my/sample/job&quot;;<br><br>    @Reference<br>    private JobManager jobManager;<br><br>    // ============================================================<br>    // Lifecycle<br>    // ============================================================<br>    @Activate<br>    @Modified // Handles OSGi config updates without restart<br>    protected void activate(final Config config) {<br><br>        // Always clean up existing scheduled entries first to prevent duplicates<br>        unscheduleJobs();<br><br>        if (!config.enabled()) {<br>            logger.info(&quot;SimpleJobScheduler is disabled. No job scheduled for topic &#39;{}&#39;.&quot;, JOB_TOPIC);<br>            return;<br>        }<br><br>        Map&lt;String, Object&gt; jobProperties = new HashMap&lt;&gt;();<br>        jobProperties.put(&quot;myParameter&quot;, config.myParameter());<br>        jobManager.createJob(JOB_TOPIC)<br>            .properties(jobProperties)<br>            .schedule()<br>            .cron(config.scheduler_expression())<br>            .add(); // Persists the scheduled job to the JCR<br><br>        logger.info(&quot;Scheduled Sling Job &#39;{}&#39; with cron &#39;{}&#39;&quot;, JOB_TOPIC, config.scheduler_expression());<br>    }<br><br>    @Deactivate<br>    protected void deactivate() {<br>        // Clean up on bundle stop - prevents orphaned schedules in JCR<br>        unscheduleJobs();<br>        logger.info(&quot;SimpleJobScheduler deactivated. Unscheduled all jobs for topic &#39;{}&#39;.&quot;, JOB_TOPIC);<br>    }<br><br>    // ============================================================<br>    // Helpers<br>    // ============================================================<br>    private void unscheduleJobs() {<br>        Collection&lt;ScheduledJobInfo&gt; scheduledJobs = jobManager.getScheduledJobs(JOB_TOPIC, 10, null);<br><br>        if (scheduledJobs != null) {<br>            scheduledJobs.forEach(ScheduledJobInfo::unschedule);<br>        }<br>    }<br><br>}</pre><h3>Advanced Pattern-Triggering Jobs On-Demand (Non-Scheduled)</h3><p>Not every job needs a cron. Use JobManager.addJob() to fire immediately from a Servlet, Workflow, or another Service:</p><pre>// Trigger a Sling Job programmatically (e.g., from a Servlet)<br>@Reference<br>private JobManager jobManager;<br><br>public void triggerJob(String resourcePath) {<br>    Map&lt;String, Object&gt; jobProperties = new HashMap&lt;&gt;();<br>    jobProperties.put(&quot;resourcePath&quot;, resourcePath);<br>    jobProperties.put(&quot;triggeredBy&quot;, &quot;ContentPublishServlet&quot;);<br>    Job job = jobManager.addJob(&quot;my/sample/job&quot;, jobProperties);<br>    if (job != null) {<br>        logger.info(&quot;Job queued successfully. Job ID: {}&quot;, job.getId());<br>    } else {<br>        logger.error(&quot;Failed to queue job for topic: my/sample/job&quot;);<br>    }<br>}</pre><p><strong>Technical proof:</strong> JobManager.addJob() returns null if no JobConsumer is registered for the topic. Always null-check the return value — it is your deployment health check.</p><h3>Unit Testing (Following Archetype PR #1331)</h3><h3>Testing the Consumer</h3><pre>// Reference: SimpleJobConsumerTest.java from aem-project-archetype PR #1331<br>@ExtendWith(AemContextExtension.class)<br>class SimpleJobConsumerTest {<br><br>private SimpleJobConsumer fixture = new SimpleJobConsumer();<br><br>    @Test<br>    void process() {<br>        Job job = mock(Job.class);<br>        when(job.getTopic()).thenReturn(&quot;my/sample/job&quot;);<br>        when(job.getProperty(&quot;myParameter&quot;, String.class)).thenReturn(&quot;test-value&quot;);<br>        JobResult result = fixture.process(job);<br>        assertEquals(JobResult.OK, result);<br>    }<br><br>    @Test<br>    void process_exceptionReturnsFailure() {<br>        Job job = mock(Job.class);<br>        when(job.getTopic()).thenThrow(new RuntimeException(&quot;simulated error&quot;));<br>        JobResult result = fixture.process(job);<br>        // Verify FAILED (not CANCEL) so Sling retries<br>        assertEquals(JobResult.FAILED, result);<br>    }<br><br>}</pre><h3>Testing the Scheduler</h3><pre>// Reference: SimpleJobSchedulerTest.java from aem-project-archetype PR #1331<br>@ExtendWith(AemContextExtension.class)<br>class SimpleJobSchedulerTest {<br><br>    private SimpleJobScheduler fixture = new SimpleJobScheduler();<br>    private JobManager jobManager;<br>    private JobBuilder jobBuilder;<br>    private JobBuilder.ScheduleBuilder scheduleBuilder;<br><br>    @BeforeEach<br>    void setup() throws Exception {<br>        jobManager = mock(JobManager.class);<br>        jobBuilder = mock(JobBuilder.class);<br>        scheduleBuilder = mock(JobBuilder.ScheduleBuilder.class);<br>        when(jobManager.getScheduledJobs(anyString(), any(Long.class), any()))<br>            .thenReturn(Collections.emptyList());<br>        when(jobManager.createJob(anyString())).thenReturn(jobBuilder);<br>        when(jobBuilder.properties(any())).thenReturn(jobBuilder);<br>        when(jobBuilder.schedule()).thenReturn(scheduleBuilder);<br>        when(scheduleBuilder.cron(anyString())).thenReturn(scheduleBuilder);<br><br>        // Inject mocked JobManager via reflection (no AEM container needed)<br>        Field jobManagerField = fixture.getClass().getDeclaredField(&quot;jobManager&quot;);<br>        jobManagerField.setAccessible(true);<br>        jobManagerField.set(fixture, jobManager);<br>    }<br><br>    @Test<br>    void activate_whenEnabled_schedulesJob() {<br>        SimpleJobScheduler.Config config = mock(SimpleJobScheduler.Config.class);<br>        when(config.enabled()).thenReturn(true);<br>        when(config.myParameter()).thenReturn(&quot;test-param&quot;);<br>        when(config.scheduler_expression()).thenReturn(&quot;0 0 * * * ?&quot;);<br>        fixture.activate(config);<br>        verify(jobManager).createJob(&quot;my/sample/job&quot;);<br>        verify(jobBuilder).properties(any());<br>        verify(scheduleBuilder).cron(&quot;0 0 * * * ?&quot;);<br>        verify(scheduleBuilder).add();<br>    }<br><br>    @Test<br>    void activate_whenDisabled_doesNotSchedule() {<br>        SimpleJobScheduler.Config config = mock(SimpleJobScheduler.Config.class);<br>        when(config.enabled()).thenReturn(false);<br>        fixture.activate(config);<br>        verify(jobManager, never()).createJob(anyString());<br>    }<br><br>}</pre><h3>OSGi Services — Component Lifecycle Best Practices</h3><p>Every job consumer and scheduler is ultimately an OSGi Service. These rules govern all of them.</p><h3>The Lifecycle Diamond</h3><pre>@Activate ──► running ──► @Modified (config update — no restart)<br>                │<br>                ▼<br>           @Deactivate</pre><pre>@Component(service = MyOsgiService.class)<br>@Designate(ocd = MyOsgiService.Config.class)<br>public class MyOsgiService {<br><br>    @ObjectClassDefinition(name = &quot;My OSGi Service Configuration&quot;)<br>    public static @interface Config {<br><br>        @AttributeDefinition(name = &quot;Service Enabled&quot;)<br>        boolean enabled() default true;<br><br>        @AttributeDefinition(name = &quot;Max Retry Count&quot;)<br>        int maxRetries() default 3;<br><br>    }<br><br>    @Reference<br>    private ResourceResolverFactory resourceResolverFactory;<br><br>    private volatile boolean enabled; // volatile for thread safety<br><br>    @Activate<br>    @Modified<br>    protected void activate(Config config) {<br>        this.enabled = config.enabled();<br>    }<br><br>    @Deactivate<br>    protected void deactivate() {<br>        // Release resources, stop background threads<br>    }<br><br>    /**<br>     * BEST PRACTICE: Always use service user resolvers, never admin sessions.<br>     * Map service user in: /apps/myproject/config/org.apache.sling.serviceusermapping.impl.ServiceUserMapperImpl.amended-myproject.xml<br>     */<br>    private ResourceResolver getServiceResourceResolver() throws LoginException {<br>        Map&lt;String, Object&gt; param = new HashMap&lt;&gt;();<br>        param.put(ResourceResolverFactory.SUBSERVICE, &quot;my-service-user&quot;);<br>        return resourceResolverFactory.getServiceResourceResolver(param);<br>    }<br><br>}</pre><h3>Complete Best Practices Reference</h3><h3>1. Separate the Scheduler from the Consumer</h3><p>Never put business logic in the scheduler. The scheduler is purely an orchestrator (WHEN). The consumer is purely a handler (WHAT). This enables independent testing, redeployment, and scaling.</p><h3>2. Default enabled = false</h3><p>New schedulers should default to off. This prevents accidental job fires during deployment to non-production environments. Operators explicitly enable via OSGi config after validation.</p><h3>3. Always Annotate @Modified on @Activate</h3><pre>@Activate<br>@Modified  // Without this, config changes require a full OSGi bundle restart<br>protected void activate(Config config) { ... }</pre><h3>4. Always Clean Up in @Deactivate</h3><p>Orphaned ScheduledJobInfo entries accumulate in the JCR under /var/eventing. Each redeploy without cleanup creates a new schedule entry. The unscheduleJobs() pattern from PR #1331 prevents this.</p><h3>5. Use Constants for Job Topics</h3><pre>// String literals scattered across files — fragile<br>property = { JobConsumer.PROPERTY_TOPICS + &quot;=my/sample/job&quot; }<br><br>// Constants defined in one place - shared between Consumer and Scheduler<br>public final class JobTopics {<br>    public static final String SAMPLE_JOB = &quot;my/sample/job&quot;;<br><br>    // Topic naming convention: &lt;domain&gt;/&lt;action&gt;/&lt;entity&gt;<br>    public static final String CONTENT_REPLICATION = &quot;myproject/replication/content&quot;;<br>}</pre><h3>6. Use Quartz Cron Format (Not Unix Cron)</h3><p>Sling uses <strong>Quartz cron format</strong> which has 6 or 7 fields (includes seconds), unlike Unix cron with 5.</p><p>(examples references : <a href="https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm">https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm</a>)</p><pre>Unix cron:   0 0 * * *      (minute hour day month weekday)<br>Quartz cron: 0 0 0 * * ?    (second minute hour day month weekday)<br>                       ↑ trailing ? is required for day-of-week wildcard</pre><h3>7. Implement JobExecutionContext for Long-Running Jobs</h3><p>For jobs that take more than a few seconds, implement progress tracking and stoppability:</p><pre>// For complex, long-running jobs — use JobExecutor (advanced)<br>@Component(service = JobExecutor.class, property = {<br>    JobExecutor.PROPERTY_TOPICS + &quot;=myproject/heavyjob&quot;<br>})<br>public class HeavyJobExecutor implements JobExecutor {<br><br>    @Override<br>    public JobExecutionResult process(Job job, JobExecutionContext context) {<br>        context.initProgress(100, -1); // 100 steps, no time limit<br>        for (int i = 0; i &lt; 100; i++) {<br>            if (context.isStopped()) {<br>                return context.result().cancelled(); // Graceful stop on cluster failover<br>            }<br>            processStep(i);<br>            context.incrementProgressCount(1);<br>        }<br>        return context.result().succeeded();<br>    }<br><br>}</pre><h3>8. Use Service Users, Never Admin Sessions</h3><pre>// FORBIDDEN in AEMaaCS<br>ResourceResolver resolver = resourceResolverFactory.getAdministrativeResourceResolver(null);<br><br>// REQUIRED: Map service user in OSGi config, use subservice name<br>Map&lt;String, Object&gt; param = Collections.singletonMap(<br>    ResourceResolverFactory.SUBSERVICE, &quot;my-background-job-user&quot;<br>);<br>ResourceResolver resolver = resourceResolverFactory.getServiceResourceResolver(param);</pre><h3>9. Always Close ResourceResolvers in Finally / Try-with-Resources</h3><pre>// Try-with-resources guarantees resolver closure even on exception<br>try (ResourceResolver resolver = getServiceResourceResolver()) {<br>    // do JCR work<br>    resolver.commit();<br>}</pre><h3>10. Monitor via Sling Eventing Console</h3><p>All Sling Jobs are visible in the OSGi Web Console:</p><ul><li><strong>Active Jobs:</strong> /system/console/slingevent</li><li><strong>Job Statistics:</strong> /system/console/slingevent/stats</li><li><strong>Scheduled Jobs:</strong> /system/console/slingevent/scheduled</li></ul><h3>Package Structure (Following Archetype PR #1331)</h3><pre>core/src/main/java/com/myproject/core/<br>├── jobs/<br>│   ├── package-info.java         (@Version(&quot;1.0&quot;))<br>│   ├── SimpleJobConsumer.java    (implements JobConsumer)<br>│   └── HeavyJobExecutor.java    (implements JobExecutor — advanced)<br>├── schedulers/<br>│   ├── package-info.java         (@Version(&quot;1.0&quot;))<br>│   └── SimpleJobScheduler.java   (@Component, uses JobManager)<br>└── services/<br>    └── MyOsgiService.java        (@Component with @Designate)<br><br>core/src/test/java/com/myproject/core/<br>├── jobs/<br>│   └── SimpleJobConsumerTest.java<br>└── schedulers/<br>    └── SimpleJobSchedulerTest.java</pre><p><strong>Architectural principle:</strong> jobs/ and schedulers/ are always separate packages. A consumer never directly references its scheduler and vice versa — they are decoupled through the job topic string only.</p><h3>Technical Proof Summary</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/123b0f7c8e42e758a092e90158ccd1b2/href">https://medium.com/media/123b0f7c8e42e758a092e90158ccd1b2/href</a></iframe><h3>The Architect’s Checklist</h3><p>Before any Sling Job ships to production, verify:</p><ul><li>Runnable interface is NOT implemented anywhere</li><li>JobConsumer has PROPERTY_TOPICS property set</li><li>Job topic is a shared constant — not a string literal</li><li>@Activate is also annotated @Modified</li><li>@Deactivate calls unscheduleJobs()</li><li>enabled = false by default in OSGi config</li><li>JobResult.FAILED returned on transient errors (not CANCEL)</li><li>ResourceResolver opened with service user — not admin</li><li>ResourceResolver closed via try-with-resources</li><li>Unit tests cover both enabled = true and enabled = false</li><li>Unit tests verify JobResult.OK on success and JobResult.FAILED on exception</li><li>Long-running jobs check context.isStopped() for graceful cluster failover</li></ul><p><em>References:</em></p><ul><li><a href="https://experienceleague.adobe.com/en/docs/experience-manager-cloud-service/content/overview/architecture">Introduction to the Architecture of AEM as a Cloud Service</a> — Explains the separation of code and content, the immutable baseline images, and how the Author/Publish tiers are clustered.</li><li><a href="https://github.com/adobe/aem-project-archetype/pull/1331"><em>Adobe AEM Project Archetype PR #1331</em></a><em> — Refactor legacy OSGi Schedulers to Sling Job Consumers</em></li><li><a href="https://experienceleague.adobe.com/en/docs/experience-manager-cloud-service/content/implementing/developing/development-guidelines">AEM as a Cloud Service Development Guidelines</a> — This is the master document outlining the “Code Must Be Cluster-Aware” rule. It details why the disk is ephemeral, why memory state is forbidden, and why Sling Jobs must replace Schedulers.</li><li><a href="https://experienceleague.adobe.com/en/docs/experience-manager-learn/cloud-service/expert-resources/cloud-5/season-2/cloud5-sling-job-scheduler">Cloud 5 Season 2: Sling Job Scheduler Video Tutorial</a> — An Adobe developer video specifically walking through the “gotchas” of Job Scheduling and consumption in a clustered cloud environment compared to classic AEM.</li><li><a href="https://sling.apache.org/documentation/bundles/apache-sling-eventing-and-job-handling.html"><em>Apache Sling Eventing and Job Handling</em></a><em> — </em>This is the core manual for the Sling Job framework. It explains the difference between the Event Admin (fire and forget) and the Job Manager (guaranteed processing), how to configure queues, and how to write a JobConsumer.</li><li><a href="https://developer.adobe.com/experience-manager/reference-materials/6-5/javadoc/org/apache/sling/event/jobs/package-summary.html">Package org.apache.sling.event.jobs (JavaDocs)</a> — The technical API reference for JobManager, JobConsumer, and the JobBuilder interfaces used in your Java code to instantiate and process jobs.</li><li><a href="https://experienceleague.adobe.com/en/docs/experience-manager-learn/cloud-service/developing/osgi-services/service-users"><em>AEMaaCS Service Users</em></a><em> — </em>When a Sling Job executes in the background, it does not have a user request or session attached to it. To interact with the JCR (e.g., to read content or update a property), the job must authenticate securely. Admin sessions are strictly forbidden and disabled; instead, you must use Service Users.</li><li><a href="https://experienceleague.adobe.com/en/docs/experience-manager-learn/cloud-service/developing/advanced/run-job-on-leader-instance-in-aem-author">Tutorial: How to Run a Job on the Leader Instance in AEMaaCS</a> — Provides exact code and OSGi configurations for creating an ORDERED Sling Job Queue that restricts execution to a single leader pod, preventing duplicate processing.</li><li><a href="https://docs.osgi.org/specification/osgi.cmpn/7.0.0/service.component.html"><em>OSGi Declarative Services Specification R7</em></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d76f45d9e32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Under the hood of the JCR Oak Storage Engine: AEM Developer’s Guide to NodeStore & Compaction]]></title>
            <link>https://medium.com/@bkkothari2255/under-the-hood-of-the-jcr-oak-storage-engine-aem-developers-guide-to-nodestore-compaction-4021eb4fd7c1?source=rss-20e3c0874a59------2</link>
            <guid isPermaLink="false">https://medium.com/p/4021eb4fd7c1</guid>
            <category><![CDATA[oak]]></category>
            <category><![CDATA[aem]]></category>
            <category><![CDATA[aem-developer]]></category>
            <dc:creator><![CDATA[Bhavik Kothari]]></dc:creator>
            <pubDate>Mon, 16 Mar 2026 09:37:05 GMT</pubDate>
            <atom:updated>2026-03-17T20:31:36.076Z</atom:updated>
            <content:encoded><![CDATA[<p>We’ve wired our Java backend together with <strong>OSGi</strong>, and we’ve mapped our incoming web traffic using Sling. But at the end of the day, AEM is a <strong>Content Management System</strong>. Where does all that content actually live?</p><p>Every time a content author clicks “<strong>Publish</strong>” in AEM, something has to write that data to disk. Every package installation from <strong>FileVault</strong>, every Sling resource update, every workflow — it all ends in the same place: <strong>Apache Jackrabbit Oak.</strong></p><p>But <strong>Oak</strong> doesn’t write data the way you think it does. It doesn’t update records in place like MySQL. It doesn’t overwrite files like a standard file system. It has a fundamentally different storage philosophy — and if you don’t understand the consequence of that philosophy, your production server will eventually run out of disk space and crash with no warning.</p><p>AEM is not built on a traditional relational database. It runs on top of <strong>Apache Jackrabbit Oak</strong>, a hierarchical NoSQL storage engine designed specifically to handle massive, deeply nested trees of content.</p><p>Let’s crack open the storage layer and see exactly how <strong>Oak</strong> reads, writes, and manages your data.</p><h3>1. The NodeStore: TarMK vs. MongoMK</h3><p>When application code uses the JCR API to read or write a node, <strong>Oak</strong> routes that request to the <strong>NodeStore</strong>. The <strong>NodeStore</strong> is the physical persistence layer, and AEM gives architects two primary choices on how to configure it:</p><h4><strong>SegmentNodeStore (TarMK)</strong></h4><p>This is the default and the fastest option. It writes data to local .tar files directly on the server&#39;s file system. It is highly optimized for read performance, making it the default choice for both Author and Publish tier servers in the majority of AEM deployments.</p><h4><strong>DocumentNodeStore (MongoMK)</strong></h4><p>Instead of local files, this stores nodes as JSON documents inside a MongoDB cluster. This sacrifices some raw read speed but allows for horizontal scaling (clustering multiple active AEM Author servers together to handle massive authoring teams).</p><h4><strong>Where Binaries Live: The BlobStore</strong></h4><p>There is one critical distinction that the <strong>NodeStore</strong> section above glosses over: <strong>TarMK</strong>’s .tar segment files store node metadata and text properties efficiently. But what about binary data — images, PDFs, videos, and other large file uploads?</p><p>Storing a 50MB video directly inside a .tar segment file would be catastrophic for performance. <strong>Oak</strong> solves this with a separate storage layer called the <strong>BlobStore</strong>, which handles all binary content independently from the node tree.</p><p>In a standard AEM on-premise installation, the <strong>BlobStore</strong> is a <strong>FileDataStore</strong> — a flat folder on the local file system where every binary is stored as a content-addressed file (named by the SHA-256 hash of its contents). In cloud deployments, this is swapped out for an <strong>AzureBlobStore</strong> or <strong>S3DataStore</strong>, pushing binary storage to <strong>cloud object storage</strong> entirely.</p><p>This separation is why AEM backup strategies must always cover two distinct locations: the segmentstore/ directory for <strong>node data</strong>, and the datastore/ directory for <strong>binaries</strong>. Backing up only one without the other produces a corrupt, unusable repository.</p><blockquote><strong>Pro-tip:</strong> Duplicate binaries are automatically deduplicated by the BlobStore. If 500 authors upload the same logo PNG, Oak stores the binary exactly once and points all 500 nodes at the same hash. This is not a feature you configure — it is built into the content-addressing model.</blockquote><h3>2. The Append-Only Reality (Why Compaction Exists)</h3><p>If your AEM instance is running TarMK — which the vast majority do — there is a fundamental architectural reality you must understand: <strong>TarMK is an append-only file system.</strong></p><p>If a content author edits a page’s jcr:title 100 times, Oak does not overwrite the existing property value. It writes 100 brand-new revisions to the .tar files and never touches the old ones. Every node update, every property change, every workflow step — each one adds a new entry to the end of the file. Nothing is ever deleted automatically.</p><p>The trap is obvious in hindsight: because TarMK never removes old data, your AEM disk will grow continuously until the server runs out of space entirely.</p><h4><strong>Online Compaction (The Daily Maintenance Window)</strong></h4><p>AEM ships with a built-in solution called <strong>Revision Garbage Collection</strong>, which runs automatically inside the daily maintenance window (by default, between 2am and 5am). This is called <strong>Online Compaction</strong> because it runs while the server is live and serving traffic.</p><p>The process works in three phases. First, the Estimation phase scans the .tar files and calculates how much garbage — obsolete, unreachable node revisions — has accumulated. If the garbage falls below a configurable threshold (default 10%), compaction is skipped entirely as unnecessary. Second, the Compaction phase rewrites only the currently live, reachable node revisions into fresh, tightly packed .tar files. Third, the Cleanup phase deletes the old bloated .tar files, reclaiming the disk space.</p><h4><strong>Offline Compaction (The Emergency Tool)</strong></h4><p>If Online Compaction has been skipped for too long — or if a server has been running without maintenance for months — the .tar files can grow so large that the Online process itself runs out of memory trying to compact them. In this scenario, administrators must take the AEM instance offline and run compaction manually using the oak-run.jar command-line tool:</p><p>java -jar oak-run.jar compact crx-quickstart/repository/segmentstore</p><p>This is the nuclear option. It is slower, requires downtime, but can compact even severely bloated repositories that the online process can no longer handle.</p><blockquote><strong><em>Pro-tip:</em></strong><em> Never let Online Compaction get disabled on a production instance. A repository that hasn’t been compacted for 30 days can easily consume 3–5x its logical data size in raw disk space.</em></blockquote><h3>3. The Need for Speed (/oak:index)</h3><p>Because Oak stores data in a massive, sprawling tree, searching it is inherently difficult.</p><p>If you write a query to find all pages with the template myproject/templates/article, and you do not have an index, Oak performs a <strong>Traversal</strong>. It starts at the root (/) and literally walks down every single branch of the database, checking every node one by one. In a repository with 5 million nodes, a traversal will paralyze your server&#39;s CPU.</p><p>To prevent this, AEM uses the /oak:index system (typically powered by Apache Lucene or Elasticsearch).</p><pre>-- A standard JCR-SQL2 Query<br>SELECT * FROM [cq:PageContent] AS p WHERE ISDESCENDANTNODE(p, &#39;/content/myproject&#39;) AND p.[cq:template] = &#39;/conf/myproject/settings/wcm/templates/article&#39;</pre><p>When you execute this query via the QueryBuilder API, Oak intercepts it and checks /oak:index. If you have defined a Lucene index for the cq:template property, Oak skips the tree entirely. It asks the index for the exact memory addresses of those specific nodes and fetches them instantly in milliseconds.</p><blockquote><em>Pro-tip: Never deploy a custom component that relies on a complex QueryBuilder search without also packaging the corresponding XML definition for its </em><em>/oak:index!</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Bwf5rR-t0oyrGZQkxHh7w.png" /><figcaption>Apache Jackrabbit Oak — Architecture</figcaption></figure><p><strong>Walking through the lifecycle:</strong></p><blockquote><em>When your Java code uses the JCR API, it talks to the </em><strong><em>Oak Core</em></strong><em>, which acts as the traffic cop enforcing permissions and sessions. If you fire a query, the </em><strong><em>Query Engine</em></strong><em> intercepts it and immediately checks the </em><strong><em>/oak:index</em></strong><em> to avoid catastrophic tree traversals. Finally, when data needs to be saved or retrieved, Oak delegates the physical disk operations to the configured </em><strong><em>NodeStore</em></strong><em>—most commonly the append-only </em><strong><em>TarMK</em></strong><em>.</em></blockquote><p><strong>Oak</strong> is the silent foundation beneath everything AEM does. Every page an author publishes, every package <strong>FileVault</strong> installs, every Sling resource that gets written — it all ends here, in a segment record inside a .tar file on disk.</p><p>We now understand the full content lifecycle from deployment to persistence. But what happens after <strong>Oak</strong> writes that node? How does that content travel from the Author instance to the Publish tier — and what stands between Publish and the end user?</p><p><em>Series 3 coming soon…</em></p><h3>The AEM Internals Masterclass: OSGi, Sling &amp; Oak</h3><p><em>A quick-reference series on the internal mechanics of </em><strong><em>service wiring</em></strong><em>, </em><strong><em>URL resolution</em></strong><em>, and </em><strong><em>content persistence</em></strong><em>.</em></p><p>Part 1 → <a href="https://medium.com/@bkkothari2255/under-the-hood-of-the-service-registry-aem-developers-guide-to-osgi-annotations-493721b83d35">Under the hood of the Service Registry: AEM Developer’s Guide to OSGi Annotations</a></p><p>Part 2 → <a href="https://medium.com/@bkkothari2255/under-the-hood-of-sling-resource-resolution-aem-developers-guide-to-url-routing-e9d898473d1a">Under the hood of Sling Resource Resolution: AEM Developer’s Guide to URL Routing</a></p><p><strong>Part 3 →</strong> <a href="https://medium.com/@bkkothari2255/under-the-hood-of-the-jcr-oak-storage-engine-aem-developers-guide-to-nodestore-compaction-4021eb4fd7c1"><strong>Under the hood of the JCR Oak Storage Engine: AEM Developer’s Guide to NodeStore &amp; Compaction</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4021eb4fd7c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Under the hood of Sling Resource Resolution: AEM Developer’s Guide to URL Routing]]></title>
            <link>https://medium.com/@bkkothari2255/under-the-hood-of-sling-resource-resolution-aem-developers-guide-to-url-routing-e9d898473d1a?source=rss-20e3c0874a59------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9d898473d1a</guid>
            <category><![CDATA[aem]]></category>
            <category><![CDATA[aem-developer]]></category>
            <category><![CDATA[sling]]></category>
            <dc:creator><![CDATA[Bhavik Kothari]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 08:36:49 GMT</pubDate>
            <atom:updated>2026-03-16T11:43:01.048Z</atom:updated>
            <content:encoded><![CDATA[<p>In a traditional Java web application like Spring MVC, routing is <strong>code-first</strong>. You write a Controller, map it to a specific URL path (e.g., @GetMapping(&quot;/home&quot;)), and when a request comes in, the server executes that Java method.</p><p>AEM, powered by <strong>Apache Sling</strong>, completely flips this on its head. Sling is <strong>content-first</strong>. When a request hits AEM, the server does not look for a Java class. It looks for a piece of content in the database.</p><p>Let’s break down exactly how Sling magically maps a browser URL to a rendered component.</p><h3>1. URL to Resource (The Content Lookup)</h3><p>Imagine a user navigates to <a href="https://yoursite.com/content/myproject/en/home.html.">https://yoursite.com/content/myproject/en/home.html.</a></p><p>Sling intercepts this URL and uses the ResourceResolver to break it apart. First, it strips away the domain, the extension (.html), and any selectors. It takes the raw path—/content/myproject/en/home—and searches the JCR database for a matching node.</p><p>In Sling terminology, everything is a <strong>Resource</strong>. If the ResourceResolver finds that node, it pulls it into memory. <em>Notice that no Java code has executed yet to handle the routing; we merely found a database record.</em></p><h3>2. Resource to Script (The Rendering Engine)</h3><p>Now that Sling has the Resource, how does it know what HTML to render?</p><p>Sling inspects the Resource’s properties, specifically looking for the holy grail of AEM routing: <strong>sling:resourceType</strong>. Let&#39;s say our home page node has sling:resourceType = &quot;myproject/components/page&quot;.</p><p>Sling takes that string and begins a search path, looking for a matching component script. By default, it searches in this order:</p><ol><li>/apps/myproject/components/page/ (Your custom code)</li><li>/libs/myproject/components/page/ (Out-of-the-box Adobe code)</li></ol><p>If it finds page.html (an HTL script) or page.jsp inside that folder, it executes the script, hands it the Resource data, and sends the compiled HTML back to the browser.</p><blockquote><em>Pro-tip: This is why headless AEM is so elegant. If the request was for </em><em>.json instead of </em><em>.html, Sling simply looks for a JSON exporter servlet registered to that exact same </em><em>sling:resourceType, leaving your content hierarchy completely untouched!</em></blockquote><h3>3. The Inheritance Chain (sling:resourceSuperType)</h3><p>What if Sling searches your /apps/ folder and the script <em>isn&#39;t there</em>?</p><p>This is where the true power of AEM Core Components comes in. If you inspect your custom component node at /apps/myproject/components/page, you will often see a property called <strong>sling:resourceSuperType</strong> pointing to something like core/wcm/components/page/v3/page.</p><p>This creates a fallback inheritance chain. Sling says: <em>“Okay, the developer didn’t write a custom HTL script for this component. Let me check its super-type.”</em> It traverses to the Core Component path and executes the Adobe-provided script instead. This allows you to inherit thousands of lines of robust backend logic and frontend markup while only overriding the specific files you want to change.</p><h3>4. The Code: ResourceResolver in Action</h3><p>When you are writing backend OSGi services or Sling Models, you interact with this routing engine programmatically. Here is what it looks like to resolve a path and check its type:</p><pre>import org.apache.sling.api.resource.Resource;<br>import org.apache.sling.api.resource.ResourceResolver;<br><br>public void analyzeContent(ResourceResolver resolver, String path) {<br>    // 1. Map the string path to a Sling Resource<br>    Resource resource = resolver.getResource(path);<br>    <br>    if (resource != null) {<br>        // 2. Check the component routing type<br>        boolean isPage = resource.isResourceType(&quot;myproject/components/page&quot;);<br>        <br>        // 3. Adapt the raw resource into a strongly typed Sling Model<br>        MyPageModel pageModel = resource.adaptTo(MyPageModel.class);<br>    }<br>}</pre><blockquote><em>Writing unit tests for this? In JUnit 5, you don’t need a live server. Use </em><em>aemContext.create().resource(...) to instantly mock the JCR tree and test your resolution logic!</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*2X7SAb2qt6-QJvYMIDzp3w.png" /><figcaption>The URL Routing Lifecycle</figcaption></figure><p><strong>Walking through the lifecycle:</strong></p><blockquote><em>The browser requests a URL ending in </em><em>.html. Sling translates that URL into a physical JCR Node (the Resource) and reads its </em><em>sling:resourceType. It then hunts for a matching rendering script in </em><em>/apps/. If the custom script is missing, Sling gracefully falls back to the </em><em>sling:resourceSuperType to borrow the rendering logic from a Core Component.</em></blockquote><p>We now understand how AEM wires its Java backend together (<strong>OSGi</strong>) and how it routes web traffic to specific content components (<strong>Sling</strong>). But where is this content actually living?</p><p>Underneath <strong>FileVault, OSGi, and Sling </strong>sits a massive, highly optimized <strong>NoSQL storage engine </strong>we are going to crack open the <strong>JCR Oak Storage Engine</strong> and discover how AEM actually saves nodes to disk!</p><h3>The AEM Internals Masterclass: OSGi, Sling &amp; Oak</h3><p><em>A quick-reference series on the internal mechanics of </em><strong><em>service wiring</em></strong><em>, </em><strong><em>URL resolution</em></strong><em>, and </em><strong><em>content persistence</em></strong><em>.</em></p><p>Part 1 → <a href="https://medium.com/@bkkothari2255/under-the-hood-of-the-service-registry-aem-developers-guide-to-osgi-annotations-493721b83d35">Under the hood of the Service Registry: AEM Developer’s Guide to OSGi Annotations</a></p><p><strong>Part 2 → </strong><a href="https://medium.com/@bkkothari2255/under-the-hood-of-sling-resource-resolution-aem-developers-guide-to-url-routing-e9d898473d1a"><strong>Under the hood of Sling Resource Resolution: AEM Developer’s Guide to URL Routing</strong></a></p><p>Part 3 → <a href="https://medium.com/@bkkothari2255/under-the-hood-of-the-jcr-oak-storage-engine-aem-developers-guide-to-nodestore-compaction-4021eb4fd7c1">Under the hood of the JCR Oak Storage Engine: AEM Developer’s Guide to NodeStore &amp; Compaction</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9d898473d1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Under the hood of the Service Registry: AEM Developer’s Guide to OSGi Annotations]]></title>
            <link>https://medium.com/@bkkothari2255/under-the-hood-of-the-service-registry-aem-developers-guide-to-osgi-annotations-493721b83d35?source=rss-20e3c0874a59------2</link>
            <guid isPermaLink="false">https://medium.com/p/493721b83d35</guid>
            <category><![CDATA[osgi-annotations]]></category>
            <category><![CDATA[aem-architect]]></category>
            <category><![CDATA[aem-developer]]></category>
            <dc:creator><![CDATA[Bhavik Kothari]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 08:35:27 GMT</pubDate>
            <atom:updated>2026-03-16T11:41:48.482Z</atom:updated>
            <content:encoded><![CDATA[<p>In our previous series, we explored how the <strong>Apache Felix framework</strong> resolves bundle dependencies to reach the ACTIVE state. But getting your bundle to start is only half the battle. Once your code is running, how do the different parts of your application actually talk to each other without creating tightly coupled, brittle spaghetti code?</p><p>Welcome to the <strong>OSGi Service Registry</strong>.</p><h3>1. The Dynamic Registry: From Yellow Pages to Uber</h3><p>In a traditional Java application, if Class A needs Class B, you usually hardcode the dependency by instantiating it (new ClassB()). Think of this like having a specific person&#39;s phone number saved in your contacts. You must know exactly who you are calling. If that person changes their number, your call fails (NullPointerException).</p><p><strong>OSGi forces a decoupled approach</strong> using the <strong>Service Registry</strong>.</p><p><strong>The Classic Analogy (The Yellow Pages):</strong> Instead of looking up a specific name, you look up a <strong><em>category</em></strong> (like “Plumbers”). You don’t care about the plumber’s name; you just need anyone <strong>who fulfills the contract</strong> of fixing a pipe.</p><p><strong>The Modern Analogy (Uber / Ride-Sharing):</strong> Think of the OSGi Registry like the Uber app.</p><ul><li><strong>The Interface:</strong> You request an “Uber Go” (The contract: I need a basic car to take me from A to B).</li><li><strong>The Implementation:</strong> You don’t request a specific driver by name. The platform dynamically assigns an available driver who fits that description.</li><li><strong>The Dynamic Swap:</strong> If your assigned driver cancels, the app doesn’t crash. It seamlessly routes your request to the next available driver. You never knew the difference.</li></ul><h3>2. Publishing a Service (@Component)</h3><p>To put a service into the registry, we use <strong>Declarative Services</strong> <strong>(DS)</strong> <strong>annotations</strong>. The most important one is @Component.</p><p>First, you always define an interface. This is the contract you expose to the rest of the application:</p><pre>package com.myproject.core.services;<br><br>public interface ContentAnalysisService {<br>    int countWords(String path);<br>}</pre><p>Next, you create the implementation and publish it using @Component(service = ...).</p><pre>package com.myproject.core.services.impl;<br><br>import com.myproject.core.services.ContentAnalysisService;<br>import org.osgi.service.component.annotations.Component;<br>// This annotation tells OSGi: &quot;Register this class in the Service Registry under the ContentAnalysisService interface.&quot;<br>@Component(service = ContentAnalysisService.class, immediate = true)<br>public class ContentAnalysisServiceImpl implements ContentAnalysisService {<br>    @Override<br>    public int countWords(String path) {<br>        // Implementation logic here...<br>        return 42; <br>    }<br>}</pre><blockquote>Note: <strong>immediate = true</strong> forces the service to start immediately upon bundle activation, rather than waiting to be called. Use this sparingly for lightweight services that need to start early, such as registering a listener, starting a scheduler, or initializing configuration caches. Heavy services should be lazy! <strong>Avoid unnecessary immediacy </strong>and keep <strong>immediate = false </strong>to ensure that system resources are only used when necessary.</blockquote><h3>3. Consuming a Service (@Reference)</h3><p>Now, imagine you have a Sling Servlet that needs to use this word-counting logic. You do not use the new keyword. Instead, you use the @Reference annotation to ask the Service Registry to inject it.</p><pre>package com.myproject.core.servlets;<br><br>import com.myproject.core.services.ContentAnalysisService;<br>import org.osgi.service.component.annotations.Component;<br>import org.osgi.service.component.annotations.Reference;<br>import org.apache.sling.api.servlets.SlingSafeMethodsServlet;<br>@Component(service = javax.servlet.Servlet.class)<br>public class AnalysisServlet extends SlingSafeMethodsServlet {<br>    // The OSGi framework dynamically injects the implementation here<br>    @Reference<br>    private ContentAnalysisService analysisService;<br>    @Override<br>    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) {<br>        // We code against the interface, completely unaware of the implementation class!<br>        int wordCount = analysisService.countWords(request.getResource().getPath());<br>        response.getWriter().write(&quot;Word count: &quot; + wordCount);<br>    }<br>}</pre><blockquote><em>Pro-tip: When writing unit tests for these consumers in JUnit 5, you don’t need a real OSGi container. You can use </em><em>aemContext.registerService() to instantly mock the registry!</em></blockquote><h3>4. The Dynamic Trap (Reference Cardinality)</h3><p>What happens if the ContentAnalysisServiceImpl bundle is suddenly stopped?</p><p>Because of the @Reference annotation, OSGi knows AnalysisServlet depends on it. If the service disappears from the registry, OSGi will dynamically <strong>deactivate</strong> your AnalysisServlet as well, preventing a runtime crash. Your servlet will simply return a 404 until the dependency returns to the registry. <strong>This self-healing, cascading activation is the true power of the OSGi framework</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*F2QzLCwNs2YplU28yKQZrA.png" /><figcaption>The OSGi Injection Lifecycle</figcaption></figure><p><strong>Walking through the lifecycle:</strong></p><blockquote>The ContentAnalysisServiceImpl implements the ContentAnalysisService interface and registers itself into the OSGi Service Registry via @Component. The AnalysisServlet declares a @Reference — it never knows the implementation class, only the interface contract. Felix injects the live instance automatically. If the Provider bundle is ever stopped, Felix removes the service from the registry and cascades the deactivation to the Consumer bundle, preventing a runtime crash. The servlet returns a 404 until the dependency is restored.</blockquote><p>Now that our Java backend service is fully wired together using the <strong>OSGi Service Registry</strong>, how do we actually <strong>expose this data to the web</strong>? When a user types a URL into their browser, how does <strong>AEM know exactly which script or component to run</strong>?</p><h3><strong>The AEM Internals Masterclass: OSGi, Sling &amp; Oak</strong></h3><p><em>A quick-reference series on the internal mechanics of </em><strong><em>service wiring</em></strong><em>, </em><strong><em>URL resolution</em></strong><em>, and </em><strong><em>content persistence</em></strong><em>.</em></p><p><strong>Part 1 → </strong><a href="https://medium.com/@bkkothari2255/under-the-hood-of-the-service-registry-aem-developers-guide-to-osgi-annotations-493721b83d35"><strong>Under the hood of the Service Registry: AEM Developer’s Guide to OSGi Annotations</strong></a></p><p>Part 2 → <a href="https://medium.com/@bkkothari2255/under-the-hood-of-sling-resource-resolution-aem-developers-guide-to-url-routing-e9d898473d1a">Under the hood of Sling Resource Resolution: AEM Developer’s Guide to URL Routing</a></p><p>Part 3 → <a href="https://medium.com/@bkkothari2255/under-the-hood-of-the-jcr-oak-storage-engine-aem-developers-guide-to-nodestore-compaction-4021eb4fd7c1">Under the hood of the JCR Oak Storage Engine: AEM Developer’s Guide to NodeStore &amp; Compaction</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=493721b83d35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Under the hood of the Versioning Trap: AEM Developer’s Guide to package-info.java]]></title>
            <link>https://medium.com/@bkkothari2255/under-the-hood-of-the-versioning-trap-aem-developers-guide-to-package-info-java-a034db589296?source=rss-20e3c0874a59------2</link>
            <guid isPermaLink="false">https://medium.com/p/a034db589296</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[osgi]]></category>
            <category><![CDATA[aem-developer]]></category>
            <category><![CDATA[aem]]></category>
            <dc:creator><![CDATA[Bhavik Kothari]]></dc:creator>
            <pubDate>Wed, 04 Mar 2026 00:53:46 GMT</pubDate>
            <atom:updated>2026-03-04T04:24:47.977Z</atom:updated>
            <content:encoded><![CDATA[<h4>OSGi Runtime vs. Maven Compile Time (The Versioning Trap)</h4><p>As Java developers, we are trained to trust Maven. If the code compiles and the mvn clean install says &quot;BUILD SUCCESS,&quot; we assume the application is ready to run. But in an <strong>OSGi container</strong> like <strong>AEM</strong>, <strong>Maven</strong> is only half the battle. There is a massive difference between <strong>satisfying a compiler</strong> and <strong>satisfying a runtime framework</strong>.</p><h3>1. The Maven Illusion (Compile Time)</h3><p>Your pom.xml is fundamentally a <strong>compile-time tool</strong>. When you define a dependency there, you are telling Maven: <em>&quot;Go to Maven Central, download this JAR, and put it on my classpath so my compiler recognizes the classes.&quot;</em> <strong>Maven</strong> <strong>doesn&#39;t care about your AEM server</strong>. It doesn&#39;t know what versions of what bundles are <strong>currently installed</strong> on your production environment. Its only job is to ensure the <strong>syntax is correct</strong> and <strong>package your code</strong> into a ZIP or JAR.</p><h3>2. The OSGi Reality (Runtime)</h3><p><strong>OSGi (Apache Felix) doesn’t care about your </strong><strong>pom.xml</strong>. Once your bundle is deployed to the server, <strong>the </strong><strong>pom.xml is essentially dead</strong>. <strong>Felix strictly reads the </strong><strong>META-INF/MANIFEST.MF</strong> to figure out what your bundle <strong>needs</strong> (<strong>Import-Package</strong>) and what it <strong>offers</strong> (<strong>Export-Package</strong>).</p><p>Here is the trap: You can bump your project version in your pom.xml from 1.0.0 to 2.0.0. Maven will happily build my-project-2.0.0.jar. However, if another bundle on the server relies on a specific <em>Java package</em> (folder) inside your project, <strong>OSGi versioning</strong> happens at the <strong>package level</strong>, not the <strong>bundle level</strong>.</p><h3>3. The Missing Link: package-info.java</h3><p>How does the server actually know <strong>what version a specific Java package</strong> (like com.myproject.core.models) is?</p><p>It does not guess. Every folder (package) in an OSGi project that exports APIs should contain a <strong>package-info.java</strong> file. This file uses the <strong>@Version</strong> annotation to explicitly declare the <strong>semantic version</strong> of the code within that specific directory.</p><pre>@Version(&quot;2.1.0&quot;)<br>package com.myproject.core.models;<br><br>import org.osgi.annotation.versioning.Version;</pre><p><strong>The workflow looks like this:</strong></p><ol><li>You make a breaking change to an interface in com.myproject.core.models.</li><li>You update the pom.xml to 2.0.0 (Compile-time update).</li><li><strong>Crucial Step:</strong> You update the package-info.java in that specific folder to @Version(&quot;2.0.0&quot;).</li><li>During the build, the Bnd plugin reads that annotation and writes com.myproject.core.models;version=&quot;2.0.0&quot; into the Export-Package header of the MANIFEST.MF.</li><li><strong>At runtime</strong>, the OSGi framework reads the manifest and updates the system registry.</li></ol><p>If you forget step 3, Maven will build perfectly, but the OSGi framework will still advertise the old version (1.0.0) to the rest of the server. Other bundles expecting the new 2.0.0 features will fail to resolve, resulting in broken dependencies and stalled services.</p><figure><img alt="Compile-Time vs. Runtime: How package-info.java bridges the gap between Maven builds and the OSGi Service Registry" src="https://cdn-images-1.medium.com/max/1024/1*ktzKCZeyTO7i1Kg8OIYsYg.png" /><figcaption>Compile-Time vs. Runtime: How package-info.java bridges the gap between Maven builds and the OSGi Service Registry</figcaption></figure><blockquote><strong>Walking through the lifecycle:</strong></blockquote><blockquote><em>As illustrated in the diagram, the versioning process spans two entirely separate phases. During </em><strong><em>Compile Time</em></strong><em>, your Java source code and </em><em>pom.xml are digested by the Maven compiler to create your </em><em>.class files. Crucially, the Bnd Plugin steps in here to read your </em><em>package-info.java file. It acts as the bridge, translating your </em><em>@Version annotation directly into the </em><em>Export-Package header of your </em><em>MANIFEST.MF.</em></blockquote><blockquote><em>Once deployed to the </em><strong><em>Runtime Phase</em></strong><em>, the rules change. Apache Felix completely ignores your Maven setup. It reads </em>only<em> the </em><em>MANIFEST.MF to advertise your exact package version to the OSGi Service Registry, ensuring other bundles can safely consume your updated API.</em></blockquote><h3>The AEM Archetype Illusion: Who Actually Creates This File?</h3><p>A common trap developers fall into is assuming that the framework or the Maven build automatically generates the package-info.java file. <strong>It does not.</strong> As a developer, it is entirely your manual responsibility to create this file and manage its @Version annotation whenever you create a new Java package (folder) that exposes APIs or models to other bundles. The Maven Bnd plugin <strong>merely <em>reads</em></strong> this file during the build to <strong>populate the </strong><strong>MANIFEST.MF</strong>; it will never create it for you.</p><p><strong>So why do so many developers think it’s automated?</strong> The confusion usually stems from the official AEM Project Archetype. When you scaffold a fresh AEM project, the archetype script automatically creates a package-info.java file inside your default core packages. Because it is sitting there from day one, it creates a false sense of security.</p><p>The trap snaps shut when you create a brand new package — for example, com.myproject.core.utils. If you forget to manually add package-info.java to that new folder, the Bnd plugin has nothing to read. Your code will compile perfectly, but the OSGi framework will fail to export your new utilities to the rest of the server, leaving you with broken runtime dependencies.</p><h3>4. The pom.xml Connection: Instructions vs. Versions</h3><p>If package-info.java holds the version number, why do we sometimes see &lt;Export-Package&gt; and &lt;Import-Package&gt; explicitly defined in the pom.xml under the bnd-maven-plugin (or maven-bundle-plugin)?</p><p>They work together as a two-part system:</p><p>Part A: The pom.xml defines the Rules (What to export): <strong>The </strong><strong>pom.xml defines the <em>Rules</em> (What to export):</strong> In your POM, you configure the plugin to tell it which folders are legally allowed to be exposed to the OSGi server. For example:</p><pre>&lt;plugin&gt;<br>    &lt;groupId&gt;biz.aQute.bnd&lt;/groupId&gt;<br>    &lt;artifactId&gt;bnd-maven-plugin&lt;/artifactId&gt;<br>    &lt;configuration&gt;<br>        &lt;bnd&gt;<br>            Export-Package: com.myproject.core.models.*, com.myproject.core.api.*<br>            &lt;/bnd&gt;<br>    &lt;/configuration&gt;<br>&lt;/plugin&gt;</pre><p>This tells the build: <em>“Only expose packages that match these paths. Hide everything else inside the bundle.”</em></p><p><strong>Part B:</strong> The package-info.java defines the Data (The Version):</p><p>The POM tells the plugin <em>where</em> to look, but it doesn&#39;t tell it the version. When the plugin processes the com.myproject.core.models folder, it looks for the package-info.java file to answer the question: <em>&quot;Okay, I am exporting this, but what version is it?&quot;</em></p><p><strong>The Final Merge:</strong> The Bnd plugin marries these two pieces of information together. It takes the instruction from the pom.xml and the @Version(&quot;2.1.0&quot;) from the package-info.java, and writes the final, resolved string into your META-INF/MANIFEST.MF:</p><p>Export-Package: com.myproject.core.models;version=&quot;2.1.0&quot;</p><p><strong>What about </strong><strong>&lt;Import-Package&gt; in the POM?</strong> Most of the time, you don&#39;t actually need to write &lt;Import-Package&gt; in your pom.xml. The Bnd plugin is smart enough to scan your compiled .class files, see what external Java packages your code is using, and automatically generate the Import-Package list in the manifest. You generally only override &lt;Import-Package&gt; in the pom.xml when you need to force a specific behavior, like making a dependency optional (e.g., resolution:=optional) or enforcing a highly specific version range that overrides the default math.</p><h3>5. The Hardcoding Anti-Pattern: Can’t I just put the version in the POM?</h3><p>At this point, you might be thinking: <em>“If the </em><em>pom.xml handles the Export-Package instruction anyway, can&#39;t I just hardcode the version string right there and delete </em><strong><em>package-info.java</em></strong><em> entirely?&quot;</em></p><p>Technically, yes. The Bnd plugin will allow you to do this:</p><pre>&lt;plugin&gt;<br>    &lt;groupId&gt;biz.aQute.bnd&lt;/groupId&gt;<br>    &lt;artifactId&gt;bnd-maven-plugin&lt;/artifactId&gt;<br>    &lt;configuration&gt;<br>        &lt;bnd&gt;<br>            Export-Package: com.myproject.core.models.*;version=&quot;2.1.0&quot;<br>        &lt;/bnd&gt;<br>    &lt;/configuration&gt;<br>&lt;/plugin&gt;</pre><p><strong>Why is this a terrible idea?</strong> It destroys the core benefit of OSGi: <strong>Granular Semantic Versioning.</strong></p><p>In a healthy AEM architecture, versions are applied at the <em>package</em> level, not the <em>bundle</em> level. Imagine your bundle exports two packages:</p><ul><li>com.myproject.core.utils (Hasn&#39;t changed in months)</li><li>com.myproject.core.models (Just had a massive, breaking change)</li></ul><p>If you use package-info.java, you can bump the models package to 2.0.0 while leaving the utils package safely at 1.0.0. Any other bundle on the server that only relies on your utils will continue running perfectly without needing to be recompiled or re-tested against a new version.</p><p>If you hardcode the version in the pom.xml using a wildcard (e.g., Export-Package: com.myproject.core.*;version=&quot;${project.version}&quot;), you force <em>every single package</em> to inherit that new version. You have now falsely advertised to the OSGi framework that utils had a breaking change. Every bundle relying on utils will suddenly be blocked by the framework and stuck in the INSTALLED state until someone updates their Import-Package rules to match your unnecessary version bump.</p><p>By relying on package-info.java, you keep your versions strictly isolated to the exact folders where the code actually changed, keeping your OSGi ecosystem stable and untangled.</p><p>As we’ve explored, relying purely on the pom.xml creates a dangerous blind spot between compile-time success and runtime stability. By taking manual ownership of your package-info.java files and embracing granular semantic versioning, you ensure that your code doesn&#39;t just compile—it resolves perfectly within the OSGi service registry.</p><p>That wraps up this four-part masterclass! We’ve looked under the hood of AEM’s most critical infrastructure: cracking open the FileVault data model, navigating OSGi dependency resolution, controlling the “blast radius” with workspace filters, and finally, bridging the gap between Maven and the runtime environment.</p><p><strong>Remember: Maven might build the bundle, but </strong><strong>package-info.java builds the trust. Don&#39;t let your OSGi framework guess your version.</strong></p><h3>The AEM Internals Masterclass: FileVault &amp; OSGi</h3><p><em>This article is part of a quick-reference series for AEM developers diving into the internal mechanics of </em><strong><em>package management</em></strong><em> and </em><strong><em>bundle resolution</em></strong><em>.</em></p><p>Part 1: <a href="https://medium.com/@bkkothari2255/under-the-hood-of-content-packages-aem-developers-guide-to-filevault-structure-340e2e87f581">Under the hood of Content Packages: AEM Developer’s Guide to FileVault Structure</a></p><p>Part 2: <a href="https://medium.com/@bkkothari2255/under-the-hood-of-osgi-aem-developers-guide-to-import-package-and-security-enforcement-3ca723ce4a18">Under the hood of OSGi: AEM Developer’s Guide to Import-Package and Security Enforcement</a></p><p>Part 3: <a href="https://medium.com/@bkkothari2255/under-the-hood-of-content-collisions-aem-developers-guide-to-workspace-filters-and-import-modes-1246013a5185">Under the hood of the Blast Radius: AEM Developer’s Guide to Workspace Filters and Import Modes</a></p><p><strong>Part 4: </strong><a href="https://medium.com/@bkkothari2255/under-the-hood-of-the-versioning-trap-aem-developers-guide-to-package-info-java-a034db589296"><strong>Under the hood of the Versioning Trap: AEM Developer’s Guide to package-info.java</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a034db589296" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Under the hood of Content Collisions: AEM Developer’s Guide to Workspace Filters and Import Modes]]></title>
            <link>https://medium.com/@bkkothari2255/under-the-hood-of-content-collisions-aem-developers-guide-to-workspace-filters-and-import-modes-1246013a5185?source=rss-20e3c0874a59------2</link>
            <guid isPermaLink="false">https://medium.com/p/1246013a5185</guid>
            <category><![CDATA[aem-features]]></category>
            <category><![CDATA[aem-developer]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[aem-architect]]></category>
            <dc:creator><![CDATA[Bhavik Kothari]]></dc:creator>
            <pubDate>Tue, 03 Mar 2026 19:02:53 GMT</pubDate>
            <atom:updated>2026-03-04T04:25:59.990Z</atom:updated>
            <content:encoded><![CDATA[<h3>The “Blast Radius” (Filters &amp; Import Modes)</h3><p>When you install a FileVault package, you are effectively merging a serialized offline database (the ZIP) with a live, running database (the JCR). If you aren’t careful, this collision can overwrite critical configurations or delete user-generated content.</p><p>FileVault manages this “blast radius” using two distinct mechanisms: <strong>Workspace Filters</strong> (where we are allowed to touch) and <strong>Import Modes</strong> (how we touch it).</p><figure><img alt="decision tree FileVault uses when it encounters a path" src="https://cdn-images-1.medium.com/max/995/1*Sz9XiJGOiBn9yWgF5viJ_A.png" /><figcaption>decision tree <strong>FileVault</strong> uses when it encounters a path</figcaption></figure><h3>1. The Workspace Filter (filter.xml)</h3><p>Think of the workspace filter as a strict set of boundary lines. Located at META-INF/vault/filter.xml, it explicitly lists the repository paths the package is authorized to modify. Crucially, this is also where you define the <strong>Import Mode</strong> to tell FileVault <em>how</em> to handle conflicts at those paths.</p><pre>&lt;workspaceFilter version=&quot;1.0&quot;&gt;<br>    &lt;filter root=&quot;/apps/myproject&quot;/&gt;<br>    <br>    &lt;filter root=&quot;/content/myproject/en&quot; mode=&quot;update&quot;&gt;<br>        &lt;exclude pattern=&quot;/content/myproject/en/user-generated(/.*)?&quot;/&gt;<br>    &lt;/filter&gt;<br>    <br>    &lt;filter root=&quot;/conf/myproject/settings&quot; mode=&quot;merge&quot;/&gt;<br>&lt;/workspaceFilter&gt;</pre><p>If a path is not covered by a &lt;filter root=&quot;...&quot;&gt;, FileVault will completely ignore it during installation, even if the payload exists in the jcr_root folder. The filter can also contain &lt;include&gt; and &lt;exclude&gt; rules using regular expressions to fine-tune exactly which sub-nodes are affected.</p><h3>2. Import Modes: Rules of Engagement</h3><p>Once the filter authorizes a path, the <strong>Import Mode</strong> dictates the behavior of the merge. The import mode is defined in the filter file for specific roots. There are three primary modes:</p><ol><li><strong>REPLACE (The Default &amp; Most Dangerous):</strong> This is a destructive, exact-sync mode. If the package contains /apps/myproject/A, and the JCR contains /apps/myproject/A and /apps/myproject/B, FileVault will install A and <strong>delete</strong> B because B was not in the package. It ensures the JCR exactly matches the ZIP within the filter boundary.</li></ol><ul><li><strong>The AEM Horror Story:</strong> &gt; Why is REPLACE so dangerous? Imagine a developer wants to deploy three brand new marketing pages to production. They build a package containing only those three pages under jcr_root/content/myproject/en/.</li><li>They forget to set the mode in the filter.xml, so it defaults to REPLACE.</li><li>When the package installs, FileVault looks at the /content/myproject/en/ boundary. It sees the three new pages in the ZIP, and installs them. Then, it looks at the live production database. It sees 500 existing pages authored by the marketing team over the last two years. Because those 500 pages are <em>not</em> inside the ZIP, FileVault&#39;s exact-sync logic assumes they shouldn&#39;t exist. It permanently deletes all 500 pages in seconds.</li></ul><p><strong>2. MERGE:</strong> This mode is highly conservative. It will only add nodes that do not currently exist in the JCR. If a node already exists in the repository, FileVault leaves it entirely alone, ignoring the version in the package. It never deletes anything.</p><p><strong>3. UPDATE:</strong> A middle ground. It updates existing nodes with the properties from the package and adds new nodes. However, unlike REPLACE, it will <strong>not delete</strong> nodes in the JCR that are missing from the package.</p><blockquote><em>Always use </em><em>UPDATE or </em><em>MERGE when packaging paths under </em><em>/content/.</em></blockquote><h3>The Decision Logic</h3><p>When <strong>FileVault</strong> iterates through the <strong>JCR paths</strong>, it evaluates every single node against a strict decision tree.</p><p><strong>Is the path covered by the Workspace Filter?</strong></p><ul><li>If <strong>no</strong>, ignore it entirely.</li></ul><p><strong>Does the node exist in the ZIP?</strong></p><ul><li>If <strong>yes</strong>, prepare to import.</li></ul><p><strong>Does the node already exist in the JCR?</strong> *</p><ul><li>If <strong>no</strong>: Create it.</li><li>If <strong>yes</strong>: Look at the <strong>Import Mode</strong> (REPLACE overwrites it, MERGE skips it, UPDATE overwrites it).</li></ul><p><strong>What about nodes in the JCR that are missing from the ZIP?</strong></p><ul><li>If the mode is REPLACE, delete them from the live database.</li><li>If the mode is UPDATE or MERGE, leave them alone.</li></ul><h3>The AEM Internals Masterclass: FileVault &amp; OSGi</h3><p><em>This article is part of a quick-reference series for AEM developers diving into the internal mechanics of </em><strong><em>package management</em></strong><em> and </em><strong><em>bundle resolution</em></strong><em>.</em></p><p>Part 1: <a href="https://medium.com/@bkkothari2255/under-the-hood-of-content-packages-aem-developers-guide-to-filevault-structure-340e2e87f581">Under the hood of Content Packages: AEM Developer’s Guide to FileVault Structure</a></p><p>Part 2: <a href="https://medium.com/@bkkothari2255/under-the-hood-of-osgi-aem-developers-guide-to-import-package-and-security-enforcement-3ca723ce4a18">Under the hood of OSGi: AEM Developer’s Guide to Import-Package and Security Enforcement</a></p><p><strong>Part 3: </strong><a href="https://medium.com/@bkkothari2255/under-the-hood-of-content-collisions-aem-developers-guide-to-workspace-filters-and-import-modes-1246013a5185"><strong>Under the hood of the Blast Radius: AEM Developer’s Guide to Workspace Filters and Import Modes</strong></a></p><p><strong>Part 4:</strong> <a href="https://medium.com/@bkkothari2255/under-the-hood-of-the-versioning-trap-aem-developers-guide-to-package-info-java-a034db589296">Under the hood of the Versioning Trap: AEM Developer’s Guide to package-info.java</a></p><h3>What’s Next in the Masterclass?</h3><p>By mastering workspace filters and import modes, you ensure your packages never accidentally wipe out a production database. But safely installing the package is only part of the battle. <strong>How does the server actually know which version of your Java code to run?</strong></p><p><strong>Continue to Part 4:</strong> <a href="https://medium.com/@bkkothari2255/under-the-hood-of-the-versioning-trap-aem-developers-guide-to-package-info-java-a034db589296">Under the hood of the Versioning Trap: AEM Developer’s Guide to package-info.java</a> to discover the massive difference between a successful <strong>Maven build and a stable OSGi runtime</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1246013a5185" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Under the Hood of OSGi: AEM Developer’s Guide to Import-Package and Security Enforcement]]></title>
            <link>https://medium.com/@bkkothari2255/under-the-hood-of-osgi-aem-developers-guide-to-import-package-and-security-enforcement-3ca723ce4a18?source=rss-20e3c0874a59------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ca723ce4a18</guid>
            <category><![CDATA[osgi]]></category>
            <category><![CDATA[aem-developer]]></category>
            <category><![CDATA[aem-architect]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[aem]]></category>
            <dc:creator><![CDATA[Bhavik Kothari]]></dc:creator>
            <pubDate>Mon, 02 Mar 2026 17:08:27 GMT</pubDate>
            <atom:updated>2026-03-04T04:26:23.203Z</atom:updated>
            <content:encoded><![CDATA[<h3>OSGi Dependency Resolution (The Gatekeeper)</h3><p>In a standard Java application, missing a dependency usually means you get a spectacular ClassNotFoundException at runtime, crashing the process.</p><p><strong>AEM</strong> and <strong>Apache Sling</strong> handle things differently. They use the <strong>OSGi (Open Services Gateway initiative)</strong> framework, which relies on a <strong>strict</strong>, <strong>dynamic dependency resolution process</strong>.</p><p>Before your <strong>Sling Distribution</strong> code — or any custom bundle — is allowed to execute, the <strong>OSGi framework</strong> must verify that every single package it needs is <strong>present</strong>, <strong>active</strong>, and mathematically <strong>compatible</strong>.</p><figure><img alt="OSGi Resolution" src="https://cdn-images-1.medium.com/max/573/1*2xmxUdenNKRohKnRQRFXhA.png" /><figcaption><a href="https://gist.github.com/bkkothari2255/9807c42f1d31577decaf6802603ce60f#file-osgi-resolution-state-machine-md">OSGi Resolution State Machine</a></figcaption></figure><h3>The Contract: pom.xml to MANIFEST.MF</h3><p>When you define a dependency in your Maven pom.xml, you are essentially just <strong>satisfying the compiler</strong>. But AEM&#39;s OSGi framework doesn&#39;t read your POM. Instead, the Maven Bundle Plugin (or Bnd plugin) <strong>translates</strong> those <strong>build-time requirements into a strict OSGi runtime contract </strong>located inside your <strong>compiled bundle</strong> at META-INF/MANIFEST.MF.</p><p>If you were to unzip your compiled .jar file and open that manifest in a text editor, you would see a raw key-value dictionary. The two most critical headers for dependency resolution are:</p><ol><li><strong>Export-Package:</strong> The code <em>this</em> bundle is offering to the rest of the server.</li><li><strong>Import-Package:</strong> The exact Java packages <em>this</em> bundle needs from the server to survive.</li></ol><p>Here is what a real MANIFEST.MF snippet looks like:</p><pre>Manifest-Version: 1.0<br>Bundle-SymbolicName: com.myproject.core<br>Bundle-Version: 1.0.0<br>Export-Package: com.myproject.core.models;version=&quot;1.0.0&quot;<br>Import-Package: org.apache.jackrabbit.vault.packaging;version=&quot;[3.4.0,4.0.0)&quot;,<br> org.osgi.framework;version=&quot;[1.8,2)&quot;</pre><h3>Decoding the OSGi Version Math</h3><p>Notice the version string attached to the FileVault package: [3.4.0,4.0.0). This isn&#39;t just a suggestion; it is a <strong>strict mathematical range</strong>.</p><p>OSGi uses standard interval notation to define API compatibility:</p><ul><li><strong>Square Brackets </strong><strong>[ or </strong><strong>]</strong> mean <strong>Inclusive</strong> (the exact version is allowed).</li><li><strong>Parentheses </strong><strong>( or </strong><strong>)</strong> mean <strong>Exclusive</strong> (up to, but <em>not</em> including, this version).</li></ul><p>Therefore, [3.4.0, 4.0.0) translates to: <em>&quot;</em><strong><em>This bundle requires FileVault version 3.4.0 or higher, up to but absolutely excluding 4.0.0.</em></strong><em>&quot;</em></p><p><strong>Why exclude </strong><strong>4.0.0?</strong> Semantic versioning dictates that a major version bump (from 3.x to 4.x) introduces breaking API changes. The Bnd plugin automatically caps the range at the next major version to prevent your code from executing—and inevitably crashing—on an incompatible framework.</p><h3>How OSGi Resolves Dependencies Under the Hood</h3><p>When you deploy your bundle to the server, it enters the <strong>INSTALLED</strong> state. It does not run yet.</p><p>The <strong>Apache Felix</strong> <strong>framework</strong> acts as a <strong>matchmaker</strong>. It reads your Import-Package header and scans the server for another active bundle that exports org.apache.jackrabbit.vault.packaging within that exact [3.4.0, 4.0.0) mathematical range.</p><ul><li><strong>If a match is found:</strong> Your bundle transitions to the <strong>RESOLVED</strong> state, and eventually to <strong>ACTIVE</strong> (meaning it is running).</li><li><strong>If a match is NOT found:</strong> Your bundle is trapped in the <strong>INSTALLED</strong> state. The framework physically blocks your code from starting.</li></ul><h3>Enforcing Security: Rejecting Insecure Versions</h3><p>So, how does changing a version in your pom.xml actively protect the server?</p><p>Let’s say an older version of <strong>FileVault</strong> (e.g., version 3.1.2) has a known security vulnerability. To protect the system, you update your project’s pom.xml to require <strong>FileVault</strong> 3.4.0 or higher.</p><p>When you compile, the <strong>bnd plugin</strong> writes that exact version range into the Import-Package header: version=&quot;[3.4.0,4.0.0)&quot;.</p><p>If an administrator tries to install your new <strong>Sling Distribution bundle</strong> on an older, unpatched server running <strong>FileVault</strong> 3.1.2, <strong>the OSGi framework intervenes.</strong> <strong>Felix</strong> sees that 3.1.2 does not fall within your required mathematical range [3.4.0, 4.0.0).</p><p>Because the <strong>strict OSGi contract is broken</strong>,<strong> Felix refuses to resolve your bundle</strong>. It stays in the INSTALLED state, effectively rejecting the deployment and preventing your code from executing on top of an insecure, vulnerable foundation.</p><h3>The AEM Internals Masterclass: FileVault &amp; OSGi</h3><p><em>This article is part of a quick-reference series for AEM developers diving into the internal mechanics of </em><strong><em>package management</em></strong><em> and </em><strong><em>bundle resolution</em></strong><em>.</em></p><p>Part 1: <a href="https://medium.com/@bkkothari2255/under-the-hood-of-content-packages-aem-developers-guide-to-filevault-structure-340e2e87f581">Under the hood of Content Packages: AEM Developer’s Guide to FileVault Structure</a></p><p><strong><em>Part 2: </em></strong><a href="https://medium.com/@bkkothari2255/under-the-hood-of-osgi-aem-developers-guide-to-import-package-and-security-enforcement-3ca723ce4a18"><strong><em>Under the hood of OSGi: AEM Developer’s Guide to Import-Package and Security Enforcement</em></strong></a></p><p>Part 3: <a href="https://medium.com/@bkkothari2255/under-the-hood-of-content-collisions-aem-developers-guide-to-workspace-filters-and-import-modes-1246013a5185">Under the hood of the Blast Radius: AEM Developer’s Guide to Workspace Filters and Import Modes</a></p><p>Part 4: <a href="https://medium.com/@bkkothari2255/under-the-hood-of-the-versioning-trap-aem-developers-guide-to-package-info-java-a034db589296">Under the hood of the Versioning Trap: AEM Developer’s Guide to package-info.java</a></p><h3>What’s Next in the Masterclass?</h3><p>We now know how FileVault packages are structured, and how the OSGi framework ensures the Java code inside them is safe to run. But what happens when the content payload of that package collides with the live database?</p><p>If you aren’t careful, installing a package can accidentally delete gigabytes of user-generated content.</p><p><strong>Continue to Part 3:</strong> <a href="https://medium.com/@bkkothari2255/under-the-hood-of-content-collisions-aem-developers-guide-to-workspace-filters-and-import-modes-1246013a5185">Under the hood of the Blast Radius: AEM Developer’s Guide to Workspace Filters and Import Modes</a> to learn how to control the damage during a package installation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ca723ce4a18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Under the Hood of Content Packages: AEM Developer’s Guide to FileVault Structure]]></title>
            <link>https://medium.com/@bkkothari2255/under-the-hood-of-content-packages-aem-developers-guide-to-filevault-structure-340e2e87f581?source=rss-20e3c0874a59------2</link>
            <guid isPermaLink="false">https://medium.com/p/340e2e87f581</guid>
            <category><![CDATA[aem-developer]]></category>
            <category><![CDATA[sling]]></category>
            <category><![CDATA[adobe-experience-manager]]></category>
            <dc:creator><![CDATA[Bhavik Kothari]]></dc:creator>
            <pubDate>Mon, 02 Mar 2026 16:39:37 GMT</pubDate>
            <atom:updated>2026-03-04T04:26:55.236Z</atom:updated>
            <content:encoded><![CDATA[<h3>Anatomy of a Package (The Data Model)</h3><p>At its core, a <strong>FileVault</strong> package is just a ZIP file. But to a <strong>Java Content Repository (JCR)</strong>, it’s a highly structured serialization of a database tree. When you crack open a .zip package, you are essentially looking at a <strong>freeze-frame of a repository&#39;s state</strong>, translated into standard file system concepts (files, folders, and XML).</p><p>There are two primary top-level directories in any valid FileVault package: the <strong>jcr_root</strong> and the <strong>META-INF</strong>. Let&#39;s break down exactly what they do.</p><figure><img alt="the transformation process between a physical FileVault ZIP archive and a live Java Content Repository (JCR)" src="https://cdn-images-1.medium.com/max/1024/1*_DPFuP5UaXoa6oluAcV4Jw.png" /><figcaption>the transformation process between a physical <strong>FileVault ZIP</strong> archive and a live <strong>Java Content Repository </strong>(JCR) Nodes</figcaption></figure><blockquote><em>At the top level, the ZIP archive bifurcates into two distinct pathways: </em><strong><em>Control </em></strong><em>and </em><strong><em>Payload</em></strong><em>.</em></blockquote><blockquote><em>On the left (</em><strong><em>Control</em></strong><em>), the </em><em>META-INF/vault/ directory acts as the gatekeeper. It highlights the </em><em>properties.xml (handling bundle dependencies and package identity) and the </em><em>filter.xml (acting as the boundary overlay that dictates which JCR paths are touched).</em></blockquote><blockquote><em>On the right (</em><strong><em>Payload</em></strong><em>), the </em><em>jcr_root/ directory demonstrates the physical-to-database mapping logic.</em></blockquote><h3>1. jcr_root/: The Physical Payload</h3><p>This folder is the actual content. The directory structure inside jcr_root mirrors the exact path hierarchy of the repository.</p><p>Here is how the physical file system maps to the JCR database:</p><ul><li><strong>Standard Folders:</strong> A physical directory like jcr_root/apps/myproject/ translates to a standard node in the JCR (usually nt:folder or sling:Folder).</li><li><strong>Standard Files:</strong> A physical file like style.css becomes an nt:file node in the JCR, with a child jcr:content node containing the binary data.</li><li><strong>The Magic of </strong><strong>.content.xml:</strong> The JCR holds complex data structures (like cq:Page, cq:Component, or custom properties) that don&#39;t exist in standard file systems. FileVault solves this using .content.xml files. When FileVault sees a folder accompanied by a .content.xml, it reads the XML to assign the correct jcr:primaryType and properties to that node, rather than just treating it as a dumb folder.</li></ul><p><strong>Example Mapping:</strong> If you have a component at /apps/ui/hero, the package structure looks like this:</p><pre>jcr_root/<br>└── apps/<br>    └── ui/<br>        └── hero/<br>            ├── .content.xml  &lt;-- Tells the JCR: &quot;I am a cq:Component with jcr:title=&#39;Hero&#39;&quot;<br>            ├── hero.html     &lt;-- The actual rendering script<br>            └── _cq_dialog<br>                └── .content.xml    &lt;-- Defines the authoring interface</pre><h3>2. META-INF/vault/: The Brains and Instructions</h3><p>If jcr_root is the <em>what</em>, META-INF/vault is the <em>how</em>. This folder contains the metadata and instructions that the package manager needs to safely install the payload.</p><p>Key files inside this directory include:</p><ul><li><strong>properties.xml:</strong> The identity of the package. It stores the package name, version, group, built-by information, and any package dependencies (e.g., &quot;Do not install this until package X is installed&quot;).</li><li><strong>filter.xml (The Workspace Filter):</strong> This is arguably the most critical file. It defines the &quot;Blast Radius.&quot; It tells the package manager exactly which paths in the jcr_root are allowed to be imported, and what <em>rules</em> to apply when conflicts occur (e.g., should it overwrite existing nodes, merge with them, or leave them alone?).</li><li><strong>nodetypes.cnd (The Blueprint):</strong> JCR nodes are built on strict definitions (like cq:Page or nt:unstructured). But what if your application requires a custom data structure? <strong><em>Real-World Scenario:</em></strong> Imagine you are building a strict product catalog, and you define a custom node type called myproj:Product that <em>must</em> contain a sku property. If FileVault tries to import a myproj:Product node but the live JCR has never heard of that type, the import crashes. The .cnd (Compact Node Type Definition) file acts as the blueprint. FileVault reads this file and registers the custom node type with the repository <em>before</em> it attempts to unpack the jcr_root payload.</li><li><strong>privileges.xml (Custom Access Control):</strong> AEM comes with standard privileges (read, write, delete). But sometimes enterprise security requires custom permissions. <strong><em>Real-World Scenario:</em></strong> You build a feature that allows authors to push content directly to an external API, and you want to lock this down with a custom privilege called myproj:publishExternal. You define that custom privilege in this XML file. FileVault registers it with the JCR security manager so that when your package later imports a user group with that specific permission, the server knows exactly what it means.</li></ul><h3>The Import Cycle in Summary</h3><p>When you upload and install this ZIP, the FileVault engine doesn’t just blindly extract files. It reads the properties.xml to check dependencies, validates your payload against the filter.xml blast radius, registers any custom node types or privileges, and <em>then</em> traverses the jcr_root to deserialize the XML back into live database nodes.</p><p>It is a highly orchestrated database merge, masquerading as a simple ZIP extraction.</p><p>Now that we understand how the payload is structured and imported into the JCR, what happens when the Java code inside this package actually tries to run on the server?</p><p>Unlike a standard Java application, AEM doesn’t just let your code execute. It has to pass the gatekeeper.</p><h3>The AEM Internals Masterclass: FileVault &amp; OSGi</h3><p><em>This article is part of a quick-reference series for AEM developers diving into the internal mechanics of </em><strong><em>package management</em></strong><em> and </em><strong><em>bundle resolution</em></strong><em>.</em></p><p><strong><em>Part 1: </em></strong><a href="https://medium.com/@bkkothari2255/under-the-hood-of-content-packages-aem-developers-guide-to-filevault-structure-340e2e87f581"><strong><em>Under the hood of Content Packages: AEM Developer’s Guide to FileVault Structure</em></strong></a></p><p>Part 2: <a href="https://medium.com/@bkkothari2255/under-the-hood-of-osgi-aem-developers-guide-to-import-package-and-security-enforcement-3ca723ce4a18">Under the hood of OSGi: AEM Developer’s Guide to Import-Package and Security Enforcement</a></p><p>Part 3: <a href="https://medium.com/@bkkothari2255/under-the-hood-of-content-collisions-aem-developers-guide-to-workspace-filters-and-import-modes-1246013a5185">Under the hood of the Blast Radius: AEM Developer’s Guide to Workspace Filters and Import Modes</a></p><p>Part 4: <a href="https://medium.com/@bkkothari2255/under-the-hood-of-the-versioning-trap-aem-developers-guide-to-package-info-java-a034db589296">Under the hood of the Versioning Trap: AEM Developer’s Guide to package-info.java</a>What’s Next in the Masterclass?</p><p><strong>Continue to Part 2:</strong> <a href="https://medium.com/@bkkothari2255/under-the-hood-of-osgi-aem-developers-guide-to-import-package-and-security-enforcement-3ca723ce4a18">Under the hood of OSGi: AEM Developer’s Guide to Import-Package and Security Enforcement</a> to see exactly how AEM resolves bundle dependencies at runtime.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=340e2e87f581" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Architect’s Guide to Sling Models: From Annotations to Technical Proofs]]></title>
            <link>https://medium.com/@bkkothari2255/the-architects-guide-to-sling-models-from-annotations-to-technical-proofs-2372355c91e7?source=rss-20e3c0874a59------2</link>
            <guid isPermaLink="false">https://medium.com/p/2372355c91e7</guid>
            <category><![CDATA[aem-architect]]></category>
            <category><![CDATA[aem]]></category>
            <category><![CDATA[aem-sling-models]]></category>
            <category><![CDATA[sling]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Bhavik Kothari]]></dc:creator>
            <pubDate>Sat, 28 Feb 2026 04:09:48 GMT</pubDate>
            <atom:updated>2026-02-28T04:09:48.887Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="sling-models-architect-reference.mmd" src="https://cdn-images-1.medium.com/max/1024/1*Nw3Icj1fFFcJjZQgwnUFuw.png" /></figure><p>Sling Models are the backbone of modern Adobe Experience Manager (AEM) development. They provide an annotation-driven Java framework to map JCR data, OSGi services, and request attributes directly into Plain Old Java Objects (POJOs). This article explores every essential annotation, performance-driven best practices, and the technical evidence supporting them.</p><h4>1. The Core Annotation</h4><p>Every Sling Model must begin with the @Model annotation.</p><ul><li><a href="https://github.com/apache/sling-org-apache-sling-models-api/blob/master/src/main/java/org/apache/sling/models/annotations/Model.java"><strong>@Model</strong></a>: Marks a class or interface as a Sling Model.</li></ul><p><strong>Key Parameters</strong>:</p><ul><li>adaptables: Defines the source object (typically Resource.class or SlingHttpServletRequest.class).</li><li>adapters: Lists the interfaces or classes to which the model can be adapted.</li><li>defaultInjectionStrategy: Sets whether fields are REQUIRED or OPTIONAL by default.</li><li>cache: If true, the model is cached during the lifecycle of the adaptable.</li></ul><h4>2. Comprehensive Annotation</h4><p>Sling Models use specific injectors to retrieve data efficiently.</p><h4>Data Injection Annotations</h4><ul><li><a href="https://github.com/apache/sling-org-apache-sling-models-api/blob/master/src/main/java/org/apache/sling/models/annotations/injectorspecific/ValueMapValue.java"><strong>@ValueMapValue</strong></a>: Injects properties directly from the JCR node (ValueMap).</li><li><a href="https://github.com/apache/sling-org-apache-sling-models-api/blob/master/src/main/java/org/apache/sling/models/annotations/injectorspecific/ChildResource.java"><strong>@ChildResource</strong></a>: Injects a child resource (node) relative to the current resource.</li><li><a href="https://wwhttps//github.com/apache/sling-org-apache-sling-models-api/blob/master/src/main/java/org/apache/sling/models/annotations/injectorspecific/OSGiService.java"><strong>@OSGiService</strong></a>: Injects an OSGi service from the AEM bundle container.</li><li><a href="https://github.com/apache/sling-org-apache-sling-models-api/blob/master/src/main/java/org/apache/sling/models/annotations/injectorspecific/RequestAttribute.java"><strong>@RequestAttribute</strong></a>: Retrieves attributes passed from an HTL data-sly-use statement or a Servlet.</li><li><a href="https://github.com/apache/sling-org-apache-sling-models-api/blob/master/src/main/java/org/apache/sling/models/annotations/injectorspecific/ResourcePath.java"><strong>@ResourcePath</strong></a>: Injects a resource by specifying a path or reading a path from a property.</li><li><a href="https://github.com/apache/sling-org-apache-sling-models-api/blob/master/src/main/java/org/apache/sling/models/annotations/injectorspecific/Self.java"><strong>@Self</strong></a>: Injects the adaptable object itself or an object adapted from it.</li><li><a href="https://github.com/apache/sling-org-apache-sling-models-api/blob/master/src/main/java/org/apache/sling/models/annotations/injectorspecific/SlingObject.java"><strong>@SlingObject</strong></a>: Injects standard Sling objects such as ResourceResolver, SlingHttpServletRequest, or SlingHttpServletResponse.</li></ul><h4>Logic &amp; Behaviour Annotations</h4><ul><li><a href="https://github.com/apache/sling-org-apache-sling-models-api/blob/master/src/main/java/org/apache/sling/models/annotations/Default.java"><strong>@Default</strong></a>: Provides a fallback value (String, Boolean, Integer, etc.) if injection fails.</li><li><a href="https://github.com/apache/sling-org-apache-sling-models-api/blob/master/src/main/java/org/apache/sling/models/annotations/Via.java"><strong>@Via</strong></a>: Instructs the injector to find the value in a different object (e.g., get a property from the resource when the model is adapted from the request).</li><li><a href="https://github.com/apache/sling-org-apache-sling-models-impl/blob/master/src/test/java/org/apache/sling/models/testmodels/classes/TruePostConstructModel.java"><strong>@PostConstruct</strong></a>: Marks a method to execute immediately after all fields are injected. Use this for complex business logic.</li></ul><h4>3. Best Practices and Technical Evidence</h4><p>Following these best practices ensures your AEM backend is performant, stable, and maintainable.</p><h4>I. Use <a href="https://github.com/apache/sling-org-apache-sling-models-api/tree/master/src/main/java/org/apache/sling/models/annotations/injectorspecific">Injector-Specific</a> Annotations</h4><ul><li><strong>Best Practice</strong>: Use @ValueMapValue or @OSGiService instead of the generic @Inject.</li><li><strong>Reason</strong>: Generic injection forces Sling to loop through every registered injector. Specific annotations target the correct injector directly, reducing overhead.</li><li><strong>Technical Proof</strong>: Internal classes like <a href="https://github.com/apache/sling-org-apache-sling-models-impl/blob/master/src/main/java/org/apache/sling/models/impl/injectors/ValueMapInjector.java">ValueMapInjector.java</a> and <a href="https://github.com/apache/sling-org-apache-sling-models-impl/blob/master/src/main/java/org/apache/sling/models/impl/injectors/SlingObjectInjector.java">OSGiServiceInjector.java</a> show that specific injectors are registered to handle these annotations exclusively.</li></ul><h4>II. Default to Optional Strategies</h4><ul><li><strong>Best Practice</strong>: Set defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL.</li><li><strong>Reason</strong>: If a model is REQUIRED (the default) and a single property is missing in the JCR, the entire model fails to instantiate, causing null pointers in HTL.</li><li><strong>Technical Proof</strong>: <a href="https://github.com/apache/sling-org-apache-sling-models-impl/blob/master/src/test/java/org/apache/sling/models/testmodels/classes/ResourceModelWithRequiredField.java">ResourceModelWithRequiredField.java</a> demonstrates that missing properties trigger a MissingElementsException, while <a href="https://github.com/apache/sling-org-apache-sling-models-impl/blob/master/src/test/java/org/apache/sling/models/testmodels/classes/ResourceModelWithRequiredFieldOptionalStrategy.java">ResourceModelWithRequiredFieldOptionalStrategy.java</a> proves that the OPTIONAL strategy allows successful instantiation even with missing data.</li></ul><h4>III. Favor Interface-Based Models</h4><ul><li><strong>Best Practice</strong>: Define an interface for your model and list it in the adapters parameter.</li><li><strong>Reason</strong>: This decouples the API used by HTL from the implementation logic, making unit testing with AEM Mocks significantly easier.</li><li><strong>Technical Proof</strong>: The Sling test suite uses <a href="https://github.com/apache/sling-org-apache-sling-models-impl/blob/master/src/test/java/org/apache/sling/models/testmodels/classes/implextend/SampleServiceInterface.java">SampleServiceInterface.java</a> to verify that HTL can call stable interface methods while the implementation remains private.</li></ul><h4>IV. Enable Caching</h4><ul><li><strong>Best Practice</strong>: Use cache = true in the @Model annotation.</li><li><strong>Reason</strong>: Prevents re-running the injection logic if the model is called multiple times in one request (e.g., a header component used across various scripts).</li><li><strong>Technical Proof</strong>: <a href="https://github.com/apache/sling-org-apache-sling-models-impl/blob/master/src/test/java/org/apache/sling/models/impl/CachingTest.java">CachingTest.java</a> confirms that when cache = true is enabled, the ModelAdapterFactory returns the same Java instance for subsequent adaptation requests of the same object.</li></ul><h4>V. Lightweight Adaptables</h4><ul><li><strong>Best Practice</strong>: Adapt from Resource.class whenever possible.</li><li><strong>Reason</strong>: Adapting from SlingHttpServletRequest is more resource-intensive because it carries headers, cookies, and parameters that are rarely needed for simple component rendering.</li><li><strong>Technical Proof</strong>: Comparison between <a href="https://github.com/apache/sling-org-apache-sling-models-impl/blob/master/src/test/java/org/apache/sling/models/impl/injectors/SlingObjectInjectorResourceTest.java">SlingObjectInjectorResourceTest.java</a> and <a href="https://github.com/apache/sling-org-apache-sling-models-impl/blob/master/src/test/java/org/apache/sling/models/impl/injectors/SlingObjectInjectorRequestTest.java">SlingObjectInjectorRequestTest.java</a> illustrates the simplified injection path when using a Resource.</li></ul><h4>4. Exporter Annotations (Headless &amp; JSON Integration)</h4><p>Sling Models can be automatically serialized into JSON using the Sling Models Exporter framework. This is essential for React/Angular integrations or providing a JSON API for your components.</p><ul><li><a href="https://github.com/apache/sling-org-apache-sling-models-api/blob/master/src/main/java/org/apache/sling/models/annotations/Exporter.java"><strong>@Exporter</strong></a>: Registered at the class level to specify which exporter should handle the model (e.g., name = &quot;jackson&quot;, extensions = &quot;json&quot;).</li><li><a href="https://github.com/apache/sling-org-apache-sling-models-api/blob/master/src/main/java/org/apache/sling/models/annotations/Exporters.java"><strong>@Exporters</strong></a>: A container used if a single model needs to be available via multiple exporters (e.g., different configurations for different output formats).</li><li><a href="https://github.com/apache/sling-org-apache-sling-models-api/blob/master/src/main/java/org/apache/sling/models/annotations/ExporterOption.java"><strong>@ExporterOption</strong></a>: Provides specific configuration to the underlying serializer, such as changing the way dates are formatted or mapping snake_case to camelCase.</li><li><strong>@JsonProperty</strong>: (Jackson-specific) While not a Sling annotation, it is used within Sling Models to rename a field in the resulting JSON output.</li></ul><h4>Best Practices for Exporters</h4><ul><li><strong>Use Interfaces for Exporting</strong>: Always apply the @Exporter annotation to the interface rather than the implementation. This ensures the exported JSON structure remains stable even if the backend logic changes.</li><li><strong>Avoid Serializing Sensitive Data</strong>: Use the @JsonIgnore annotation on fields like ResourceResolver or internal paths that should not be exposed to the front-end.</li><li><strong>Set </strong><strong>SerializationFeature via Options</strong>: Use @ExporterOption to disable features like WRITE_DATES_AS_TIMESTAMPS to ensure your JSON API returns ISO-formatted dates that are easier for front-end developers to consume.</li></ul><p><strong>Proof</strong>: The <a href="https://github.com/apache/sling-org-apache-sling-models-impl/blob/master/src/main/java/org/apache/sling/models/impl/ExportServlet.java">ExportServlet</a> specifically looks for the @Exporter annotation on a model to determine if it should allow a .model.json selector request. If the annotation is missing, the servlet returns a 404 or 406, proving that this annotation is the gatekeeper for the Jackson serialization process.</p><h4>The Architectural Foundation: Sling Adapter Annotations</h4><p>To truly master AEM backends, one must look beneath the high-level Sling Models API to the fundamental <strong>Sling Adapter</strong> framework that powers it. While @Model automates much of the boilerplate, understanding the underlying adapter metadata is what separates a developer from an architect.</p><ul><li><strong>@SlingAdapter</strong>: This is the core metadata annotation for <strong>Adapter Factories</strong>. It explicitly defines the system-level mapping between adaptables (the source objects, such as Resource or SlingHttpServletRequest) and their adapters (the target interfaces or classes).</li><li><strong>@AdapterCondition</strong>: Architects use this to provide a natural language description or specific technical constraints under which an adaptation is valid. This metadata is invaluable for system-wide debugging, as it appears directly in the <strong>Sling Adapter Web Console</strong>.</li><li><strong>@AdapterDeprecated</strong>: A critical tool for lifecycle management, this annotation allows you to systematically mark an adaptation path as deprecated. It serves as a clear signal to the team that a specific model or adaptation logic is slated for removal in future sprints.</li></ul><h4>Technical Proof: The Adapter Factory in Action</h4><ul><li><strong>Reference</strong>: TextLengthIfFitsAdapterFactory.java</li><li><strong>Proof</strong>: The official Apache Sling test suite demonstrates an implementation of an AdapterFactory using the @SlingAdapter and @AdapterCondition annotations. It proves that the system relies on this metadata to map a String adaptable to an Integer adapter only when a specific condition (text length) is met. This is the exact same mechanism used by the ModelAdapterFactory to instantiate your Sling Models at runtime.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2372355c91e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AEM Debugging: How a Single Stuck Sling Job Took Down the Entire DAM]]></title>
            <link>https://medium.com/@bkkothari2255/aem-debugging-how-a-single-stuck-sling-job-took-down-the-entire-dam-69c9678e9982?source=rss-20e3c0874a59------2</link>
            <guid isPermaLink="false">https://medium.com/p/69c9678e9982</guid>
            <category><![CDATA[aem-architect]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[aem]]></category>
            <category><![CDATA[sling]]></category>
            <category><![CDATA[adobe-experience-manager]]></category>
            <dc:creator><![CDATA[Bhavik Kothari]]></dc:creator>
            <pubDate>Fri, 09 Jan 2026 17:10:40 GMT</pubDate>
            <atom:updated>2026-01-09T17:10:40.429Z</atom:updated>
            <content:encoded><![CDATA[<p>It started like any other critical production issue: Users reported that the <strong>AEM Assets (DAM)</strong> console was timing out. Thumbnails weren’t loading, folders wouldn’t open, and the authoring experience had ground to a halt.</p><p>As an AEM architects, our first instinct was to check the usual suspects: Was the Java Heap full?</p><p>Was the CPU pegged?</p><p>Had Online Revision Cleanup failed?</p><p>While Revision Cleanup <em>had</em> failed, the root cause wasn’t a lack of maintenance — it was a silent architectural killer known as <strong>Head-of-Line Blocking</strong>.</p><p>In this article, I’ll walk through how we diagnosed a massive system bottleneck caused by a single stuck replication job, and how this experience led to my recent contribution to Apache Sling to prevent similar resource starvation in the future.</p><h3>The Symptoms: “Index Traversed”</h3><p>The system felt sluggish, but the logs revealed something specific. We saw a flood of <strong>warnings</strong> indicating that a query was traversing thousands of nodes instead of using an <strong>index</strong>.</p><pre>*WARN* ... org.apache.jackrabbit.oak.plugins.index.search.spi.query.FulltextIndex$FulltextPathCursor <br>Index-Traversed 30000 nodes with filter Filter(query=select [jcr:path], [jcr:score], * from [slingevent:Job] as a where [event.job.topic] = &#39;com/day/cq/replication/job/Int-publish--abc0123456&#39; ...)</pre><p>This log entry told a clear story:</p><ul><li><strong>The Target:</strong> The system was querying slingevent:Job nodes (background jobs).</li><li><strong>The Topic:</strong> It was looking for replication jobs targeting a specific publish agent (Int-publish-abc0123456).</li><li><strong>The Failure:</strong> It scanned 30,000+ nodes linearly. This massive traversal was eating up our Disk I/O, causing the entire repository to slow down.</li></ul><p>But why were there 30,000 nodes sitting there?</p><blockquote>Once upon time wisedev said 1 error easy to diagnose then 1000 warnings</blockquote><h3>The Investigation: The Smoking Gun</h3><p>we navigated to the <strong>Sling Jobs Console</strong> (/system/console/slingevent) to see what was clogging the system. The statistics for that specific replication queue were alarming:</p><ul><li><strong>Queued Jobs:</strong> 138</li><li><strong>Failed Jobs:</strong> 281</li><li><strong>Average Waiting Time:</strong> <strong>412 minutes (Wait… nearly 7 hours?)</strong></li></ul><p>The queue status showed it was Type: Ordered and Max Parallel: 1.</p><h3>The Root Cause: Head-of-Line Blocking</h3><p>This is a classic distributed systems problem. AEM Replication agents use <strong>Ordered Queues</strong> to ensure data consistency (e.g., you can’t process a “Delete” event before the “Create” event that preceded it).</p><p>To guarantee this order, the queue is single-threaded (Max Parallel: 1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jK_S0Iiw5Ag_aZZLQ741VQ.png" /><figcaption>Head-of-Line Blocking</figcaption></figure><p>Here is exactly what happened to our server:</p><ol><li><strong>The Blocker:</strong> The first job in the queue tried to replicate to a specific Publish instance (abc0123456). That instance was unreachable (likely network or downtime).</li><li><strong>The Traffic Jam:</strong> Because the queue is <em>Ordered</em>, Job #2 cannot start until Job #1 finishes. Job #1 kept failing and retrying, effectively halting the queue.</li><li><strong>The Accumulation:</strong> While the queue was stuck for 7 hours, new jobs kept piling up in the repository under /var/eventing/jobs.</li><li><strong>The Crash:</strong> AEM’s background “Health Checks” run periodically to count these jobs. Because thousands of job nodes had accumulated, the Health Check query triggered the massive <strong>Index Traversal</strong> we saw in the logs.</li><li><strong>The Consequence:</strong> The traversal exhausted the Disk I/O. This starved the DAM UI (which needs I/O to render thumbnails) and caused the daily Revision Cleanup to fail (0 bytes reclaimed), putting the repository in a death spiral.</li></ol><h3>The Immediate Fix</h3><p>To bring the server back to life, we had to unclog the pipe immediately.</p><ol><li><strong>Stop the Bleeding:</strong> We disabled the specific Replication Agent to stop new jobs from entering the queue.</li><li><strong>Clear the Blockage:</strong> In the Sling Jobs console, we clicked <strong>“Drop All”</strong> on the stuck queue. This physically deleted the job nodes from the repository.</li><li><strong>Recovery:</strong> Once the nodes were gone, the traversal warnings stopped. We manually triggered <strong>Revision Cleanup</strong>, which finally succeeded in reclaiming space.</li></ol><p>The DAM Assets page loaded instantly.</p><h3>The Long-Term Solution: Thread Pool Isolation</h3><p>This incident highlighted a flaw in how we handle background tasks. When one part of the system (Replication) gets backed up, it shouldn’t starve critical resources (like the Default Thread Pool) needed by the rest of the application.</p><p>This inspired my recent contribution to <strong>Apache Sling</strong>. while looking for root cause I went though similar reported issues on Sling project’s jira and found one <a href="https://issues.apache.org/jira/browse/SLING-11026">SLING-11026</a></p><h3>The Epiphany: It’s Not Just About Replication</h3><p>While we fixed the immediate outage by unclogging the Replication queue, the incident taught me a deeper architectural lesson: <strong>Shared resources are dangerous.</strong></p><p>The crash happened because a heavy background process (Replication) was sharing the default system resources. When it choked, it took down everything else (DAM, Health Checks, Maintenance) with it.</p><p>I realised that <strong>Sling Content Distribution (SCD)</strong> — the modern successor to replication often used in AEM as a Cloud Service — was vulnerable to this exact same “Noisy Neighbour” pattern. Its cleanup tasks and discovery services were running on the default Sling scheduler. If a distribution queue ever got stuck like our replication queue did, it would cause the exact same system-wide outage.</p><p>I got chance to fix this architectural vulnerability upstream before it could bite us. I submitted two Pull Requests to the Apache Sling project (Jira: SLING-11026):</p><ul><li><strong>Core Bundle:</strong> <a href="https://github.com/apache/sling-org-apache-sling-distribution-core/pull/73">PR #73</a></li><li><strong>Journal Bundle:</strong> <a href="https://github.com/apache/sling-org-apache-sling-distribution-journal/pull/179">PR #179</a></li></ul><p><strong>The Architectural Change:</strong></p><p>I modified the DistributionPackageBuilderFactory and DiscoveryService to use a <strong>Dedicated Thread Pool</strong> (org-apache-sling-distribution) instead of the default Sling scheduler.</p><pre>// File: DistributionPackageBuilderFactory.java<br><br>// Before: The scheduler configuration had no thread pool defined<br>// (Result: It ran on the &quot;sling-default&quot; pool)<br>props.put(Scheduler.PROPERTY_SCHEDULER_CONCURRENT, false);<br>props.put(Scheduler.PROPERTY_SCHEDULER_PERIOD, cleanupDelay);<br><br>// After: Explicitly assigning the dedicated thread pool<br>props.put(Scheduler.PROPERTY_SCHEDULER_CONCURRENT, false);<br>props.put(Scheduler.PROPERTY_SCHEDULER_PERIOD, cleanupDelay);<br>props.put(Scheduler.PROPERTY_SCHEDULER_THREAD_POOL, &quot;org-apache-sling-distribution&quot;); // &lt;--- The Fix<br><br><br>// File: DiscoveryService.java<br><br>// Before: It was using a custom name &quot;content-distribution&quot; <br>// (or implicit default in older versions)<br>props.put(Scheduler.PROPERTY_SCHEDULER_THREAD_POOL, &quot;content-distribution&quot;);<br><br>// After: Standardizing to &quot;org-apache-sling-distribution&quot; to match the Core bundle<br>props.put(Scheduler.PROPERTY_SCHEDULER_THREAD_POOL, &quot;org-apache-sling-distribution&quot;);</pre><p><strong>Why this matters:</strong> This change ensures that even if the cleanup task (ResourceDistributionPackageCleanup) takes hours to run because of a large repository, it stays in its own &quot;lane.&quot; It will never again hog the threads needed for the DAM UI or System Health Checks.</p><h3>Key Takeaways for AEM Developers</h3><ol><li><strong>Monitor Wait Times, Not Just Failures:</strong> A queue with only 100 items might seem healthy, but if the <strong><em>Wait Time</em></strong> is 400 minutes, your system is broken.</li><li><strong>Beware of Ordered Queues:</strong> They prioritise consistency over availability. If your destination server is flaky, an <strong>Ordered Queue</strong> will take down your Source server.</li><li><strong>Isolate Your Resources:</strong> Whenever you develop background processes (listeners, schedulers, or consumers), ask yourself: <em>“If this hangs, what else dies?”</em> If the answer is “The User Interface,” move it to a dedicated thread pool.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69c9678e9982" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>