Cloud Native 18 min read

How Nacos Implements Long‑Polling for Dynamic Config Updates

This article explains Nacos Config Center's long‑polling mechanism, detailing both client‑side scheduling and server‑side handling, with code walkthroughs, architecture diagrams, and the flow of configuration change detection and notification.

Top Architect
Top Architect
Top Architect
How Nacos Implements Long‑Polling for Dynamic Config Updates

Today we introduce one principle of Nacos Config Center: the long‑polling mechanism.

For clarity we refer to the Nacos console and registry as the Nacos server, and the business service we write as the Nacos client.

Below is the architecture diagram of Nacos dynamic listening long‑polling mechanism.

ConfigService

is the class provided by the Nacos client for basic configuration operations. We start the source‑level journey of the long‑polling scheduling mechanism from the instantiation of ConfigService.

1. Client long‑polling scheduling mechanism

We start from NacosPropertySourceLocator.locate() and step into the creation of the ConfigService instance.

1.1 Using reflection to instantiate NacosConfigService object

The client’s long‑polling task is started in NacosFactory.createConfigService(), which builds the ConfigService instance.

public static ConfigService createConfigService(Properties properties) throws NacosException {
    //【断点步入】创建 ConfigService
    return ConfigFactory.createConfigService(properties);
}

1.2 NacosConfigService constructor starts long‑polling task

Inside NacosConfigService.NacosConfigService() some remote‑task related properties are set.

1.2.1 Initialize HttpAgent

Classes MetricsHttpAgent and ServerHttpAgent are designed as follows:

1.2.2 Initialize ClientWorker

The ClientWorker.ClientWorker() constructor creates two scheduled thread pools and starts a scheduled task.

In ClientWorker.checkConfigInfo() it checks configuration every 10 seconds.

cacheMap: an AtomicReference<Map<String, CacheData>> storing the cache of listened configurations.

Long‑polling task split: By default each LongPollingRunnable handles 3000 listeners; more requires multiple runnables.

1.3 Checking configuration changes – LongPollingRunnable.run()

The method splits data by taskId from cacheMap, then calls checkLocalConfig() to compare local files under ${user}\nacos\config\. If changes are detected, it triggers notifications.

public void run() {
    List<CacheData> cacheDatas = new ArrayList();
    ArrayList inInitializingCacheList = new ArrayList();
    try {
        //遍历 CacheData,检查本地配置
        Iterator var3 = ((Map)ClientWorker.this.cacheMap.get()).values().iterator();
        while (var3.hasNext()) {
            CacheData cacheData = (CacheData)var3.next();
            if (cacheData.getTaskId() == this.taskId) {
                cacheDatas.add(cacheData);
                try {
                    //检查本地配置
                    ClientWorker.this.checkLocalConfig(cacheData);
                    if (cacheData.isUseLocalConfigInfo()) {
                        cacheData.checkListenerMd5();
                    }
                } catch (Exception var13) {
                    ClientWorker.LOGGER.error("get local config info error", var13);
                }
            }
        }
        //【断点步入 1.3.1】通过长轮询请求检查服务端对应的配置是否发生变更
        List<String> changedGroupKeys = ClientWorker.this.checkUpdateDataIds(cacheDatas, inInitializingCacheList);
        //遍历存在变更的 groupKey,重新加载最新数据
        Iterator var16 = changedGroupKeys.iterator();
        while (var16.hasNext()) {
            String groupKey = (String)var16.next();
            String[] key = GroupKey.parseKey(groupKey);
            String dataId = key[0];
            String group = key[1];
            String tenant = null;
            if (key.length == 3) {
                tenant = key[2];
            }
            try {
                //【断点步入 1.3.2】读取变更配置,这里的 dataId、group 和 tenant 是【1.3.1】里获取的
                String content = ClientWorker.this.getServerConfig(dataId, group, tenant, 3000L);
                CacheData cache = (CacheData)((Map)ClientWorker.this.cacheMap.get()).get(GroupKey.getKeyTenant(dataId, group, tenant));
                cache.setContent(content);
                ClientWorker.LOGGER.info("[{}] [data-received] dataId={}, group={}, tenant={}, md5={}, content={}", ClientWorker.this.agent.getName(), dataId, group, tenant, cache.getMd5(), ContentUtils.truncateContent(content));
            } catch (NacosException var12) {
                String message = String.format("[%s] [get-update] get changed config exception. dataId=%s, group=%s, tenant=%s", ClientWorker.this.agent.getName(), dataId, group, tenant);
                ClientWorker.LOGGER.error(message, var12);
            }
        }
        //触发事件通知
        var16 = cacheDatas.iterator();
        while (true) {
            CacheData cacheDatax;
            do {
                if (!var16.hasNext()) {
                    inInitializingCacheList.clear();
                    //继续定时执行当前线程
                    ClientWorker.this.executorService.execute(this);
                    return;
                }
                cacheDatax = (CacheData)var16.next();
            } while (cacheDatax.isInitializing() && !inInitializingCacheList.contains(GroupKey.getKeyTenant(cacheDatax.dataId, cacheDatax.group, cacheDatax.tenant)));
            cacheDatax.checkListenerMd5();
            cacheDatax.setInitializing(false);
        }
    } catch (Throwable var14) {
        ClientWorker.LOGGER.error("longPolling error : ", var14);
        ClientWorker.this.executorService.schedule(this, (long)ClientWorker.this.taskPenaltyTime, TimeUnit.MILLISECONDS);
    }
}

