#14958·amplify-js

DataStore.stop() never resolves when called before initial sync is ready

Author: nghiatranhnlCreated Sep 24, 2026Updated Sep 28, 2026
LabelsbugDataStorepending-maintainer-response

Before opening, please confirm:

JavaScript Framework

React Native

Amplify APIs

DataStore, GraphQL API

Amplify Version

v6

Amplify Categories

No response

Backend

None

Environment information

System:
    OS: macOS 26.5.2
    CPU: (8) arm64 Apple M3
    Memory: 16.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.19.6 - ~/.nvm/versions/node/v20.19.6/bin/node
    Yarn: 3.6.4 - <project>/node_modules/.bin/yarn
    npm: 10.8.2 - ~/.nvm/versions/node/v20.19.6/bin/npm
  Browsers:
    Chrome: 153.0.8010.53
    Safari: 26.5.2
  npmPackages:
    @aws-amplify/api:  6.3.17 
    @aws-amplify/api-graphql:  4.7.21 
    @aws-amplify/auth:  6.15.0 
    @aws-amplify/core:  6.13.1 
    @aws-amplify/datastore:  5.0.88 
    @aws-amplify/datastore-storage-adapter: 2.1.49 => 2.1.49 
    @aws-amplify/react-native: 1.1.4 => 1.1.4 
    @azure/core-asynciterator-polyfill: 1.0.2 => 1.0.2 
    @babel/core: ^7.25.2 => 7.28.3 
    @babel/runtime: ^7.25.0 => 7.28.3 (7.29.2)
    @react-native-async-storage/async-storage: 2.2.0 => 2.2.0 
    @react-native-community/netinfo: 11.3.3 => 11.3.3 (11.5.2)
    @react-native/babel-preset: 0.80.2 => 0.80.2 
    @react-native/metro-config: 0.80.2 => 0.80.2 
    aws-amplify: 6.15.5 => 6.15.5 
    buffer: 6.0.3 => 6.0.3 (4.9.2, 5.7.1)
    immer: 10.1.1 => 10.1.1 (9.0.6)
    react: 19.1.0 => 19.1.0 
    react-native: 0.80.2 => 0.80.2 
    react-native-get-random-values: 1.11.0 => 1.11.0 
    react-native-sqlite-storage: 6.0.1 => 6.0.1 
    react-native-url-polyfill: 2.0.0 => 2.0.0 
    rxjs:  7.8.2 
    typescript: 5.0.4 => 5.0.4 
  npmGlobalPackages:
    corepack: 0.34.1
    npm: 10.8.2

Describe the bug

Calling DataStore.stop() while the initial sync is still running (before the Hub emits ready) returns a Promise that never resolves. DataStore stays stuck and cannot be started again until the app is restarted. DataStore.clear() is affected the same way, since it also calls sync.stop().

This is easy to hit on React Native: DataStore.start() resolves before the initial sync finishes, so a user who logs out while their data is still downloading triggers it.

Root cause

In SyncEngine.start() (packages/datastore/src/sync/index.ts), the datastore connectivity event job awaits two Promises. The realtime one listens to onTerminate, the sync-queries one does not:

typescript
this.runningProcesses.add(async onTerminate => {
	// #region GraphQL Subscriptions
	await new Promise<void>((_resolve, _reject) => {
		onTerminate.then(_reject); // ✅ gives up when stop() is called
		// ... resolve on CONNECTED
	});

	// #region Base & Sync queries
	await new Promise<void>((_resolve, _reject) => {
		// ❌ missing: onTerminate.then(_reject);
		this.syncQueriesObservable().subscribe({
			next: message => {
				if (message.type === ControlMessage.SYNC_ENGINE_SYNC_QUERIES_READY) {
					_resolve();
				}
			},
			complete: () => _resolve(),
			error: error => _reject(error),
		});
	});

	// ... doneStarting()
}, 'datastore connectivity event');

