Home > Articles > Web Development > Perl

Improving Performance with mod_perl

The Apache mod_perl module is a simple method for improving database performance. In this sample chapter, Paul Dubois describes what mod_perl is, how it changes the way Apache handles scripts to make them execute more quickly, and how that will lead to improved performance in getting data from your MySQL server with Apache.
This sample chapter is excerpted from MySQL & Perl for the Web, by Paul Dubois.
Like this article? We recommend

Like this article? We recommend

THE PRIMARY GOAL IN CHAPTER 2,“GETTING CONNECTED—PuttingYour Database on the Web,” was to take care of the basic aspects of getting your MySQL server to work with Apache.The important thing there was just to get data in and out of your databases over the Web, without any particular regard for performance. In this chapter, we’ll consider a simple method for improving performance that can help you throughout the rest of this book: use the Apache mod_perl module. In other words, the chapter isn’t so much about how to write scripts as about how to make them run faster. I’ll describe what mod_perl is and how it changes the way Apache handles scripts to make them execute more quickly.Then we’ll see what configuration changes are necessary for using mod_perl and discuss some guidelines for making sure your scripts run properly.

For more information about mod_perl, see Appendix B,“References and Further Reading.” You’ll probably want to consult the mod_perl Guide as a general reference. Several other mod_perl documents make informative reading, too.

What mod_perl Is and How It Works

When Apache receives a request for a static HTML file, it can serve the request directly by opening the file and writing it out over the network to the client.This is not true for programs, such as the Perl cgi-bin scripts we wrote in Chapter 2.Those scripts aren’t processed by Apache itself. Instead, Apache starts up Perl as an external process and returns its output to the requesting client.This works well for extending Apache’s capabilities, but invoking an external program taxes the Web server host and also introduces some delay into serving the request.This overhead is incurred repeatedly as script requests arrive because Apache starts up a new Perl process to handle each one.

An alternative to running scripts using external processes is to make the script handler part of Apache itself. In the case of Perl scripts, we can use the mod_perl module to embed the Perl interpreter into Apache.The result is that Apache gains the capability to execute Perl scripts directly.This approach has several advantages:

  • Apache can execute Perl scripts more quickly because it need not start up or wait for standalone external processes.

  • A given Apache process can serve many script requests because it doesn’t terminate when a script finishes; it just waits for the next request.This allows Apache to perform caching for scripts that are requested repeatedly, which results in a further performance improvement. (The script-execution process involves examining the script and compiling it to an internal form, and then running that form.When Perl runs as part of Apache, the compiled script remains loaded in memory and is immediately available for execution. It need not be recompiled if the server receives another request for it.)

  • Because the Perl interpreter doesn’t just exit when the script terminates the way it does when Perl is executed as a standalone process, the script-execution environment persists across scripts.This makes possible some things that can’t be done when scripts are executed individually by independent Perl processes. One of these is persistent database connections (connections to a database server that can be shared over successive scripts, minimizing overhead for setup and tear-down).

These benefits do come at a price, of course.There are also some disadvantages to using mod_perl:

  • Apache installation and configuration becomes more involved.

  • The script-execution environment persists across scripts. (Yes, I included this in the preceding list of advantages, but persistence of the Perl interpreter’s internal state also can cause problems if a script is a bad citizen that contaminates the environment of its successors.) Such scripts require some tweaking to behave better.

  • Embedding the Perl interpreter into Apache causes httpd processes to become larger and take more memory.You may find it prudent or necessary to perform some configuration tuning.

  • mod_perl scripts always run under the user and group IDs of the httpd process. You can’t execute them with the privileges of another user or group using the suEXEC mechanism the way you can with standalone scripts.

I’ve listed more disadvantages than advantages, which you may find alarming. However, most of the disadvantages are one-time issues. Apache configuration is more complicated with mod_perl, but after you get things set up the way you want them, you usually can leave your configuration alone. A script that needs some modification to run as a good citizen under mod_perl generally needs to be fixed once, not multiple times.

The benefits, on the other hand, are continuous. Having scripts run faster with mod_perl than when executed as standalone programs is a benefit you enjoy for as long as you continue to use Apache.The amount of improvement varies from site to site, but the mod_perl Guide indicates that developers report scripts running anywhere from 2 to 20 times faster than the equivalent standalone versions. See Appendix B for other reports of user experiences.

Should You Use mod_perl?

Now, having made an effort to convince you that mod_perl is a good thing, allow me to point out that you do not have to use it if you don’t want to. Indeed, if you run a low-traffic site, performance may be adequate as is, response time for clients may be perfectly satisfactory, and you may never experience any compelling reason to use mod_perl. If you don’t want to deal with mod_perl now, just skip ahead to the next chapter. If your site’s activity increases, however, you may find performance becomes an issue about which to be concerned. In that case, you can always return to this chapter and reconfigure Apache for mod_perl when you need it.

If you decide to use mod_perl and do find that it’s useful (as I expect you will), there are other Apache modules you may want to consider. Perl isn’t the only language that can be embedded into Apache as a module; languages such as PHP, Python, Ruby, and Java also can be used in module form for writing Web scripts, with advantages similar to those offered by mod_perl.

If You Are Not Using mod_perl

You should know one thing about this chapter even if you decide to skip it for now: Most of the rest of this book assumes you’ll run your scripts under mod_perl. You can recognize such scripts, because they’ll be located in the cgi-perl directory, not in cgi-bin. To use any such script in standalone fashion (assuming it doesn’t require mod_perl, of course), just put it in your cgi-bin directory and adjust the URL accordingly.

Other Uses for mod_perl

As described thus far, mod_perl is a means for improving performance of Perl scripts on a Web site, and in fact, that’s the main reason we use it in this book. mod_perl actually is more than that, however, and the performance boost can be viewed as something of a side effect of its primary purpose.

Apache is written in C and provides a C application programming interface (API). Developers can extend Apache’s capabilities by writing modules in C that communicate through that API. But not everybody wants to write C code.This is where mod_perl comes in. Its principal function is to provide an alternative to writing in C by mapping the Apache API onto a Perl API so that you can extend Apache by writing Perl programs.That’s why mod_perl embeds the Perl interpreter into Apache—it provides a bridge between the Apache C API and programs written in Perl.The primary effect of this is to make Apache internals available through the Perl language. The secondary side effect (the one we’re actually more interested in here) is that because Perl is available immediately and has already been started up, Perl scripts execute significantly faster.

Perl programs that exploit the Perl API can do some clever things. For example, packages such as Embperl, ePerl, and Mason provide you with the ability to write HTML pages that contain embedded Perl code.They use the Perl API to access Apache’s page-processing mechanisms, which allows them to look for bits of embedded code, run the Perl interpreter to evaluate the code, and use the results in producing the page. A related module, AxKit, uses mod_perl to process XML pages. mod_perl allows AxKit to combine the power of the Apache API with Perl’s XML support to transform XML pages containing embedded Perl into a variety of formats. From the same XML source, for example, you can produce an HTML page for browser display, a printer-friendly version for hard copy, or a minimal-text version for handheld wireless devices.

Alternatives to mod_perl

mod_perl isn’t the only mechanism available for speeding up Perl script execution. Others, such as FastCGI and VelociGen, can be used instead of mod_perl or in tandem with it.You can configure Apache to use mod_perl for some scripts and FastCGI or VelociGen for others. For more information, visit www.fastcgi.com and www.velocigen.com.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020