Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

A Spring LDAP batch that reads all accounts from Active Directory returns only 1,000 entries, and under load another service gets connection timeouts to the directory. Explain both problems and the fixes.

The batch stops at 1,000 entries because Active Directory enforces a server-side page size limit, MaxPageSize, which is 1,000 by default; the fix is the paged results control, PagedResultsDirContextProcessor, looping until the server returns an empty cookie. The timeouts come from opening too many unpooled connections with no time limits, so we enable pooling, set connect and read timeouts and validate pooled connections. Referrals, the global catalog port and TLS settings also change what we see and whether connections succeed.

Why this question is asked

Directory problems often look like data problems. A report shows exactly 1,000 users and nobody notices for months, or a login service starts timing out whenever the nightly batch runs. Interviewers ask about these because the causes are specific to how LDAP servers and the JNDI client behave, and the fixes are concrete settings. In this answer, we will look at why the batch is cut at 1,000, write the paged search, see how the size limit exception is handled, fix the connection problems, and cover referrals, the global catalog and TLS.

1Why the Batch Stops at 1,000

Active Directory protects itself from huge searches with a policy called MaxPageSize, set to 1,000 by default. A single search may return at most that many entries; after that, the server stops and reports that the size limit was exceeded. Other directories have similar limits, such as sizelimit in OpenLDAP, often 500.

Notice that the exact number 1,000 is the clue. A real count of accounts is almost never round, so a result of exactly 1,000 or 500 should always make us suspect a limit rather than the data.

2How the Size Limit Exception Is Handled

When the server stops early, the JNDI client raises a SizeLimitExceededException. LdapTemplate has a setting, ignoreSizeLimitExceededException, that decides what happens. In current versions it is true by default, so the template swallows the exception and returns the 1,000 entries it got, which is exactly why the batch silently returned a partial result. Check your version, and set it deliberately.

Java
LdapTemplate template = new LdapTemplate(contextSource);
template.setIgnoreSizeLimitExceededException(false); // fail loudly if a search is cut short
// a search past the limit now throws:
// org.springframework.ldap.SizeLimitExceededException: [LDAP: error code 4 - Sizelimit Exceeded]

For a batch that must read everything, failing loudly is the right default: a missing 30 percent of accounts is worse than a failed job, because nobody notices it.

3Fix 1: Paged Results

The paged results control lets the client ask for the data in pages. The client sends a page size; the server returns a page plus a cookie, an opaque marker of where it stopped; the client sends the cookie back to get the next page, until the server returns an empty cookie. Each page stays under the limit, so the server is happy.

Java
List<Account> all = new ArrayList<>();
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
controls.setReturningAttributes(new String[] {"sAMAccountName", "mail", "userAccountControl"});
PagedResultsDirContextProcessor processor = new PagedResultsDirContextProcessor(500);
SingleContextSource.doWithSingleContext(contextSource, operations -> {
do {
List<Account> page = operations.search("ou=accounts", "(objectClass=user)", controls, mapper, processor);
all.addAll(page); // 500, 500, ... , 137
} while (processor.hasMore()); // the cookie is empty after the last page
return null;
});
// all.size() -> 4637 instead of 1000
Step throughPaged search over one connection
BatchActive Directory
search, page size 500, no cookie
500 entries + cookie c1
search, page size 500, cookie c1
500 entries + cookie c2
... repeat with each cookie
137 entries + empty cookie: done

6 messages in order. Play them, or step through them one at a time.

Notice SingleContextSource.doWithSingleContext. The paging cookie belongs to one connection, so every page must be requested on the same one; with a pool, consecutive calls could use different connections and the server would reject the cookie. Also notice setReturningAttributes: asking only for the attributes we need makes each page much smaller and the batch much faster. For very large results, process each page and drop it instead of collecting everything.

4Fix 2: Pooling, Timeouts and Validation

The second problem is the timeouts in another service. Without pooling, every LDAP operation opens a new TCP connection, does a TLS handshake and binds, then closes. Under load that means hundreds of new connections per second, and the domain controller starts queuing them. Without timeouts, a thread that cannot connect waits for the operating system's TCP timeout, which can be minutes, so threads pile up until the service stops answering.

We fix both on the context source. Pooling reuses authenticated connections, either with Spring LDAP's PoolingContextSource, which is based on Commons Pool, or with the JNDI built-in pool. Timeouts are JNDI environment properties. Validation tests a pooled connection before use, so a connection silently dropped by a firewall after 15 minutes idle is replaced instead of failing a request.