1.3.1 Check configuration changes – ClientWorker.checkUpdateDataIds()

This method ultimately calls ClientWorker.checkUpdateConfigStr(), which sends a long‑polling request to /v1/cs/configs/listener via MetricsHttpAgent.httpPost(). The request timeout defaults to 30 s.

1.3.2 Read changed configuration – ClientWorker.getServerConfig()

The method calls MetricsHttpAgent.httpGet() to fetch the new configuration from /v1/cs/configs and saves it locally via LocalConfigInfoProcessor.saveSnapshot().

2. Server‑side long‑polling scheduling mechanism

2.1 Server receives request – ConfigController.listener()

The Nacos server processes the client request in the ConfigController class.

It obtains the configurations to listen and computes their MD5. ConfigServletInner.doPollingConfig() starts the long‑polling request.

2.2 Execute long‑polling request – ConfigServletInner.doPollingConfig()

This method encapsulates the long‑polling logic, compatible with short‑polling.

It creates a ClientLongPolling instance and hands it to the scheduler.

2.3 Run scheduled task – ClientLongPolling.run()

The server does not return immediately; if no change, it delays (≈30 s) before responding.

This keeps the connection alive when data does not change within the timeout.

2.4 Listen for configuration change events

2.4.1 Listening LocalDataChangeEvent

When a configuration is modified on the server, a LocalDataChangeEvent is published and listened by LongPollingService.

Before version 1.3.1, LongPollingService.onEvent() handled the event.

After 1.3.1, a Subscriber.onEvent() implementation handles it.

2.4.2 Event handling – DataChangeTask.run()

The task reads the changed configuration and notifies the client.

3. Source code structure summary

3.1 Client long‑polling mechanism

NacosPropertySourceLocator.locate()

creates ConfigService object. NacosFactory.createConfigService() creates the config server. Executors.newScheduledThreadPool() creates thread pools. ClientWorker.checkConfigInfo() checks for changes every 10 s. ClientWorker.checkLocalConfig() checks local configuration files. ClientWorker.checkUpdateDataIds() checks server for updates. ClientWorker.getServerConfig() reads changed configuration. MetricsHttpAgent.httpPost() implements the long‑polling request. MetricsHttpAgent.httpGet() fetches the configuration. LongPollingRunnable.run() runs the scheduled task.

3.2 Server long‑polling mechanism

ConfigController.listener()

receives the request. LongPollingService.addLongPollingClient() adds the client to the queue. ClientLongPolling.run() executes the timed task. Map.put() stores the ClientLongPolling instance. Queue.remove() removes it after response. MD5Util.compareMd5() compares MD5 values. LongPollingService.sendResponse() returns the result. ConfigExecutor.scheduleLongPolling() schedules the task (~29.5 s). ConfigExecutor.executeLongPolling() creates the thread.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaConfiguration Managementlong polling
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.