stop() cancels the sync queries first, so SYNC_QUERIES_READY / complete / error are never emitted. The Promise above never settles, and runningProcesses.close() waits forever for the datastore connectivity event and sync start jobs. This only happens between the Hub events subscriptionsEstablished and syncQueriesReady, a window that grows with the size of the initial sync.

Proposed fix

Add the same termination handler the realtime Promise already uses:

diff
 // #region Base & Sync queries
 try {
 	await new Promise<void>((_resolve, _reject) => {
+		onTerminate.then(_reject);
 		const syncQuerySubscription =
 			this.syncQueriesObservable().subscribe({

Expected behavior

  • DataStore.stop() resolve quickly, even if the initial sync has not finished and the Hub has not emitted ready.
  • The running initial sync is cancelled.
  • DataStore.start() can be called again in the same runtime without restarting the app.

Reproduction steps

Real-world scenario: we log in with a user that has a lot of data, with fairly large records, so the initial sync takes a long time. While DataStore is still downloading that data, the user logs out.

Since our app is a private project, unfortunately I'm not able to share its source code. Instead, I've put together a minimal example below that follows the same flow we're experiencing. I hope it helps, and I'm happy to provide more details if needed.

Login  → DataStore.start()   → resolves immediately, initial sync keeps running in the background
                               (lots of data ⇒ long sync, no Hub `ready` yet)
Logout → DataStore.stop()    → never resolves ❌
Login  → DataStore.start()   → does not work, DataStore is stuck

Steps:

  1. Use an Amplify CLI backend with any model and conflict detection enabled (required by DataStore), e.g. Post.
  2. Build an app with two buttons (see App.tsx under Code Snippet):
    • Login calls DataStore.start().
    • Logout calls DataStore.stop().
  3. Make the initial sync take a long time, as it does for a user with a lot of large records: seed many large records, or use slowSync.ts under Code Snippet so every sync query fails and is retried.
  4. Tap Login, then tap Logout before the Hub emits ready.
  5. stop() never resolves. The sync start and datastore connectivity event jobs stay pending forever.

With onTerminate.then(_reject); added (see "Proposed fix"), stop() resolves immediately, and tapping Login again works.

Reproduce without AWS: regression test in the amplify-js repo

Add this test to packages/datastore/__tests__/connectivityHandling.test.ts. It uses the existing fake GraphQL service, and DataStore.start() is already called in beforeEach:

typescript
test('stop() resolves while a sync query is still retrying', async () => {
	let syncPostsRequests = 0;
	graphqlService.intercept = (request, next) => {
		if (request.query.includes('syncPosts')) {
			syncPostsRequests++;
			// retryable error, so the initial sync never becomes ready.
			throw {
				data: { syncPosts: null },
				errors: [
					{
						path: ['syncPosts'],
						errorType: 'MappingTemplate',
						message: 'Transformation too large',
					},
				],
			};
		}
		return next();
	};

	// wait until we are in the middle of the initial sync.
	while (syncPostsRequests === 0) {
		await pause(10);
	}

	const result = await Promise.race([
		DataStore.stop().then(() => 'stopped'),
		pause(3000).then(() => 'timed out'),
	]);

	expect(result).toBe('stopped');

	// DataStore should be usable again after stopping.
	graphqlService.intercept = (request, next) => next();
	await DataStore.start();
	await waitForSyncQueriesReady();
});
@aws-amplify/[email protected] source Result
Unmodified ✕ Received: "timed out"; then afterEach calling DataStore.clear() also times out
With onTerminate.then(_reject); ✓ passes (~190 ms)

Code Snippet

The following is a simplified example that reflects the same flow as our app.

src/slowSync.ts:

typescript
// Simulates a long-running initial sync (large dataset, slow network, or an
// AppSync error that DataStore keeps retrying): every `sync*` query fails,
// so the initial sync never reaches `syncQueriesReady` / `ready`.
const originalFetch = global.fetch;

global.fetch = async (input, init) => {
	const body = typeof init?.body === 'string' ? init.body : '';
	const match = body.match(/\b(sync[A-Z]\w*)\s*\(/);

	if (match) {
		const field = match[1];
		return new Response(
			JSON.stringify({
				data: { [field]: null },
				errors: [
					{
						path: [field],
						errorType: 'MappingTemplate',
						message: 'Transformation too large',
					},
				],
			}),
			{ status: 200, headers: { 'Content-Type': 'application/json' } },
		);
	}

	return originalFetch(input, init);
};

App.tsx:

typescript
import 'react-native-get-random-values';
import './src/slowSync';
import React, { useEffect, useState } from 'react';
import { Button, SafeAreaView, ScrollView, Text } from 'react-native';
import { Amplify } from 'aws-amplify';
import { Hub } from 'aws-amplify/utils';
import { DataStore } from 'aws-amplify/datastore';
import amplifyconfig from './src/amplifyconfiguration.json';

Amplify.configure(amplifyconfig);

const SYNC_EVENTS = [
	'subscriptionsEstablished',
	'syncQueriesStarted',
	'syncQueriesReady',
	'ready',
];

export default function App() {
	const [logs, setLogs] = useState<string[]>([]);

	const log = (message: string) => {
		const line = `${new Date().toISOString().slice(11, 23)} ${message}`;
		console.log(line);
		setLogs(prev => [...prev, line]);
	};

	useEffect(
		() =>
			Hub.listen('datastore', ({ payload }) => {
				if (SYNC_EVENTS.includes(payload.event)) {
					log(`Hub: ${payload.event}`);
				}
			}),
		[],
	);

	// "Login": start DataStore. On React Native, start() resolves as soon as
	// local storage is ready, before the initial sync has finished.
	const login = async () => {
		log('login: DataStore.start()');
		await DataStore.start();
		log('start() resolved (initial sync still running)');
	};

	// "Logout": stop DataStore while the initial sync is still running.
	const logout = async () => {
		log('logout: DataStore.stop()');
		const startedAt = Date.now();

		const watchdog = setTimeout(() => {
			// Diagnostics only: list the sync engine jobs that stop() is waiting for.
			const jobs = (DataStore as any).sync?.runningProcesses;
			log(
				`stop() still pending after 10s: state=${jobs?.state} ` +
					`pending=${JSON.stringify(jobs?.pending)}`,
			);
		}, 10_000);

		await DataStore.stop();
		clearTimeout(watchdog);
		log(`stop() resolved in ${Date.now() - startedAt} ms`);
	};

	return (
		<SafeAreaView>
			<Button title="Login (DataStore.start)" onPress={login} />
			<Button title="Logout (DataStore.stop)" onPress={logout} />
			<ScrollView>
				{logs.map((line, i) => (
					<Text key={i}>{line}</Text>
				))}
			</ScrollView>
		</SafeAreaView>
	);
}

Log output

// Put your logs below this line

aws-exports.js

No response

Manual configuration

No response

Additional configuration

No response

Mobile Device

iPhone 16 Pro Max (physical device), iOS Simulator

Mobile Operating System

iOS 26.5 (physical device and simulator)

Mobile Browser

No response

Mobile Browser Version

No response

Additional information and screenshots

Current workarounds:

  • Only call stop() after the Hub emits syncQueriesReady. This forces users with a lot of data to wait for the whole download before they can log out.
  • Patch the library with patch-package using the onTerminate.then(_reject); line above.
  • Wrapping stop() in a timeout does not help: DataStore stays stuck in the stopping state, and the next start() does not work.

Pull request: I have prepared a PR with the onTerminate.then(_reject); fix above and the regression test, plus a small related change so that stop() waits for an in-flight sync page to finish merging before it resolves. I will open it and link it to this issue.