Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The NetSuite Pro

The NetSuite Pro Logo The NetSuite Pro Logo

The NetSuite Pro Navigation

  • Home
  • About Us
  • Tutorials
    • NetSuite Scripting
    • NetSuite Customization
    • NetSuite Integration
    • NetSuite Advanced PDF Templates
    • NetSuite Reporting & Analytics Guide
    • Real-World NetSuite Examples
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask A Question
  • Home
  • About Us
  • Tutorials
    • NetSuite Scripting
    • NetSuite Customization
    • NetSuite Integration
    • NetSuite Advanced PDF Templates
    • NetSuite Reporting & Analytics Guide
    • Real-World NetSuite Examples
  • Blog
  • Contact Us
Home/ Real-World NetSuite Examples/Building Restart-Safe Map/Reduce Scripts in NetSuite

Building Restart-Safe Map/Reduce Scripts in NetSuite

πŸ’Ό Business Requirement

Your NetSuite Map/Reduce script updates or creates records (e.g., Sales Orders, Invoices, Customers). However, it sometimes fails due to a server restart β€” like a system update or backend crash β€” which causes partial processing and duplicate updates when the script resumes.

You need to ensure:

  • No record is updated twice
  • Processing can resume safely after a restart
  • Your script is idempotent β€” repeatable with no side effects

🚨 Problem: Unprotected Map/Reduce Leads to Duplicate Updates

A basic script without restart-safe logic may update or save records twice if interrupted mid-run. NetSuite does not rollback saved records during server restarts β€” only internal map/reduce state is cleared.

Here’s a simple version that fails on restart:

map: function (context) {
  var soEntry = JSON.parse(context.value);
  var so = record.load({
    type: soEntry.values.recordtype,
    id: context.key
  });
  // Update fields blindly
  so.save();
}

If this script is restarted midway, it will load and save the same Sales Order again β€” resulting in duplicate processing.


βœ… Solution: Make Your Script Restart-Aware (Best Practice)

  1. Add a custom field like custbody_processed_flag on your target record.
  2. Check the field using search.lookupFields() in map() only if context.isRestarted === true.
  3. Only update the record if the flag is false.
  4. Always use context.write() regardless of restart state β€” NetSuite clears stale writes automatically.

🧩 Sample Restart-Safe Map/Reduce Script

/**
 * @NApiVersion 2.0
 * @NScriptType mapreducescript
 */
define(['N/search', 'N/record'], function(search, record) {
  return {
    getInputData: function (context) {
      return search.create({
        type: search.Type.SALES_ORDER,
        filters: [
          ['mainline', 'is', 'T'],
          'AND',
          ['custbody_processed_flag', 'is', 'F'] // Only unprocessed
        ],
        columns: ['recordtype']
      });
    },

    map: function (context) {
      var soEntry = JSON.parse(context.value);
      var alreadyProcessed = false;

      if (context.isRestarted) {
        var lookupResult = search.lookupFields({
          type: soEntry.values.recordtype,
          id: context.key,
          columns: ['custbody_processed_flag']
        });
        alreadyProcessed = lookupResult.custbody_processed_flag === true;
      }

      if (!alreadyProcessed) {
        var so = record.load({
          type: soEntry.values.recordtype,
          id: context.key
        });

        // Update the Sales Order
        so.setValue({ fieldId: 'custbody_processed_flag', value: true });
        so.save();
      }

      context.write(soEntry.values.recordtype, context.key);
    },

    reduce: function (context) {
      context.write(context.key, context.values.length);
    },

    summarize: function (summary) {
      if (summary.isRestarted) {
        log.audit({ title: 'Restart Detected', details: 'Summarize stage was restarted.' });
      }

      var totalUpdated = 0;
      summary.output.iterator().each(function (key, value) {
        log.audit({ title: key + ' updated', details: value });
        totalUpdated += parseInt(value);
        return true;
      });

      log.audit({ title: 'Total Records Updated', details: totalUpdated });
    }
  };
});

πŸ” Best Practices for Restart Safety

βœ… Do❌ Avoid
Use custbody_processed_flag to track updatesUpdating without a flag or marker
Check context.isRestarted to skip processed recordsRelying on getInputData alone to prevent duplicates
Use search.lookupFields() instead of full record load for quick flag checkLoading entire records just to check one value
Keep context.write() outside if-blocksSkipping writes can break reduce stage
Log restart awareness in summarize()Ignoring summary.isRestarted may hide issues

πŸ“Œ Summary

If your Map/Reduce script updates NetSuite records, you must protect it from accidental duplication caused by restarts. This script pattern shows exactly how to:

  • Use a processed flag
  • Check for restarts
  • Ensure idempotent behavior
  • Maintain stability even during server interruptions

This is one of the most underutilized features in SuiteScript β€” and applying it will instantly harden your scripts for production use.

Share
  • Facebook

Leave a ReplyCancel reply

Sidebar

Ask A Question

Stats

  • Questions 6
  • Answers 6
  • Best Answers 0
  • Users 3
  • Popular
  • Answers
  • Rocky

    Issue in running a client script in NetSuite SuiteScript 2.0 ...

    • 1 Answer
  • admin

    How can I send an email with an attachment in ...

    • 1 Answer
  • admin

    How do I avoid SSS_USAGE_LIMIT_EXCEEDED in a Map/Reduce script?

    • 1 Answer
  • admin
    admin added an answer The issue is usually caused by following Wrong script file… September 14, 2025 at 10:33 pm
  • admin
    admin added an answer Steps to send an Invoice PDF by email: define(['N/email', 'N/render',… August 28, 2025 at 3:05 am
  • admin
    admin added an answer This error means your script hit NetSuite’s governance usage limit… August 28, 2025 at 3:02 am

Top Members

Rocky

Rocky

  • 1 Question
  • 22 Points
Begginer
Sophie1022

Sophie1022

  • 0 Questions
  • 20 Points
Begginer
admin

admin

  • 5 Questions
  • 2 Points

Trending Tags

clientscript netsuite scripting suitescript

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Menu

  • Home
  • About Us
  • Tutorials
    • NetSuite Scripting
    • NetSuite Customization
    • NetSuite Integration
    • NetSuite Advanced PDF Templates
    • NetSuite Reporting & Analytics Guide
    • Real-World NetSuite Examples
  • Blog
  • Contact Us

Quick Links

  • NetSuite Scripting
  • NetSuite Customization
  • NetSuite Advanced PDF Template
  • NetSuite Integration
  • NetSuite Reporting & Analytics

Subscribe for NetSuite Insights....

© 2025 The NetSuite Pro. All Rights Reserved