Java
LdapContextSource source = new LdapContextSource();
source.setUrl("ldaps://dc1.corp.example.com:636");
source.setBase("dc=corp,dc=example,dc=com");
source.setUserDn(serviceUserDn);
source.setPassword(serviceUserPassword); // from a secret store, never from source code
source.setBaseEnvironmentProperties(Map.of(
"com.sun.jndi.ldap.connect.timeout", "3000", // ms to open the connection
"com.sun.jndi.ldap.read.timeout", "10000")); // ms to wait for a response
source.afterPropertiesSet();
PoolingContextSource pool = new PoolingContextSource();
pool.setContextSource(source);
pool.setMaxTotal(20); // check your version: older pools use maxActive
pool.setTestOnBorrow(true);
pool.setDirContextValidator(new DefaultDirContextValidator());

With a read timeout, a slow directory now fails a request in 10 seconds instead of holding a thread for minutes, and the batch, using at most a bounded number of pooled connections, no longer starves the other service.

5Referrals, the Global Catalog and TLS

In a forest with several domains, a search in one domain controller may hit entries that live in another domain. The server then returns a referral, a pointer to another server. The JNDI setting java.naming.referral decides whether to follow it, ignore it or throw; with ignore, Spring LDAP can raise a PartialResultException, which LdapTemplate can be told to ignore with setIgnorePartialResultException(true). Following referrals means connecting to other domain controllers, which needs network access and credentials there.

Alternatively, the global catalog on port 3268, or 3269 with TLS, answers for the whole forest but holds only a partial set of attributes. So which port we use changes which entries and which attributes we see, and that difference often explains results that differ between environments.

Finally, use LDAPS on port 636 or StartTLS on 389, never plain LDAP, because a simple bind sends the password in clear text. The directory's CA certificate must be in the JVM trust store, or the connection fails with a PKIX path building error.

6Follow-up questions

Why is a directory a poor fit as a general database?

Directories are optimized for many fast reads of small, rarely changing entries, such as users and groups, and they replicate changes between servers with eventual consistency. They have no joins, no transactions across entries, limited query features and server-side limits like the one we just met. Using LDAP for orders or frequent updates leads to replication delays and complicated code. So we keep identity data there and everything else in a real database, copying the few directory attributes we need.

Could we just raise MaxPageSize on the server?

It is possible but discouraged, because it raises memory use on every domain controller for every client. Paged results are the intended way to read large result sets.

How do we see what the batch really sends?

Enable debug logging for org.springframework.ldap and compare the filters and base DNs with a search run in a tool such as ldapsearch with the same account.

7Conclusion

In this answer, we saw that the batch stopped at exactly 1,000 because of Active Directory's MaxPageSize, and that LdapTemplate's default of ignoring SizeLimitExceededException hid it. We fixed it with PagedResultsDirContextProcessor on a single connection, looping until the cookie is empty. We fixed the timeouts with pooling, connect and read timeouts and validation of pooled connections, and we covered how referrals and the global catalog change which entries we see and why LDAPS with a trusted CA is required.

What to say in the interviewAbout 80 seconds aloud

Open with

There are two separate problems. The batch stops at 1,000 because Active Directory has a server-side limit, MaxPageSize, 1,000 by default, so a single search returns at most that many entries.

Then, if they want more

The client gets a size limit exceeded result, and LdapTemplate ignores that exception by default in current versions, so the job silently returned a partial list.

I would set ignoreSizeLimitExceededException deliberately, false for a batch, and use paged results: a PagedResultsDirContextProcessor with a page size like 500, inside SingleContextSource.doWithSingleContext so every page uses the same connection, looping while hasMore is true until the server sends an empty cookie. I would also request only the attributes I need. The timeouts come from connection handling.

Without pooling every operation opens a new TLS connection and binds, which overloads the domain controller under load, and without timeouts threads wait minutes. So I would enable pooling with PoolingContextSource or the JNDI pool, set com.sun.jndi.ldap.connect.timeout and read.timeout, and validate pooled connections on borrow so firewall-dropped connections are replaced.

I would also check referral settings and whether we query a domain controller or the global catalog on 3268, since that changes which entries we see, and make sure we use LDAPS or StartTLS with the CA in the trust store.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring Boot reference
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A Spring LDAP batch that reads all accounts from Active Directory returns only 1,000...": https://scrivio-interview-library.netlify.app/spring-boot/spring-projects/7d29816d46/