Write production-grade Adobe Experience Manager back-end Java for AEM as a Cloud Service (6.5 differences noted) — OSGi Declarative Services, runmode configs with env vars and secrets, Sling servlets and filters, service users via repoinit, outbound HTTP with timeouts, queries and custom Oak indexes, Sling Jobs, workflows and replication.
When agents use itUse this whenever the user writes or debugs an OSGi @Component, @Designate/@ObjectClassDefinition config, a .cfg.json in ui.config, $[env:] or $[secret:] values, a SlingSafeMethodsServlet or SlingAllMethodsServlet, @SlingServletResourceTypes, a Sling filter, ResourceResolverFactory, a service user mapping or repoinit script, HttpClientBuilderFactory, QueryBuilder or JCR-SQL2, an _oak_index definition, JobConsumer, a scheduler that runs on every pod, ResourceChangeListener, WorkflowProcess or Replicator, or asks why code fails on Cloud Service or leaks sessions. Also apply it when porting a 6.5 core bundle to Cloud Service. For tests use `aem-testing`.
Install
Copilot (VS Code, Visual Studio, Copilot CLI and github.com) reads skills from the repository — commit them so the whole team gets them.
npx skills add AGCO-Global/org-skills --skill aem-backend-development -a github-copilot
# or with the org installer (adds .github/skills/aem-backend-development):
npx -y github:AGCO-Global/org-skills add skill aem-backend-development
Uses the open skills CLI. Works with Claude Code, Codex, Cursor, Copilot, Gemini CLI, OpenCode, Windsurf and 60+ others — it asks which agent to install into.
Installs the aem-development-skills plugin, which bundles all AEM / Development skills and keeps them updated.
/plugin marketplace add AGCO-Global/org-skills
/plugin install aem-development-skills@org-skills
# or just this skill, in this repository:
npx skills add AGCO-Global/org-skills --skill aem-backend-development -a claude-code
Use Download .zip above, then upload it under Customize → Skills → Upload skill. Team and Enterprise admins can sync this repo as a plugin marketplace instead.
Installs into .agents/skills/, which Codex reads.
npx skills add AGCO-Global/org-skills --skill aem-backend-development -a codex
Installs into Cursor's skills folder.
npx skills add AGCO-Global/org-skills --skill aem-backend-development -a cursor
Installs into Gemini CLI's skills folder.
npx skills add AGCO-Global/org-skills --skill aem-backend-development -a gemini-cli
Nothing to install. Press Download .zip above, unzip it, and drop the aem-backend-development folder into your tool's skills folder — .claude/skills/, .github/skills/, .cursor/skills/ or .agents/skills/. Step-by-step, per tool: How to use it. For any other tool with rules or custom prompts, Copy SKILL.md and paste it in — it is plain Markdown.
The npx commands need Node.js 20+ and use your normal git sign-in to GitHub, so they work while the repository is private. Without Node.js, see the No Node.js tab — a skill is a folder of Markdown, so copying it in works just as well.
AEM back-end code runs as long-lived OSGi singletons inside an auto-scaled cluster whose pods are recycled at any time. Write every service as if it serves concurrent requests on several pods at once, with an immutable /apps, no admin session and no local disk — code written that way also runs on 6.5.
1. Decide first
Question
Default
Change when
Servlet binding
@SlingServletResourceTypes + selector + extension
Path binding (@SlingServletPaths) only for a resource-less endpoint you also allow-list in Dispatcher; it bypasses resource ACLs
Servlet base class
SlingSafeMethodsServlet (GET/HEAD)
SlingAllMethodsServlet only for state-changing POST/PUT/DELETE, with the CSRF token
Repository access outside a request
Service user: repoinit with forced path system/cq:services/<proj> + set principal ACL
6.5 before principal-based authorization is set up: set ACL for <user>
Navigate or query?
Navigate known paths (getChild, listChildren)
Unbounded search → JCR-SQL2/QueryBuilder backed by a custom lucene index
Periodic or background work
Sling Job (scheduled via JobBuilder.schedule()) — at-least-once, survives pod recycling
Commons Scheduler only for cheap, idempotent, per-pod housekeeping; Adobe states its execution "cannot be guaranteed"
Per-environment values
One .cfg.json with $[env:NAME;default=x] / $[secret:NAME]
A runmode folder (config.publish.prod) when the shape of the config differs, not just a value
Per-site values (API path, feature flag)
Sling Context-Aware Configuration under /conf
OSGi config when the value is global to the environment
Another client only if it sets connect/read timeouts explicitly
2. OSGi services and configuration
@Component(service = PriceService.class) on an impl in a non-exported impl package; config through @Designate(ocd = Config.class); one @Activate @Modified method stores the config in a volatile field. Full sample in references/osgi.md.
Components are singletons: no request or user state in fields. ResourceResolver, Session and SimpleDateFormat are not thread-safe. Static references (the default) restart the component when the dependency changes — keep them; dynamic references must be volatile and are only for optional or multiple services.
Configs are .cfg.json files in ui.config/.../apps/<proj>/osgiconfig/config[.<runmode>]. Runmodes are fixed: author, publish, dev, stage, prod, rde and their combinations; custom runmodes do not exist on Cloud Service. Factory configs are named <PID>~<name>.cfg.json.
@Component(service = Servlet.class)
@SlingServletResourceTypes(resourceTypes = "acme/components/product",
methods = HttpConstants.METHOD_GET, selectors = "prices", extensions = "json")
public class ProductPricesServlet extends SlingSafeMethodsServlet { /* doGet: serialize JSON with Jackson/Gson */ }
A selector + extension URL (/content/acme/p/jcr:content/product.prices.json) respects ACLs and is cacheable; say which Dispatcher filter and cache rule it needs (aem-dispatcher).
Validate selectors, suffix and parameters and return 400/404/405, never 200 with an error body. Mutating requests pass the Granite CSRF filter; the client fetches the token from /libs/granite/csrf/token.json. Never add a path to the CSRF exclusions to silence a 403.
Filters: @SlingServletFilter(scope = SlingServletFilterScope.REQUEST, pattern = "/content/acme/.*") plus an explicit service.ranking; they run on every matching cache miss, so keep them cheap.
4. Resource resolvers and service users
create service user acme-price-sync with forced path system/cq:services/acme
set principal ACL for acme-price-sync
allow jcr:read,rep:write on /content/acme/prices
end
try (ResourceResolver rr = resolverFactory.getServiceResourceResolver(
Map.of(ResourceResolverFactory.SUBSERVICE, "price-sync"))) {
// work, then rr.commit()
} catch (LoginException e) {
LOG.error("Service user mapping missing for sub-service price-sync", e);
}
The repoinit script ships in org.apache.sling.jcr.repoinit.RepositoryInitializer~acme.cfg.json ("scripts": [...]); the mapping in org.apache.sling.serviceusermapping.impl.ServiceUserMapperImpl.amended~acme.cfg.json as "user.mapping": ["acme.core:price-sync=[acme-price-sync]"] (bundle symbolic name : sub-service).
Principal-based ACLs under system/cq:services are the Cloud Service convention (service users tutorial). One sub-service per concern, least privilege.
Prefer the Sling Resource API over JCR. Never close request.getResourceResolver(); never store a resolver in a field; loginAdministrative fails the Cloud Manager quality gate.
Adobe's suggested values are 1 s connect and 5 s read; without them the platform default of 10 s / 60 s ties up request threads. Build the client once in @Activate and close it in @Deactivate for hot paths.
Auth headers from $[secret:] config; cache responses with a TTL; never call out from HTL or per component render. Fixed egress IP or VPN needs Advanced Networking (aem-cloud-manager).
6. Queries and Oak indexes
A traversal warning (Traversed N nodes) is a bug; check every production query with Explain Query (Developer Console → Queries). Use JCR-SQL2 with node type, ISDESCENDANTNODE and property constraints; QueryBuilder with p.limit and p.guessTotal=true, never p.limit=-1 on a request path.
Cloud Service accepts only type="lucene" definitions, deployed from ui.apps/src/main/content/jcr_root/_oak_index/ and named <prefix>.<name>-<productVersion>-custom-<n> (for example acme.article-1-custom-1). The rule, filter.xml/pom.xml settings and a full definition are in references/oak-index-naming.md — every other AEM skill links there.
7. Background work and content mutation
Sling Job for anything that must happen: JobConsumer registered with job.topics, returning JobResult.OK, FAILED (retry) or CANCEL; consumers are idempotent because delivery is at-least-once. Samples and the queue configuration in references/background-work.md.
ResourceChangeListener and EventHandler return in milliseconds: enqueue a job, do no I/O. Workflows are for human steps and audit trails, not a job queue; asset renditions belong to asset microservices (aem-assets).
Publish pods are independent and disposable: repository writes there are lost on recycle, reverse replication is unsupported, the file system is ephemeral. User-generated data goes to an external store. Activate with Replicator.replicate(session, ReplicationActionType.ACTIVATE, path); custom replication agents do not exist on Cloud Service.
Log with SLF4J {} placeholders into error.log only; level per environment through org.apache.sling.commons.log.LogManager.factory.config~acme.cfg.json.
8. Deliverable format
## Target — Cloud Service or 6.5; tiers and runmodes affected
## Design — services (interface + impl), references, background mechanism and why
## Code — Java, .cfg.json per runmode folder, repoinit + service-user mapping, index definition if a query was added
## Security — service user privileges, servlet binding, CSRF, dispatcher filter/cache rule needed
## Ops — env vars/secrets to create, log categories, reindex impact · ## Tests — cases for aem-testing
Checklist
No admin session; every service resolver opened in try-with-resources; none stored in a field
Service user created with forced path system/cq:services/… and set principal ACL, least privilege
Servlet bound by resource type + selector/extension, or the path binding is justified and allow-listed
No request/user state in component fields; dynamic references volatile
Secrets and hostnames come from $[secret:] / $[env:], not Git
Outbound HTTP has connect and read timeouts and a fallback
Every query checked with Explain Query; index is lucene and correctly named
Background work is a Sling Job, idempotent, safe on any pod; nothing long-running on publish
No runtime writes to /apps, /libs or the file system
Log statements parameterized; no PII or secrets logged
Anti-patterns
loginAdministrative or a shared "acme-admin" service user → one sub-service per concern with principal ACLs.
@SlingServletPaths("/bin/acme/…") for a new feature → resource type + selector; keeps ACLs and caching.
@Reference HttpClientFactory → that type is ACS AEM Commons; the product service is HttpClientBuilderFactory.
Commons Scheduler for work that must run once → scheduled Sling Job; publish pods are not clustered, so each pod fires the scheduler.
Index named acme-articles-custom-1 or of type property → acme.articles-1-custom-1, type="lucene".
Long work inside a listener, filter or @Activate → enqueue a job.
Custom log files or System.out on Cloud Service → error.log via SLF4J.
Go deeper
references/osgi.md — full DS component with config, dynamic references, runmode folder layout, Context-Aware Configuration sample.
references/background-work.md — choice table for jobs/schedulers/listeners/workflows, JobConsumer and scheduled-job samples, queue configuration.
references/oak-index-naming.md — the index naming rule, lucene-only constraint, project settings and a complete definition (shared by all AEM skills).
Sibling skills: aem-testing for tests, aem-code-review for reviews, aem-dispatcher for filter and cache rules, aem-cloud-manager for pipelines, env vars and RDE, aem-security for ACL and secret design, aem-performance when the symptom is slowness.
---
name: aem-backend-development
description: >
Write production-grade Adobe Experience Manager back-end Java for AEM as a Cloud Service (6.5 differences noted) — OSGi Declarative Services, runmode configs with env vars and secrets, Sling servlets and filters, service users via repoinit, outbound HTTP with timeouts, queries and custom Oak indexes, Sling Jobs, workflows and replication. Use this whenever the user writes or debugs an OSGi @Component, @Designate/@ObjectClassDefinition config, a .cfg.json in ui.config, $[env:] or $[secret:] values, a SlingSafeMethodsServlet or SlingAllMethodsServlet, @SlingServletResourceTypes, a Sling filter, ResourceResolverFactory, a service user mapping or repoinit script, HttpClientBuilderFactory, QueryBuilder or JCR-SQL2, an _oak_index definition, JobConsumer, a scheduler that runs on every pod, ResourceChangeListener, WorkflowProcess or Replicator, or asks why code fails on Cloud Service or leaks sessions. Also apply it when porting a 6.5 core bundle to Cloud Service. For tests use `aem-testing`.
metadata:
technology: AEM
type: development
---
# AEM Back-end Development
> **Targets:** AEM as a Cloud Service 2026.x (Java 21 runtime, `aem-sdk-api`), AEM 6.5 noted where different · **Verified:** 2026-09 against https://experienceleague.adobe.com/en/docs/experience-manager-cloud-service/content/implementing/developing/development-guidelines
AEM back-end code runs as long-lived OSGi singletons inside an auto-scaled cluster whose pods are recycled at any time. Write every service as if it serves concurrent requests on several pods at once, with an immutable `/apps`, no admin session and no local disk — code written that way also runs on 6.5.
## 1. Decide first
| Question | Default | Change when |
|---|---|---|
| Servlet binding | `@SlingServletResourceTypes` + selector + extension | Path binding (`@SlingServletPaths`) only for a resource-less endpoint you also allow-list in Dispatcher; it bypasses resource ACLs |
| Servlet base class | `SlingSafeMethodsServlet` (GET/HEAD) | `SlingAllMethodsServlet` only for state-changing POST/PUT/DELETE, with the CSRF token |
| Repository access outside a request | Service user: repoinit `with forced path system/cq:services/<proj>` + `set principal ACL` | 6.5 before principal-based authorization is set up: `set ACL for <user>` |
| Navigate or query? | Navigate known paths (`getChild`, `listChildren`) | Unbounded search → JCR-SQL2/QueryBuilder backed by a custom **lucene** index |
| Periodic or background work | **Sling Job** (scheduled via `JobBuilder.schedule()`) — at-least-once, survives pod recycling | Commons `Scheduler` only for cheap, idempotent, per-pod housekeeping; Adobe states its execution "cannot be guaranteed" |
| Per-environment values | One `.cfg.json` with `$[env:NAME;default=x]` / `$[secret:NAME]` | A runmode folder (`config.publish.prod`) when the *shape* of the config differs, not just a value |
| Per-site values (API path, feature flag) | Sling Context-Aware Configuration under `/conf` | OSGi config when the value is global to the environment |
| Outbound HTTP client | `org.apache.http.osgi.services.HttpClientBuilderFactory` (product service, HttpClient 4.x) | Another client only if it sets connect/read timeouts explicitly |
## 2. OSGi services and configuration
- `@Component(service = PriceService.class)` on an impl in a non-exported `impl` package; config through `@Designate(ocd = Config.class)`; one `@Activate @Modified` method stores the config in a `volatile` field. Full sample in `references/osgi.md`.
- Components are singletons: no request or user state in fields. `ResourceResolver`, `Session` and `SimpleDateFormat` are not thread-safe. Static references (the default) restart the component when the dependency changes — keep them; dynamic references must be `volatile` and are only for optional or multiple services.
- Configs are `.cfg.json` files in `ui.config/.../apps/<proj>/osgiconfig/config[.<runmode>]`. Runmodes are fixed: `author`, `publish`, `dev`, `stage`, `prod`, `rde` and their combinations; custom runmodes do not exist on Cloud Service. Factory configs are named `<PID>~<name>.cfg.json`.
```json
{ "endpoint": "$[env:PRICE_ENDPOINT;default=https://api.example.com]",
"apiKey": "$[secret:PRICE_API_KEY]",
"timeout:Integer": 3000 }
```
## 3. Servlets and filters
```java
@Component(service = Servlet.class)
@SlingServletResourceTypes(resourceTypes = "acme/components/product",
methods = HttpConstants.METHOD_GET, selectors = "prices", extensions = "json")
public class ProductPricesServlet extends SlingSafeMethodsServlet { /* doGet: serialize JSON with Jackson/Gson */ }
```
- A selector + extension URL (`/content/acme/p/jcr:content/product.prices.json`) respects ACLs and is cacheable; say which Dispatcher filter and cache rule it needs (`aem-dispatcher`).
- Validate selectors, suffix and parameters and return 400/404/405, never 200 with an error body. Mutating requests pass the Granite CSRF filter; the client fetches the token from `/libs/granite/csrf/token.json`. Never add a path to the CSRF exclusions to silence a 403.
- Filters: `@SlingServletFilter(scope = SlingServletFilterScope.REQUEST, pattern = "/content/acme/.*")` plus an explicit `service.ranking`; they run on every matching cache miss, so keep them cheap.
## 4. Resource resolvers and service users
```
create service user acme-price-sync with forced path system/cq:services/acme
set principal ACL for acme-price-sync
allow jcr:read,rep:write on /content/acme/prices
end
```
```java
try (ResourceResolver rr = resolverFactory.getServiceResourceResolver(
Map.of(ResourceResolverFactory.SUBSERVICE, "price-sync"))) {
// work, then rr.commit()
} catch (LoginException e) {
LOG.error("Service user mapping missing for sub-service price-sync", e);
}
```
- The repoinit script ships in `org.apache.sling.jcr.repoinit.RepositoryInitializer~acme.cfg.json` (`"scripts": [...]`); the mapping in `org.apache.sling.serviceusermapping.impl.ServiceUserMapperImpl.amended~acme.cfg.json` as `"user.mapping": ["acme.core:price-sync=[acme-price-sync]"]` (bundle symbolic name : sub-service).
- Principal-based ACLs under `system/cq:services` are the Cloud Service convention ([service users tutorial](https://experienceleague.adobe.com/en/docs/experience-manager-learn/cloud-service/developing/advanced/service-users)). One sub-service per concern, least privilege.
- Prefer the Sling Resource API over JCR. Never close `request.getResourceResolver()`; never store a resolver in a field; `loginAdministrative` fails the Cloud Manager quality gate.
## 5. Outbound HTTP
```java
@Reference private HttpClientBuilderFactory clientBuilderFactory; // org.apache.http.osgi.services
RequestConfig timeouts = RequestConfig.custom()
.setConnectTimeout(1000).setSocketTimeout(5000).build();
try (CloseableHttpClient client = clientBuilderFactory.newBuilder()
.setDefaultRequestConfig(timeouts).build()) {
// client.execute(new HttpGet(config.endpoint()))
}
```
- Adobe's suggested values are 1 s connect and 5 s read; without them the platform default of 10 s / 60 s ties up request threads. Build the client once in `@Activate` and close it in `@Deactivate` for hot paths.
- Auth headers from `$[secret:]` config; cache responses with a TTL; never call out from HTL or per component render. Fixed egress IP or VPN needs Advanced Networking (`aem-cloud-manager`).
## 6. Queries and Oak indexes
- A traversal warning (`Traversed N nodes`) is a bug; check every production query with Explain Query (Developer Console → Queries). Use JCR-SQL2 with node type, `ISDESCENDANTNODE` and property constraints; QueryBuilder with `p.limit` and `p.guessTotal=true`, never `p.limit=-1` on a request path.
- Cloud Service accepts only `type="lucene"` definitions, deployed from `ui.apps/src/main/content/jcr_root/_oak_index/` and named `<prefix>.<name>-<productVersion>-custom-<n>` (for example `acme.article-1-custom-1`). The rule, `filter.xml`/`pom.xml` settings and a full definition are in `references/oak-index-naming.md` — every other AEM skill links there.
## 7. Background work and content mutation
- Sling Job for anything that must happen: `JobConsumer` registered with `job.topics`, returning `JobResult.OK`, `FAILED` (retry) or `CANCEL`; consumers are idempotent because delivery is at-least-once. Samples and the queue configuration in `references/background-work.md`.
- `ResourceChangeListener` and `EventHandler` return in milliseconds: enqueue a job, do no I/O. Workflows are for human steps and audit trails, not a job queue; asset renditions belong to asset microservices (`aem-assets`).
- Publish pods are independent and disposable: repository writes there are lost on recycle, reverse replication is unsupported, the file system is ephemeral. User-generated data goes to an external store. Activate with `Replicator.replicate(session, ReplicationActionType.ACTIVATE, path)`; custom replication agents do not exist on Cloud Service.
- Log with SLF4J `{}` placeholders into `error.log` only; level per environment through `org.apache.sling.commons.log.LogManager.factory.config~acme.cfg.json`.
## 8. Deliverable format
```
## Target — Cloud Service or 6.5; tiers and runmodes affected
## Design — services (interface + impl), references, background mechanism and why
## Code — Java, .cfg.json per runmode folder, repoinit + service-user mapping, index definition if a query was added
## Security — service user privileges, servlet binding, CSRF, dispatcher filter/cache rule needed
## Ops — env vars/secrets to create, log categories, reindex impact · ## Tests — cases for aem-testing
```
## Checklist
- [ ] No admin session; every service resolver opened in try-with-resources; none stored in a field
- [ ] Service user created `with forced path system/cq:services/…` and `set principal ACL`, least privilege
- [ ] Servlet bound by resource type + selector/extension, or the path binding is justified and allow-listed
- [ ] No request/user state in component fields; dynamic references `volatile`
- [ ] Secrets and hostnames come from `$[secret:]` / `$[env:]`, not Git
- [ ] Outbound HTTP has connect and read timeouts and a fallback
- [ ] Every query checked with Explain Query; index is lucene and correctly named
- [ ] Background work is a Sling Job, idempotent, safe on any pod; nothing long-running on publish
- [ ] No runtime writes to `/apps`, `/libs` or the file system
- [ ] Log statements parameterized; no PII or secrets logged
## Anti-patterns
- **`loginAdministrative` or a shared "acme-admin" service user** → one sub-service per concern with principal ACLs.
- **`@SlingServletPaths("/bin/acme/…")` for a new feature** → resource type + selector; keeps ACLs and caching.
- **`@Reference HttpClientFactory`** → that type is ACS AEM Commons; the product service is `HttpClientBuilderFactory`.
- **Commons `Scheduler` for work that must run once** → scheduled Sling Job; publish pods are not clustered, so each pod fires the scheduler.
- **Index named `acme-articles-custom-1` or of type `property`** → `acme.articles-1-custom-1`, `type="lucene"`.
- **Long work inside a listener, filter or `@Activate`** → enqueue a job.
- **Custom log files or `System.out` on Cloud Service** → `error.log` via SLF4J.
## Go deeper
- `references/osgi.md` — full DS component with config, dynamic references, runmode folder layout, Context-Aware Configuration sample.
- `references/background-work.md` — choice table for jobs/schedulers/listeners/workflows, `JobConsumer` and scheduled-job samples, queue configuration.
- `references/oak-index-naming.md` — the index naming rule, lucene-only constraint, project settings and a complete definition (shared by all AEM skills).
- Sibling skills: `aem-testing` for tests, `aem-code-review` for reviews, `aem-dispatcher` for filter and cache rules, `aem-cloud-manager` for pipelines, env vars and RDE, `aem-security` for ACL and secret design, `aem-performance` when the symptom is slowness.